openclaw-code-agent 4.3.8 â 4.4.1
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 +11 -8
- package/dist/index.js +195 -190
- package/openclaw.plugin.json +9 -7
- package/package.json +7 -4
- package/skills/code-agent-orchestration/SKILL.md +2 -1
package/dist/index.js
CHANGED
|
@@ -1,35 +1,38 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}var
|
|
3
|
-
`)}}function
|
|
4
|
-
${
|
|
5
|
-
`)}async handleLine(e){let r=zw(e);r&&await Jw(r,{pending:this.pending,onNotification:this.onNotification,onRequest:this.onRequest,respond:n=>this.write(n)})}flushPending(e){for(let[r,n]of this.pending)clearTimeout(n.timer),n.reject(e),this.pending.delete(r)}}});function ce(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function be(t,e,r){for(let n of e){let o=t?.[n];if(typeof o!="string")continue;let i=r?.trim===!1?o:o.trim();if(i)return i}}function Qw(t){return t instanceof Error?t.message:String(t)}function Bm(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function xr(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>xr(r)).join("");let e=ce(t);if(!e)return"";for(let r of["delta","text","content","message","input","output","parts"]){let n=xr(e[r]);if(n)return n}for(let r of["item","turn","thread","response","result","data"]){let n=xr(e[r]);if(n)return n}return""}function $o(t){let e=ce(t);if(!e)return{};let r=ce(e.thread)??ce(e.session),n=ce(e.turn)??ce(e.run),o=ce(e.item),i=ce(e.serverRequest);return{threadId:be(e,["threadId","thread_id","conversationId","conversation_id"])??be(r,["id","threadId","thread_id","conversationId"]),runId:be(e,["turnId","turn_id","runId","run_id"])??be(n,["id","turnId","turn_id","runId","run_id"]),requestId:be(e,["requestId","request_id","serverRequestId"])??be(i,["id","requestId","request_id"]),itemId:be(e,["itemId","item_id"])??be(o,["id","itemId","item_id"])}}function Hi(t,e,r=0){if(r>6)return;if(Array.isArray(t)){for(let i of t){let a=Hi(i,e,r+1);if(a)return a}return}let n=ce(t);if(!n)return;let o=be(n,e);if(o)return o;for(let i of Object.values(n)){let a=Hi(i,e,r+1);if(a)return a}}function Mo(t){return{threadId:$o(t).threadId,cwd:Hi(t,["cwd","workdir","directory"])}}function Wm(t){let e=t?.trim();return!!(e&&/[/\\]worktrees[/\\][^/\\]+[/\\][^/\\]+/.test(e))}function Um(t){let e=t?.trim();if(!e)return;let r=e.split(/[/\\]+/).filter(Boolean),n=r.lastIndexOf("worktrees");if(!(n<0||n+1>=r.length))return r[n+1]}function zi(t){let e=ce(t);if(!e)return;let r=ce(e.item)??e;return be(r,["id","itemId","item_id","messageId","message_id"])}function Yw(t,e=!1){let r=ce(t);if(!r)return"";let n=ce(r.item)??r;return be(n,["type"])?.toLowerCase()!=="agentmessage"?"":e?xr(n):be(n,["text"],{trim:!1})??xr(n)}function Km(t,e){let r=t.trim().toLowerCase();return r==="item/agentmessage/delta"?{mode:"delta",text:xr(e),itemId:zi(e)}:r==="item/completed"?{mode:"snapshot",text:Yw(e),itemId:zi(e)}:{mode:"ignore",text:""}}function jm(t){return{itemId:zi(t),delta:xr(t)}}function Gm(t){let e=ce(t),r=ce(e?.plan),o=(Array.isArray(e?.plan)?e.plan:Array.isArray(r?.steps)?r.steps:[]).map(i=>{let a=ce(i),u=be(a,["step","title","text"]);if(!u)return null;let p=be(a,["status"])?.toLowerCase()??"pending";return{step:u,status:p==="inprogress"||p==="in_progress"?"inProgress":p==="completed"?"completed":"pending"}}).filter(Boolean);return{explanation:be(r,["explanation"])??be(e,["explanation"]),steps:o}}function Vm(t){let e=ce(t);if(!e)return{};let r=ce(e.item)??e;return be(r,["type"])?.toLowerCase()!=="plan"?{}:{itemId:zi(r),text:be(r,["text"],{trim:!1})??xr(r)}}function Hm(t,e){let r=t.trim().toLowerCase();if(r==="turn/failed")return"failed";if(r==="turn/cancelled")return"interrupted";let n=ce(e)??{},o=ce(n.turn)??n,i=be(o,["status"])?.toLowerCase();return i==="failed"?"failed":i==="interrupted"||i==="cancelled"?"interrupted":"completed"}function zm(t,e){let r=ce(e)??{},n=ce(r.turn)??r,o=ce(n.error)??ce(r.error);if(o)return be(o,["message","text","summary","reason"])}function Zw(t,e){let r=Qw(t).toLowerCase();return r.includes("method not found")||r.includes("unknown method")?!0:r.includes("unknown variant")?e?r.includes(`unknown variant \`${e.toLowerCase()}\``):!0:!1}function ev(t){return Xw.has(t.trim().toLowerCase())}function tv(t){let e=ce(t);return e?!!be(e,["threadId","thread_id"]):!1}async function Oo(t){if(t.payloads.length===0)throw new Error(`codex app server request skipped: no payloads for ${t.methods.join(", ")||"<none>"}`);let e;for(let r of t.methods)for(let n of t.payloads){if(ev(r)&&!tv(n))throw new Error(`codex app server request missing threadId: ${r}`);try{return await t.client.request(r,n,t.timeoutMs)}catch(o){if(e=o,!Zw(o,r))continue}}throw e instanceof Error?e:new Error(String(e))}function Jm(t){let e={cwd:t.cwd};return t.model?.trim()&&(e.model=t.model.trim()),t.reasoningEffort?.trim()&&(e.reasoningEffort=t.reasoningEffort.trim()),t.fastMode===!0&&(e.service_tier="fast"),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim()),[e]}function Qm(t){let e={threadId:t.threadId,persistExtendedHistory:!1};return t.model?.trim()&&(e.model=t.model.trim()),t.reasoningEffort?.trim()&&(e.reasoningEffort=t.reasoningEffort.trim()),t.fastMode===!0&&(e.service_tier="fast"),t.cwd?.trim()&&(e.cwd=t.cwd.trim()),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim()),[e]}function rv(t){return[{type:"text",text:t}]}function nv(t,e,r,n){let o=e?.trim(),i=r?.trim(),a=n?.trim();if(t!=="plan")return o||i||a?{mode:"default",settings:{...o?{model:o}:{},...i?{reasoningEffort:i}:{},developerInstructions:a??null}}:void 0;if(!(!o&&!i&&!a))return{mode:"plan",settings:{...o?{model:o}:{},...i?{reasoningEffort:i}:{},developerInstructions:a??null}}}function Ym(t){let e={threadId:t.threadId,input:rv(t.prompt)};t.model?.trim()&&(e.model=t.model.trim()),t.fastMode===!0&&(e.service_tier="fast"),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim());let r=nv(t.permissionMode??"default",t.model,t.reasoningEffort,t.systemPrompt);return r?[{...e,collaborationMode:r}]:[e]}function Zm(t){return[{threadId:t.threadId,turnId:t.turnId}]}function ov(t){let e=ce(t);if(!e)return[];let r=e.options??e.choices??e.availableDecisions??e.decisions;return Array.isArray(r)?r.map(n=>typeof n=="string"?n.trim():be(ce(n),["label","title","text","value","name","id"])??"").filter(Boolean):[]}function iv(t){let e=t.trim().toLowerCase();return e.includes("session")?"acceptForSession":/cancel|abort|stop/.test(e)?"cancel":/deny|decline|reject|block|no/.test(e)?"decline":/approve|allow|accept|yes/.test(e)?"accept":t.trim()}function Xm(t,e,r){let n=t.trim().toLowerCase(),o=ov(r),i=Hi(r,["question","prompt","message","text","summary","reason"])??void 0,a=n.includes("requestapproval"),u=a?o.map(p=>({kind:"approval",label:p,decision:iv(p),responseDecision:p})):o.map(p=>({kind:"option",label:p,value:p}));return{requestId:e,kind:a?"approval":"question",promptText:i,options:o,actions:u,allowsFreeText:!0}}function ec(t){let e=t.trim().toLowerCase();return e.includes("requestuserinput")||e.includes("requestapproval")}function sp(t,e){let r=t==="bypassPermissions"?"never":e?.trim()||"never";return{approvalPolicy:r,sandbox:r==="never"?"danger-full-access":void 0}}var Xw,tc=De(()=>{Xw=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function rc(t){return t instanceof Error?t.message:String(t)}function dv(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return String(t);let e=t;return typeof e.message?.content=="string"?e.message.content:typeof e.text=="string"?e.text:String(t)}var sv,rn,av,uv,pv,Ji,nc=De(()=>{qm();ip();tc();sv="1.0",rn=6e4,av="OPENCLAW_CODEX_APP_SERVER_COMMAND",uv="OPENCLAW_CODEX_APP_SERVER_ARGS",pv="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";Ji=class{constructor(e={}){this.deps=e}deps;name="codex";backendKind="codex-app-server";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!0,nativePlanArtifacts:!0,worktrees:"native-restore"};launch(e){let r={command:process.env[av]?.trim()||"codex",args:Bm(process.env[uv]),requestTimeoutMs:Number.parseInt(process.env[pv]??String(rn),10)||rn},n=this.deps.createClient?.(r)??new Vi(r.command,r.args,r.requestTimeoutMs),o=new Ln,i=e.resumeSessionId,a,u=e.backendRef?.worktreePath,p=e.backendRef?.worktreeId,d=e.permissionMode??"default",l,m=0,c="",h=[],y,k=new Map,S=new Set,x=ne=>{let j=ne?.trim();if(!j)return;let H=e.originalWorkdir?.trim()||e.cwd.trim();e.worktreeStrategy&&e.worktreeStrategy!=="off"&&j!==H&&Wm(j)&&(u=j,p=Um(j))},R=()=>{i&&o.enqueue(qi({kind:"codex-app-server",conversationId:i,...a?{runId:a}:{},...p?{worktreeId:p}:{},...u?{worktreePath:u}:{}}))};n.setNotificationHandler(async(ne,j)=>{let H=ne.trim().toLowerCase(),Ce=$o(j),Lt=Mo(j);if(Ce.threadId&&i&&Ce.threadId!==i)return;if(Ce.threadId&&(i=Ce.threadId),Ce.runId&&(a=Ce.runId),x(Lt.cwd),(Ce.threadId||Ce.runId||Lt.cwd)&&R(),H==="serverrequest/resolved"){l&&(o.enqueue(Fn(l.requestId)),l=void 0);return}if(H==="turn/plan/updated"){let tt=Gm(j);c=tt.explanation??c,tt.steps.length>0&&(h=tt.steps);return}if(H==="item/plan/delta"){let tt=jm(j);if(tt.itemId&&tt.delta){let Sr=k.get(tt.itemId)??"";k.set(tt.itemId,`${Sr}${tt.delta}`)}return}if(H==="item/completed"){let tt=Vm(j);if(tt.text?.trim()){let Sr={explanation:c||void 0,steps:h,markdown:tt.text.trim()};o.enqueue(Ui(Sr,!0));return}}let ve=Km(H,j);if(ve.mode==="delta"&&ve.text){ve.itemId&&S.add(ve.itemId),o.enqueue(Eo(ve.text));return}ve.mode==="snapshot"&&ve.text&&(!ve.itemId||!S.has(ve.itemId))&&o.enqueue(Eo(ve.text)),(H==="turn/completed"||H==="turn/failed"||H==="turn/cancelled")&&y&&(y.method=ne,y.params=j,y.resolve())}),n.setRequestHandler(async(ne,j)=>{if(!ec(ne))return{};let H=$o(j),Ce=Mo(j);if(H.threadId&&i&&H.threadId!==i)return{};H.threadId&&(i=H.threadId),H.runId&&(a=H.runId),x(Ce.cwd),(H.threadId||H.runId||Ce.cwd)&&R();let Lt=H.requestId??`${i??"codex"}-${Date.now().toString(36)}`,ve=Xm(ne,Lt,j),tt=ne.trim().toLowerCase(),Sr=ve.options,_i=ve.actions??[],Iw=await new Promise(xw=>{l={requestId:Lt,methodLower:tt,state:ve,options:Sr,actions:_i,resolveResponse:xw},o.enqueue(Wi(ve))});return l=void 0,o.enqueue(Fn(Lt)),Iw});let $=async()=>{await n.connect(),await n.request("initialize",{protocolVersion:sv,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},rn),await n.notify("initialized",{})},C=async()=>{let ne=sp(d,e.codexApprovalPolicy);if(i){let Ce=await Oo({client:n,methods:["thread/resume"],payloads:Qm({threadId:i,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,approvalPolicy:ne.approvalPolicy,sandbox:ne.sandbox}),timeoutMs:rn}),Lt=Mo(Ce);i=Lt.threadId??i,x(Lt.cwd),R();return}let j=await Oo({client:n,methods:["thread/start","thread/new"],payloads:Jm({cwd:e.cwd,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,approvalPolicy:ne.approvalPolicy,sandbox:ne.sandbox}),timeoutMs:rn}),H=Mo(j);if(i=H.threadId,!i)throw new Error("Codex App Server did not return a thread id.");x(H.cwd),R()},xe=async ne=>{await C(),o.enqueue(Bi()),m+=1,c="",h=[],k.clear(),S.clear();let j="",H,Ce,Lt=new Promise(ve=>{Ce=ve});y={resolve:Ce};try{let ve=sp(d,e.codexApprovalPolicy),tt=await Oo({client:n,methods:["turn/start"],payloads:Ym({threadId:i,prompt:ne,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,systemPrompt:e.systemPrompt,permissionMode:d,approvalPolicy:ve.approvalPolicy,sandbox:ve.sandbox}),timeoutMs:rn}),Sr=$o(tt);Sr.runId&&(a=Sr.runId,R()),await Lt,j=y?.method??"turn/failed",H=y?.params;let _i=Hm(j,H);o.enqueue(tn({success:_i==="completed",outcome:_i,duration_ms:0,total_cost_usd:0,num_turns:m,result:zm(j,H),session_id:i}))}catch(ve){o.enqueue(tn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:m,result:rc(ve),session_id:i??""}))}finally{y=void 0}},kr=async ne=>l?(l.methodLower.includes("requestapproval")?l.resolveResponse({decision:ne.trim()||"decline"}):l.resolveResponse({text:ne.trim()}),!0):!1,or=async ne=>{let j=l;if(!j)return!1;let H=j.actions[ne];if(H?.kind==="approval")return j.resolveResponse({decision:H.responseDecision,...H.proposedExecpolicyAmendment?{proposedExecpolicyAmendment:H.proposedExecpolicyAmendment}:{}}),!0;let Ce=j.options[ne];return Ce?(j.methodLower.includes("requestapproval")?j.resolveResponse({decision:Ce}):j.resolveResponse({option:Ce,index:ne}),!0):!1},Cm=typeof e.prompt=="string"?(async function*(){yield{type:"user",text:e.prompt,session_id:e.resumeSessionId??""}})():e.prompt;return(async()=>{try{await $();for await(let ne of Cm){let j=dv(ne).trim();!j||await kr(j)||await xe(j)}}catch(ne){o.enqueue(tn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:m,result:rc(ne),session_id:i??e.resumeSessionId??""}))}finally{await n.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(ne){d=ne,o.enqueue(Ki(ne))},async submitPendingInputOption(ne){return or(ne)},async submitPendingInputText(ne){return kr(ne)},async interrupt(){!i||!a||await Oo({client:n,methods:["turn/interrupt"],payloads:Zm({threadId:i,turnId:a}),timeoutMs:rn}).catch(()=>{})}}}buildUserMessage(e,r){return{type:"user",text:e,session_id:r}}}});function oc(t){ap.set(t.name,t)}function _o(t){let e=ap.get(t);if(!e)throw new Error(`Unknown agent harness: "${t}". Available: ${[...ap.keys()].join(", ")}`);return e}function ic(){return _o(dt())}var ap,up=De(()=>{Nm();nc();Je();ap=new Map;oc(new ji);oc(new Ji)});function q(t){return t.backendRef?.conversationId??t.harnessSessionId}function ke(t){return t.id??t.sessionId??t.name??q(t)??t.harnessSessionId}function lv(t){return t.harnessSessionId}function lt(t){let e=[ke(t),q(t),lv(t)].filter(r=>!!r);return[...new Set(e)]}function pp(t){return t.harnessName??t.persistedHarness??dt()}function Do(t){if(t.backendRef?.kind==="codex-app-server")return"native-restore";try{return _o(pp(t)).capabilities.worktrees}catch{return"plugin-managed"}}function dp(t){return t==="native-execution"}function Qi(t){return t==="native-restore"}function mv(t){return!!(t.backendRef?.worktreePath||t.backendRef?.worktreeId)}function mt(t){let e=Do(t);return(dp(e)||Qi(e))&&mv(t)}var Ee=De(()=>{Je();up()});import{execFileSync as je}from"child_process";import*as cs from"fs";import{tmpdir as Nv}from"os";import{dirname as Tc,join as qv}from"path";function Bv(t){try{return je("git",["rev-parse","--show-toplevel"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function fs(t){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(K.worktreeDir)return K.worktreeDir;if(t){let e=Bv(t);if(e)return qv(e,".worktrees")}return Nv()}function Rc(t){return t.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function gs(t){try{let e=je("git",["-C",t,"rev-parse","--git-common-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e&&e.endsWith("/.git")?Tc(e):void 0}catch{return}}function Wv(){if(ls!==void 0)return ls;try{return je("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ls=!0,!0}catch{return ls=!1,!1}}function Pr(){if(ms!==void 0)return ms;try{return je("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ms=!0,!0}catch{return ms=!1,!1}}function gp(t){if(!Wv())return!1;try{return je("git",["rev-parse","--git-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Cc(t){try{let e=Kv(t);if(!e)return console.warn(`[worktree] Failed to resolve free-space probe path for ${fs(t)}`),!0;let r=cs.statfsSync(e),n=r.bavail*r.bsize;return jv(n)}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function qo(t,e){try{return je("git",["-C",t,"rev-parse","--verify",e],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Uv(t){let e=t;for(;;){if(cs.existsSync(e))return e;let r=Tc(e);if(r===e)return;e=r}}function Kv(t){return Uv(fs(t))}function jv(t){return t>=104857600}function wr(t){let e=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(e)return e;try{let n=je("git",["-C",t,"rev-parse","--abbrev-ref","origin/HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().replace(/^origin\//,"");if(n)return n}catch{}try{return je("git",["-C",t,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return je("git",["-C",t,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{return"main"}}function hs(t){try{let r=je("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r==="HEAD"){console.warn(`[worktree] Worktree ${t} is in detached HEAD state \u2014 cannot determine branch name`);return}return r||void 0}catch{return}}function Bo(t,e,r){try{let n=je("git",["-C",t,"rev-list","--count",`${r}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return parseInt(n.trim(),10)>0}catch{return!1}}function Ec(t,e,r){try{let n=je("git",["-C",t,"rev-list","--left-right","--count",`${e}...${r}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),[o,i]=n.split(/\s+/);return{ahead:parseInt(o??"0",10)||0,behind:parseInt(i??"0",10)||0}}catch{return}}function $c(t,e,r){try{return je("git",["-C",t,"merge-base","--is-ancestor",e,r],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Mc(t,e,r){try{let n=je("git",["-C",t,"merge-tree","--write-tree",r,e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=je("git",["-C",t,"rev-parse",`${r}^{tree}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return!!n&&n===o}catch{return!1}}function Jt(t,e){try{return je("git",["-C",t,"branch","-D",e],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(r){return console.warn(`[worktree] Failed to delete branch ${e}: ${r instanceof Error?r.message:String(r)}`),!1}}function Oc(t,e){if(e)return e;let r;try{r=je("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}try{let n=je("git",["-C",t,"remote","get-url","upstream"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n&&n!==r){let o=n.match(/[:/]([^/]+\/[^/]+?)(?:\.git)?$/);if(o)return o[1]}}catch{}}var ls,ms,Wo=De(()=>{Je()});import{execFileSync as Un}from"child_process";import{appendFileSync as Gv,existsSync as Lc,mkdirSync as _c,readFileSync as Vv,rmSync as hp}from"fs";import{relative as Hv,sep as Dc}from"path";function zv(t,e){return!!(t&&typeof t=="object"&&"code"in t&&t.code===e)}function Jv(t){try{return Un("git",["-C",t,"rev-parse","--show-toplevel"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function Qv(t,e){let r=Jv(t);if(!r)return;let n=Hv(r,e);if(!n||n.startsWith("..")||n.includes(`..${Dc}`))return;let o=`${r}/.git/info/exclude`,i=`${n.split(Dc).join("/").replace(/\/$/,"")}/`;try{let a=Lc(o)?Vv(o,"utf-8"):"";a.split(/\r?\n/).map(p=>p.trim()).some(p=>p===i||p===`/${i}`)||Gv(o,`${a.endsWith(`
|
|
6
|
-
`)
|
|
1
|
+
var rl=Object.defineProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var ol=(t,e)=>{for(var n in e)rl(t,n,{get:e[n],enumerable:!0})};function yt(t,e){return e?{...e,...t}:t}function il(t){return{...t,[so]:!0}}function sl(t){return{const:t,type:typeof t}}var so,m,X=j(()=>{so=Symbol("optionalSchema");m={Object(t,e){let n=Object.entries(t).filter(([,o])=>!o[so]).map(([o])=>o),r=Object.fromEntries(Object.entries(t).map(([o,i])=>{let{[so]:s,...a}=i;return[o,a]}));return{...e,type:"object",...n.length>0?{required:n}:{},properties:r}},String(t){return yt({type:"string"},t)},Number(t){return yt({type:"number"},t)},Boolean(t){return yt({type:"boolean"},t)},Array(t,e){return yt({type:"array",items:t},e)},Literal:sl,Union(t,e){return yt({anyOf:t},e)},Optional:il}});function ao(t){v=t}function lo(t){B=t}var v,B,O=j(()=>{v=null,B=null});function $i(t){let e=t.chatId.trim(),n=t.topicId.trim();return!/^-?\d+$/.test(e)||!/^\d+$/.test(n)?null:`${e}:topic:${n}`}function pl(t){let e=t.conversationId.trim(),n=e.match(/^(-?\d+):topic:(\d+)$/i);if(n?.[1]&&n[2]){let i=$i({chatId:n[1],topicId:n[2]});return i?{chatId:n[1],topicId:n[2],canonicalConversationId:i}:null}if(!/^\d+$/.test(e))return null;let r=t.parentConversationId?.trim();if(!r||!/^-?\d+$/.test(r))return null;let o=$i({chatId:r,topicId:e});return o?{chatId:r,topicId:e,canonicalConversationId:o}:null}function cl(t){if(!t)return;let e=t.match(/^agent:[^:]+:discord:(direct|dm|channel|group):/i);if(!e?.[1])return;let n=e[1].toLowerCase();return n==="direct"||n==="dm"?"user":"channel"}function ml(t,e){if(!/^\d+$/.test(t))return t;let n=cl(e);return n?`${n}:${t}`:`channel:${t}`}function fl(t){if(!(!t?.provider||!t.target)&&!(t.provider==="system"||t.target==="system"))return t.accountId?`${t.provider}|${t.accountId}|${t.target}`:`${t.provider}|${t.target}`}function gl(t){let e=t.toLowerCase(),n=[":thread:",":topic:"];for(let r of n){let o=e.lastIndexOf(r);if(o===-1)continue;let i=t.slice(0,o).trim(),s=t.slice(o+r.length).trim()||void 0;return{id:i||t,threadId:s}}return{id:t}}function hl(t){let e=t?.trim();if(!e)return;let n=e.split(":").filter(Boolean);if(n[0]?.trim().toLowerCase()==="agent")for(let r=2;r<=n.length-3;r+=1){let o=n[r]?.trim().toLowerCase();if(!o||!ul.has(o))continue;let i=n[r+1]?.trim().toLowerCase(),s=n.slice(r+2).join(":").trim();if(!(!i||!s))return{provider:o,kind:i,rawId:s}}}function Sl(t,e=pl){try{return e({conversationId:t})}catch{return null}}function uo(t){return{provider:"system",target:"system",sessionKey:t?.trim()||void 0}}function po(t,e){return{...t,threadId:e??t.threadId}}function kl(t,e,n){return t==="telegram"&&n?.provider==="telegram"&&!!n.target&&e!==n.target}function vl(t){let e=t?.trim();if(!e)return;let n=hl(e);if(!n)return;let{provider:r,kind:o,rawId:i}=n,s=gl(i),a=null;if(r==="telegram")try{a=yl.safeParseTelegramTopicConversation(i)}catch{a=null}let d=a?.chatId??s.id,l=a?.topicId??s.threadId,u=r==="discord"?o==="direct"||o==="dm"?`user:${d}`:`channel:${d}`:d;return{provider:r,target:u,threadId:l,sessionKey:e}}function co(t){let e=t?.match(/:topic:(\d+)$/);return e?parseInt(e[1],10):void 0}function Di(t){return!!(t?.provider&&t.target&&t.provider!=="system"&&t.target!=="system")}function kt(t,e,n){let r=vl(n),o=e!=null?String(e):void 0,i=t?.trim();if(!i||i.toLowerCase()==="unknown")return r?po(r,o):uo(n);let s=i.split("|").map(g=>g.trim());if(s.length<2)return r?po(r,o):uo(n);let[a,d,l]=s,u=s.length>=3?l:d,p=s.length>=3?d:void 0,c=a?.toLowerCase();if(!c||!u)return r?po(r,o):uo(n);let f=c==="discord"?ml(u,n):u;return kl(c,f,r)?{provider:c,accountId:p,target:r.target,threadId:o??r.threadId,sessionKey:n?.trim()||void 0}:{provider:c,accountId:p,target:f,threadId:o??(r?.provider===c?r.threadId:void 0),sessionKey:n?.trim()||void 0}}function Oe(t){return kt(fl(t.route)??t.originChannel,t.route?.threadId??t.originThreadId,t.route?.sessionKey??t.originSessionKey)??t.route}function Ae(t){let e=Oe(t);return Di(e)?e:void 0}function wl(t){return Object.fromEntries(Object.entries(t).filter(e=>!!e[1]))}function vt(t){let e=Oe(t);if(!Di(e))return"";let n=wl({provider:e?.provider,accountId:e?.accountId,target:e?.target,threadId:e?.threadId??(t.originThreadId!=null?String(t.originThreadId):void 0),sessionKey:e?.sessionKey??t.originSessionKey});return Object.keys(n).length===0?"":["Session origin route (authoritative for human follow-ups):",`originRoute: ${JSON.stringify(n)}`,"Routing rule: Send any human follow-up for this wake to originRoute. 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."].join(`
|
|
2
|
+
`)}var ul,yl,ke=j(()=>{ul=new Set(["telegram","discord","slack","system","mattermost","feishu","line","whatsapp","signal","matrix","googlechat","bluebubbles","imessage","msteams"]);yl={safeParseTelegramTopicConversation:Sl}});import{readFileSync as Pl}from"fs";import{homedir as bl}from"os";import{join as Al}from"path";function Ni(){if(wt!==void 0)return wt;try{let t=Pl(Al(bl(),".claude.json"),"utf-8");wt=JSON.parse(t).mcpServers??{}}catch{wt={}}return wt}function Wi(t){let e=t.defaultHarness??Oi,n={};for(let[r,o]of Object.entries(Pt)){let i={...o};o.allowedModels&&(i.allowedModels=[...o.allowedModels]),n[r]=i}for(let[r,o]of Object.entries(t.harnesses??{})){let i=n[r]??{},s={...i,defaultModel:o.defaultModel??i.defaultModel,reasoningEffort:o.reasoningEffort??i.reasoningEffort,fastMode:o.fastMode??i.fastMode};o.allowedModels!==void 0?s.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(s.allowedModels=void 0),n[r]=s}if(t.defaultModel!==void 0){let r=n[e]??{};n[e]={...r,defaultModel:t.harnesses?.[e]?.defaultModel??t.defaultModel,allowedModels:t.harnesses?.[e]?.allowedModels!==void 0?r.allowedModels:t.allowedModels},`${e}`}if(t.model!==void 0){let r=n.codex??{};n.codex={...r,defaultModel:t.harnesses?.codex?.defaultModel??t.model,allowedModels:t.harnesses?.codex?.allowedModels!==void 0?r.allowedModels:t.allowedModels}}if(t.reasoningEffort!==void 0){let r=n.codex??{};n.codex={...r,reasoningEffort:t.harnesses?.codex?.reasoningEffort??t.reasoningEffort}}if(t.allowedModels!==void 0)for(let[r,o]of Object.entries(n))t.harnesses?.[r]?.allowedModels===void 0&&(n[r]={...o,allowedModels:void 0});E={maxSessions:t.maxSessions??20,defaultWorkdir:t.defaultWorkdir,idleTimeoutMinutes:t.idleTimeoutMinutes??15,sessionGcAgeMinutes:t.sessionGcAgeMinutes??1440,maxPersistedSessions:t.maxPersistedSessions??1e4,fallbackChannel:t.fallbackChannel,agentChannels:t.agentChannels,maxAutoResponds:t.maxAutoResponds??10,permissionMode:t.permissionMode??"plan",planApproval:t.planApproval??"delegate",defaultHarness:e,harnesses:n,allowedModels:t.allowedModels,defaultWorktreeStrategy:t.defaultWorktreeStrategy??"delegate",worktreeDir:t.worktreeDir}}function se(){return E.defaultHarness??Oi}function go(t){let e=Pt[t],n=E.harnesses[t];return{...e,...n,allowedModels:n?.allowedModels??e?.allowedModels}}function Qe(t){return go(t).defaultModel}function en(t){return E.harnesses[t]?.allowedModels??E.allowedModels}function xe(t){return go(t).reasoningEffort}function Je(t){return t==="codex"?go(t).fastMode:void 0}function we(t){return t==null?void 0:String(t).trim()||void 0}function ho(t){return{channel:we(t?.deliveryContext?.channel),to:we(t?.deliveryContext?.to),accountId:we(t?.deliveryContext?.accountId),threadId:we(t?.deliveryContext?.threadId)}}function Li(t,e,n){if(!(!t||!e))return n?`${t}|${n}|${e}`:`${t}|${e}`}function mo(t){return we(t?.requesterSenderId??t?.senderId)}function fo(t){return(we(t.deliveryContext?.channel)??t.messageChannel??t.channel)?.toLowerCase()!=="telegram"?!1:!!co(t.sessionKey)}function tn(t){let e=ho(t),n=Li(e.channel,e.to,e.accountId);if(n)return n;if(t.messageChannel){let r=t.messageChannel.split("|");if(r.length>=3)return t.messageChannel;if(t.agentAccountId&&r.length>=2)return`${r[0]}|${t.agentAccountId}|${r.slice(1).join("|")}`;let o=we(t.chatId);if(r.length===1&&o)return`${r[0]}|${o}`;let i=mo(t);if(r.length===1&&i&&!fo(t))return`${r[0]}|${i}`}if(t.workspaceDir){let r=At(t.workspaceDir);if(r)return r}if(t.messageChannel&&t.messageChannel.includes("|"))return t.messageChannel}function bt(t,e){if(e&&String(e).includes("|"))return String(e);let n=ho(t),r=Li(n.channel,n.to,n.accountId);if(r)return r;if(t?.channelId&&String(t.channelId).includes("|"))return String(t.channelId);if(t?.messageChannel){let a=String(t.messageChannel);if(a.includes("|"))return a;let d=we(t.chatId);if(d)return`${a}|${d}`;let l=mo(t);if(l&&!fo(t))return`${a}|${l}`}let o=we(t?.channel),i=we(t?.chatId);if(o&&i)return`${o}|${i}`;let s=mo(t);return o&&s&&!fo(t)?`${o}|${s}`:t?.id&&/^-?\d+$/.test(String(t.id))?`telegram|${t.id}`:E.fallbackChannel??"unknown"}function So(t){return ho(t).threadId??t?.messageThreadId??void 0}function Ye(t,e,n){return kt(bt(t,e),So(t),n??t?.sessionKey)}function At(t){let e=E.agentChannels;if(!e)return;let n=i=>i.replace(/\/+$/,""),r=n(t),o=Object.entries(e).sort((i,s)=>s[0].length-i[0].length);for(let[i,s]of o)if(r===n(i)||r.startsWith(n(i)+"/"))return s}function Bi(t){return co(t)}var wt,Oi,Pt,E,te=j(()=>{ke();Oi="claude-code",Pt={"claude-code":{defaultModel:"anthropic/claude-sonnet-4-7",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.5",allowedModels:["gpt-5.5","gpt-5.5-pro"],reasoningEffort:"medium"},opencode:{}};E={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"delegate",defaultWorktreeStrategy:"delegate",harnesses:{"claude-code":{...Pt["claude-code"]},codex:{...Pt.codex},opencode:{...Pt.opencode}}}});function Xe(t){return{type:"backend_ref",ref:t}}function et(t){return{type:"run_started",...t?{runId:t}:{}}}function Ne(t){return{type:"text_delta",text:t}}function nn(t,e){return{type:"tool_call",name:t,input:e}}function We(t){return{type:"pending_input",state:t}}function Ce(t){return t?{type:"pending_input_resolved",requestId:t}:{type:"pending_input_resolved"}}function rn(t,e){return{type:"plan_artifact",artifact:t,finalized:e}}function tt(t){return t?{type:"settings_changed",permissionMode:t}:{type:"settings_changed"}}function Re(t){return{type:"run_completed",data:t}}var Te,on=j(()=>{Te=class{queue=[];resolvePending=null;done=!1;enqueue(e){this.queue.push(e),this.flush()}close(){this.done=!0,this.flush()}flush(){this.resolvePending&&(this.resolvePending(),this.resolvePending=null)}messages(){let e=this;return(async function*(){for(;;){for(;e.queue.length>0;)yield e.queue.shift();if(e.done)return;await new Promise(n=>{e.resolvePending=n})}})()}}});import*as an from"@anthropic-ai/claude-agent-sdk";function Rl(t){if(typeof t.result=="string"&&t.result.length>0)return t.result;if(Array.isArray(t.errors)){let e=t.errors.filter(n=>typeof n=="string"&&n.length>0);if(e.length>0)return e.join(`
|
|
3
|
+
`)}}function Il(t,e,n){let o=(Array.isArray(n.questions)?n.questions:[])[0]??{},i=typeof o.question=="string"?o.question:void 0,s=Array.isArray(o.options)?o.options.map(a=>{if(!a||typeof a!="object")return"";let d=a.label;return typeof d=="string"?d:""}).filter(Boolean):[];return{requestId:`${t||"claude"}-ask-${e}`,kind:"question",promptText:i,options:s,allowsFreeText:s.length===0||o.multiSelect===!0}}var sn,Fi=j(()=>{on();sn=class{constructor(e={}){this.deps=e}deps;name="claude-code";backendKind="claude-code";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!1,nativePlanArtifacts:!1,worktrees:"plugin-managed"};launch(e){let n=new Te,r=!1,o="",i=!1,s=0,a=e.resumeSessionId??"",d=e.canUseTool,l={cwd:e.cwd,model:e.model,...e.reasoningEffort?{effort:e.reasoningEffort}:{},permissionMode:e.permissionMode,allowDangerouslySkipPermissions:!0,allowedTools:e.allowedTools,systemPrompt:e.systemPrompt,includePartialMessages:!0,abortController:e.abortController,mcpServers:e.mcpServers,...d?{canUseTool:async(g,h)=>{if(g!=="AskUserQuestion")return{behavior:"allow"};let y=Il(a,++s,h);n.enqueue(We(y));try{let k=await d(g,h);return n.enqueue(Ce(y.requestId)),k}catch(k){throw n.enqueue(Ce(y.requestId)),k}}}:{}};e.resumeSessionId&&(l.resume=e.resumeSessionId,l.forkSession=e.forkSession??!1);let u=e.prompt,p=this.deps.query??an.query,c=this.deps.startup??an.startup,f=(async()=>{if(typeof c!="function")return p({prompt:u,options:l});let g=await c({options:l});try{return g.query(u)}catch(h){throw await g.close?.(),h}})();return(async()=>{try{let g=await f;for await(let h of g){let y=h;if(y.type==="system"&&y.subtype==="init"){a=y.session_id??a,n.enqueue(Xe({kind:"claude-code",conversationId:a}));continue}if(y.type==="system"&&y.subtype==="status"&&y.permissionMode){n.enqueue(tt(y.permissionMode));continue}if(y.type==="assistant"){r||(r=!0,n.enqueue(et()));for(let k of y.message?.content??[]){if(k.type==="text"){o+=o?`
|
|
4
|
+
${k.text}`:k.text,n.enqueue(Ne(k.text));continue}k.type==="tool_use"&&((k.name==="ExitPlanMode"||k.name==="set_permission_mode")&&(i=!0),k.name!=="AskUserQuestion"&&n.enqueue(nn(k.name,k.input)))}continue}if(y.type==="result"){let k=o.trim();if(k&&(e.permissionMode==="plan"||i)){let b={explanation:void 0,steps:[],markdown:k};n.enqueue(rn(b,!0))}n.enqueue(Re({success:y.subtype==="success",duration_ms:y.duration_ms??0,total_cost_usd:y.total_cost_usd??0,num_turns:y.num_turns??0,result:Rl(y),session_id:y.session_id??a})),o="",i=!1,r=!1}}}finally{n.close()}})().catch(g=>{n.enqueue(Re({success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,result:g instanceof Error?g.message:String(g),session_id:a})),n.close()}),{messages:n.messages(),async setPermissionMode(g){let h=await f;typeof h.setPermissionMode=="function"&&await h.setPermissionMode(g)},async streamInput(g){let h=await f;typeof h.streamInput=="function"&&await h.streamInput(g)},async interrupt(){let g=await f;typeof g.interrupt=="function"&&await g.interrupt()}}}buildUserMessage(e,n){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:n}}}});import{spawn as xl}from"node:child_process";import Tl from"node:readline";function Cl(t){return t instanceof Error?t.message:String(t)}function Ml(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}async function _l(t,e){if(t.id!=null&&(Object.hasOwn(t,"result")||Object.hasOwn(t,"error"))){let r=String(t.id),o=e.pending.get(r);if(!o)return;if(clearTimeout(o.timer),e.pending.delete(r),t.error){o.reject(new Error(`codex app server rpc error (${t.error.code??"unknown"}): ${t.error.message??"unknown error"}`));return}o.resolve(t.result);return}let n=t.method?.trim();if(n){if(t.id==null){await e.onNotification(n,t.params);return}try{let r=await e.onRequest(n,t.params);e.respond({jsonrpc:"2.0",id:t.id,result:r??{}})}catch(r){e.respond({jsonrpc:"2.0",id:t.id,error:{code:-32603,message:Cl(r)}})}}}var dn,qi=j(()=>{dn=class{constructor(e,n,r){this.command=e;this.args=n;this.requestTimeoutMs=r}command;args;requestTimeoutMs;process=null;pending=new Map;counter=0;onNotification=()=>{};onRequest=async()=>({});setNotificationHandler(e){this.onNotification=e}setRequestHandler(e){this.onRequest=e}async connect(){if(this.process)return;let e=xl(this.command,["app-server",...this.args],{stdio:["pipe","pipe","pipe"],env:process.env});if(!e.stdin||!e.stdout||!e.stderr)throw new Error("codex app server stdio pipes unavailable");this.process=e,Tl.createInterface({input:e.stdout}).on("line",r=>{this.handleLine(r)}),e.stderr.on("data",()=>{}),e.on("close",()=>{this.flushPending(new Error("codex app server stdio closed")),this.process=null})}async close(){this.flushPending(new Error("codex app server stdio closed"));let e=this.process;this.process=null,e&&e.kill()}async notify(e,n){this.write({jsonrpc:"2.0",method:e,params:n??{}})}async request(e,n,r){let o=`rpc-${++this.counter}`,i=new Promise((s,a)=>{let d=setTimeout(()=>{this.pending.delete(o),a(new Error(`codex app server timeout: ${e}`))},Math.max(100,r??this.requestTimeoutMs));d.unref?.(),this.pending.set(o,{resolve:s,reject:a,timer:d})});return this.write({jsonrpc:"2.0",id:o,method:e,params:n??{}}),await i}write(e){if(!this.process?.stdin)throw new Error("codex app server stdio not connected");this.process.stdin.write(`${JSON.stringify(e)}
|
|
5
|
+
`)}async handleLine(e){let n=Ml(e);n&&await _l(n,{pending:this.pending,onNotification:this.onNotification,onRequest:this.onRequest,respond:r=>this.write(r)})}flushPending(e){for(let[n,r]of this.pending)clearTimeout(r.timer),r.reject(e),this.pending.delete(n)}}});function L(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function z(t,e,n){for(let r of e){let o=t?.[r];if(typeof o!="string")continue;let i=n?.trim===!1?o:o.trim();if(i)return i}}function El(t){return t instanceof Error?t.message:String(t)}function Ki(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function Me(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>Me(n)).join("");let e=L(t);if(!e)return"";for(let n of["delta","text","content","message","input","output","parts"]){let r=Me(e[n]);if(r)return r}for(let n of["item","turn","thread","response","result","data"]){let r=Me(e[n]);if(r)return r}return""}function Rt(t){let e=L(t);if(!e)return{};let n=L(e.thread)??L(e.session),r=L(e.turn)??L(e.run),o=L(e.item),i=L(e.serverRequest);return{threadId:z(e,["threadId","thread_id","conversationId","conversation_id"])??z(n,["id","threadId","thread_id","conversationId"]),runId:z(e,["turnId","turn_id","runId","run_id"])??z(r,["id","turnId","turn_id","runId","run_id"]),requestId:z(e,["requestId","request_id","serverRequestId"])??z(i,["id","requestId","request_id"]),itemId:z(e,["itemId","item_id"])??z(o,["id","itemId","item_id"])}}function ln(t,e,n=0){if(n>6)return;if(Array.isArray(t)){for(let i of t){let s=ln(i,e,n+1);if(s)return s}return}let r=L(t);if(!r)return;let o=z(r,e);if(o)return o;for(let i of Object.values(r)){let s=ln(i,e,n+1);if(s)return s}}function It(t){return{threadId:Rt(t).threadId,cwd:ln(t,["cwd","workdir","directory"])}}function Ui(t){let e=t?.trim();return!!(e&&/[/\\]worktrees[/\\][^/\\]+[/\\][^/\\]+/.test(e))}function Vi(t){let e=t?.trim();if(!e)return;let n=e.split(/[/\\]+/).filter(Boolean),r=n.lastIndexOf("worktrees");if(!(r<0||r+1>=n.length))return n[r+1]}function un(t){let e=L(t);if(!e)return;let n=L(e.item)??e;return z(n,["id","itemId","item_id","messageId","message_id"])}function $l(t,e=!1){let n=L(t);if(!n)return"";let r=L(n.item)??n;return z(r,["type"])?.toLowerCase()!=="agentmessage"?"":e?Me(r):z(r,["text"],{trim:!1})??Me(r)}function Gi(t,e){let n=t.trim().toLowerCase();return n==="item/agentmessage/delta"?{mode:"delta",text:Me(e),itemId:un(e)}:n==="item/completed"?{mode:"snapshot",text:$l(e),itemId:un(e)}:{mode:"ignore",text:""}}function Hi(t){return{itemId:un(t),delta:Me(t)}}function ji(t){let e=L(t),n=L(e?.plan),o=(Array.isArray(e?.plan)?e.plan:Array.isArray(n?.steps)?n.steps:[]).map(i=>{let s=L(i),a=z(s,["step","title","text"]);if(!a)return null;let d=z(s,["status"])?.toLowerCase()??"pending";return{step:a,status:d==="inprogress"||d==="in_progress"?"inProgress":d==="completed"?"completed":"pending"}}).filter(Boolean);return{explanation:z(n,["explanation"])??z(e,["explanation"]),steps:o}}function zi(t){let e=L(t);if(!e)return{};let n=L(e.item)??e;return z(n,["type"])?.toLowerCase()!=="plan"?{}:{itemId:un(n),text:z(n,["text"],{trim:!1})??Me(n)}}function Qi(t,e){let n=t.trim().toLowerCase();if(n==="turn/failed")return"failed";if(n==="turn/cancelled")return"interrupted";let r=L(e)??{},o=L(r.turn)??r,i=z(o,["status"])?.toLowerCase();return i==="failed"?"failed":i==="interrupted"||i==="cancelled"?"interrupted":"completed"}function Ji(t,e){let n=L(e)??{},r=L(n.turn)??n,o=L(r.error)??L(n.error);if(o)return z(o,["message","text","summary","reason"])}function Dl(t,e){let n=El(t).toLowerCase();return n.includes("method not found")||n.includes("unknown method")?!0:n.includes("unknown variant")?e?n.includes(`unknown variant \`${e.toLowerCase()}\``):!0:!1}function Nl(t){return Ol.has(t.trim().toLowerCase())}function Wl(t){let e=L(t);return e?!!z(e,["threadId","thread_id"]):!1}async function xt(t){if(t.payloads.length===0)throw new Error(`codex app server request skipped: no payloads for ${t.methods.join(", ")||"<none>"}`);let e;for(let n of t.methods)for(let r of t.payloads){if(Nl(n)&&!Wl(r))throw new Error(`codex app server request missing threadId: ${n}`);try{return await t.client.request(n,r,t.timeoutMs)}catch(o){if(e=o,!Dl(o,n))continue}}throw e instanceof Error?e:new Error(String(e))}function Yi(t){let e={cwd:t.cwd};return t.model?.trim()&&(e.model=t.model.trim()),t.reasoningEffort?.trim()&&(e.reasoningEffort=t.reasoningEffort.trim()),t.fastMode===!0&&(e.service_tier="fast"),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim()),[e]}function Zi(t){let e={threadId:t.threadId,persistExtendedHistory:!1};return t.model?.trim()&&(e.model=t.model.trim()),t.reasoningEffort?.trim()&&(e.reasoningEffort=t.reasoningEffort.trim()),t.fastMode===!0&&(e.service_tier="fast"),t.cwd?.trim()&&(e.cwd=t.cwd.trim()),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim()),[e]}function Ll(t){return[{type:"text",text:t}]}function Bl(t,e,n,r){let o=e?.trim(),i=n?.trim(),s=r?.trim();if(t!=="plan")return o||i||s?{mode:"default",settings:{...o?{model:o}:{},...i?{reasoningEffort:i}:{},developerInstructions:s??null}}:void 0;if(!(!o&&!i&&!s))return{mode:"plan",settings:{...o?{model:o}:{},...i?{reasoningEffort:i}:{},developerInstructions:s??null}}}function Xi(t){let e={threadId:t.threadId,input:Ll(t.prompt)};t.model?.trim()&&(e.model=t.model.trim()),t.fastMode===!0&&(e.service_tier="fast"),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim());let n=Bl(t.permissionMode??"default",t.model,t.reasoningEffort,t.systemPrompt);return n?[{...e,collaborationMode:n}]:[e]}function es(t){return[{threadId:t.threadId,turnId:t.turnId}]}function Fl(t){let e=L(t);if(!e)return[];let n=e.options??e.choices??e.availableDecisions??e.decisions;return Array.isArray(n)?n.map(r=>typeof r=="string"?r.trim():z(L(r),["label","title","text","value","name","id"])??"").filter(Boolean):[]}function ql(t){let e=t.trim().toLowerCase();return e.includes("session")?"acceptForSession":/cancel|abort|stop/.test(e)?"cancel":/deny|decline|reject|block|no/.test(e)?"decline":/approve|allow|accept|yes/.test(e)?"accept":t.trim()}function ts(t,e,n){let r=t.trim().toLowerCase(),o=Fl(n),i=ln(n,["question","prompt","message","text","summary","reason"])??void 0,s=r.includes("requestapproval"),a=s?o.map(d=>({kind:"approval",label:d,decision:ql(d),responseDecision:d})):o.map(d=>({kind:"option",label:d,value:d}));return{requestId:e,kind:s?"approval":"question",promptText:i,options:o,actions:a,allowsFreeText:!0}}function ns(t){let e=t.trim().toLowerCase();return e.includes("requestuserinput")||e.includes("requestapproval")}function yo(t,e){let n=t==="bypassPermissions"?"never":e?.trim()||"never";return{approvalPolicy:n,sandbox:n==="never"?"danger-full-access":void 0}}var Ol,rs=j(()=>{Ol=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function os(t){return t instanceof Error?t.message:String(t)}function Hl(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return String(t);let e=t;return typeof e.message?.content=="string"?e.message.content:typeof e.text=="string"?e.text:String(t)}var Kl,Le,Ul,Vl,Gl,pn,is=j(()=>{qi();on();rs();Kl="1.0",Le=6e4,Ul="OPENCLAW_CODEX_APP_SERVER_COMMAND",Vl="OPENCLAW_CODEX_APP_SERVER_ARGS",Gl="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";pn=class{constructor(e={}){this.deps=e}deps;name="codex";backendKind="codex-app-server";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!0,nativePlanArtifacts:!0,worktrees:"native-restore"};launch(e){let n={command:process.env[Ul]?.trim()||"codex",args:Ki(process.env[Vl]),requestTimeoutMs:Number.parseInt(process.env[Gl]??String(Le),10)||Le},r=this.deps.createClient?.(n)??new dn(n.command,n.args,n.requestTimeoutMs),o=new Te,i=e.resumeSessionId,s,a=e.backendRef?.worktreePath,d=e.backendRef?.worktreeId,l=e.permissionMode??"default",u,p=0,c="",f=[],g,h=new Map,y=new Set,k=_=>{let C=_?.trim();if(!C)return;let M=e.originalWorkdir?.trim()||e.cwd.trim();e.worktreeStrategy&&e.worktreeStrategy!=="off"&&C!==M&&Ui(C)&&(a=C,d=Vi(C))},b=()=>{i&&o.enqueue(Xe({kind:"codex-app-server",conversationId:i,...s?{runId:s}:{},...d?{worktreeId:d}:{},...a?{worktreePath:a}:{}}))};r.setNotificationHandler(async(_,C)=>{let M=_.trim().toLowerCase(),F=Rt(C),ie=It(C);if(F.threadId&&i&&F.threadId!==i)return;if(F.threadId&&(i=F.threadId),F.runId&&(s=F.runId),k(ie.cwd),(F.threadId||F.runId||ie.cwd)&&b(),M==="serverrequest/resolved"){u&&(o.enqueue(Ce(u.requestId)),u=void 0);return}if(M==="turn/plan/updated"){let Y=ji(C);c=Y.explanation??c,Y.steps.length>0&&(f=Y.steps);return}if(M==="item/plan/delta"){let Y=Hi(C);if(Y.itemId&&Y.delta){let ce=h.get(Y.itemId)??"";h.set(Y.itemId,`${ce}${Y.delta}`)}return}if(M==="item/completed"){let Y=zi(C);if(Y.text?.trim()){let ce={explanation:c||void 0,steps:f,markdown:Y.text.trim()};o.enqueue(rn(ce,!0));return}}let q=Gi(M,C);if(q.mode==="delta"&&q.text){q.itemId&&y.add(q.itemId),o.enqueue(Ne(q.text));return}q.mode==="snapshot"&&q.text&&(!q.itemId||!y.has(q.itemId))&&o.enqueue(Ne(q.text)),(M==="turn/completed"||M==="turn/failed"||M==="turn/cancelled")&&g&&(g.method=_,g.params=C,g.resolve())}),r.setRequestHandler(async(_,C)=>{if(!ns(_))return{};let M=Rt(C),F=It(C);if(M.threadId&&i&&M.threadId!==i)return{};M.threadId&&(i=M.threadId),M.runId&&(s=M.runId),k(F.cwd),(M.threadId||M.runId||F.cwd)&&b();let ie=M.requestId??`${i??"codex"}-${Date.now().toString(36)}`,q=ts(_,ie,C),Y=_.trim().toLowerCase(),ce=q.options,je=q.actions??[],oo=await new Promise(io=>{u={requestId:ie,methodLower:Y,state:q,options:ce,actions:je,resolveResponse:io},o.enqueue(We(q))});return u=void 0,o.enqueue(Ce(ie)),oo});let A=async()=>{await r.connect(),await r.request("initialize",{protocolVersion:Kl,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},Le),await r.notify("initialized",{})},I=async()=>{let _=yo(l,e.codexApprovalPolicy);if(i){let F=await xt({client:r,methods:["thread/resume"],payloads:Zi({threadId:i,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,approvalPolicy:_.approvalPolicy,sandbox:_.sandbox}),timeoutMs:Le}),ie=It(F);i=ie.threadId??i,k(ie.cwd),b();return}let C=await xt({client:r,methods:["thread/start","thread/new"],payloads:Yi({cwd:e.cwd,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,approvalPolicy:_.approvalPolicy,sandbox:_.sandbox}),timeoutMs:Le}),M=It(C);if(i=M.threadId,!i)throw new Error("Codex App Server did not return a thread id.");k(M.cwd),b()},W=async _=>{await I(),o.enqueue(et()),p+=1,c="",f=[],h.clear(),y.clear();let C="",M,F,ie=new Promise(q=>{F=q});g={resolve:F};try{let q=yo(l,e.codexApprovalPolicy),Y=await xt({client:r,methods:["turn/start"],payloads:Xi({threadId:i,prompt:_,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,systemPrompt:e.systemPrompt,permissionMode:l,approvalPolicy:q.approvalPolicy,sandbox:q.sandbox}),timeoutMs:Le}),ce=Rt(Y);ce.runId&&(s=ce.runId,b()),await ie,C=g?.method??"turn/failed",M=g?.params;let je=Qi(C,M);o.enqueue(Re({success:je==="completed",outcome:je,duration_ms:0,total_cost_usd:0,num_turns:p,result:Ji(C,M),session_id:i}))}catch(q){o.enqueue(Re({success:!1,duration_ms:0,total_cost_usd:0,num_turns:p,result:os(q),session_id:i??""}))}finally{g=void 0}},S=async _=>u?(u.methodLower.includes("requestapproval")?u.resolveResponse({decision:_.trim()||"decline"}):u.resolveResponse({text:_.trim()}),!0):!1,R=async _=>{let C=u;if(!C)return!1;let M=C.actions[_];if(M?.kind==="approval")return C.resolveResponse({decision:M.responseDecision,...M.proposedExecpolicyAmendment?{proposedExecpolicyAmendment:M.proposedExecpolicyAmendment}:{}}),!0;let F=C.options[_];return F?(C.methodLower.includes("requestapproval")?C.resolveResponse({decision:F}):C.resolveResponse({option:F,index:_}),!0):!1},H=typeof e.prompt=="string"?(async function*(){yield{type:"user",text:e.prompt,session_id:e.resumeSessionId??""}})():e.prompt;return(async()=>{try{await A();for await(let _ of H){let C=Hl(_).trim();!C||await S(C)||await W(C)}}catch(_){o.enqueue(Re({success:!1,duration_ms:0,total_cost_usd:0,num_turns:p,result:os(_),session_id:i??e.resumeSessionId??""}))}finally{await r.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(_){l=_,o.enqueue(tt(_))},async submitPendingInputOption(_){return R(_)},async submitPendingInputText(_){return S(_)},async interrupt(){!i||!s||await xt({client:r,methods:["turn/interrupt"],payloads:es({threadId:i,turnId:s}),timeoutMs:Le}).catch(()=>{})}}}buildUserMessage(e,n){return{type:"user",text:e,session_id:n}}}});import{spawn as jl}from"node:child_process";import{constants as zl,accessSync as Ql}from"node:fs";import{createServer as Jl}from"node:net";import{delimiter as Yl,dirname as ko,join as as,sep as Zl}from"node:path";function Tt(t){return t instanceof Error?t.message:String(t)}function ru(t){try{return Ql(t,zl.X_OK),!0}catch{return!1}}function ou(t){return t.includes("/")||Zl==="\\"&&t.includes("\\")}function iu(t){let e=(t??"").split(Yl).map(r=>r.trim()).filter(Boolean),n=[...e];for(let r of e)r.replaceAll("\\","/").endsWith("/opt/node/bin")&&n.push(as(ko(ko(ko(r))),"bin"));return n.push("/home/linuxbrew/.linuxbrew/bin","/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin"),[...new Set(n)]}function su(t,e=process.env.PATH){if(ou(t))return t;for(let n of iu(e)){let r=as(n,t);if(ru(r))return r}return t}function Z(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function au(t){if(typeof t=="string")return t;if(!Z(t))return String(t);if(typeof t.text=="string")return t.text;let e=Z(t.message)?t.message:void 0;return typeof e?.content=="string"?e.content:String(t)}function ds(t){let e=t?.trim();if(!e)return;let n=e.indexOf("/");if(!(n<=0||n===e.length-1))return{providerID:e.slice(0,n),modelID:e.slice(n+1)}}function du(t){let e=ds(t);return e?{id:e.modelID,providerID:e.providerID}:void 0}function ss(t){let e=t??"default",n=e==="plan"?"deny":e==="bypassPermissions"?"allow":"ask";return nu.map(r=>({permission:r,pattern:"*",action:n}))}function vo(){let t=process.env.OPENCODE_SERVER_PASSWORD;if(!t)return{};let e=process.env.OPENCODE_SERVER_USERNAME||"opencode";return{Authorization:`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`}}async function lu(){return new Promise((t,e)=>{let n=Jl();n.once("error",e),n.listen(0,"127.0.0.1",()=>{let r=n.address();n.close(()=>{r&&typeof r=="object"?t(r.port):e(new Error("Could not allocate local OpenCode server port."))})})})}async function ls(t){await new Promise(e=>setTimeout(e,t))}async function cn(t,e){if(e.signal?.aborted)throw new Error(e.abortMessage??"Operation was aborted.");return await new Promise((n,r)=>{let o=!1,i=()=>{clearTimeout(d),e.signal?.removeEventListener("abort",a)},s=l=>{o||(o=!0,i(),l())},a=()=>{s(()=>r(new Error(e.abortMessage??"Operation was aborted.")))},d=setTimeout(()=>{s(()=>{e.onTimeout?.(),r(new Error(e.timeoutMessage))})},e.timeoutMs);e.signal?.addEventListener("abort",a,{once:!0}),t.then(l=>s(()=>n(l)),l=>s(()=>r(l)))})}async function nt(t){t.exitCode===null&&await new Promise(e=>{let n,r=setTimeout(()=>{t.exitCode===null&&t.kill("SIGKILL"),n=setTimeout(e,1e3)},2e3);t.once("exit",()=>{clearTimeout(r),n&&clearTimeout(n),e()}),t.kill("SIGTERM")})}function uu(t){return t.headers.get("content-type")?.toLowerCase()??""}function Po(t){return t.replace(/\s+/g," ").trim().slice(0,300)}function pu(t,e){return t.includes("text/html")||/^\s*<!doctype html\b/i.test(e)||/^\s*<html[\s>]/i.test(e)}function cu(t,e,n,r){let o=n?`content-type ${n}`:"missing content-type",i=Po(r),s=pu(n,r)?" (looks like the OpenCode web UI HTML app shell)":"";return`OpenCode ${t} ${e} expected JSON API response but received ${o}${s}${i?`: ${i}`:""}`}function mu(t,e,n){let r=ds(e);return{...r?{model:{providerID:r.providerID,modelID:r.modelID}}:{},...n?.trim()?{system:n.trim()}:{},parts:[{type:"text",text:t}]}}function fu(t,e){if(!Z(t))return!1;if(!(e in t))return!0;let n=t[e];return Z(n)&&n.type==="idle"}async function gu(t){let e=await lu(),n=process.env[Xl]?.trim()||"opencode",r=su(n),o=["serve","--hostname","127.0.0.1","--port",String(e),"--print-logs"],i=t.fetch??fetch,s=Math.min(t.requestTimeoutMs??Ro,1e4),a=t.startupTimeoutMs??eu,d=jl(r,o,{cwd:t.cwd,stdio:["ignore","pipe","pipe"]}),l=`http://127.0.0.1:${e}`,u="",p="",c,f=(k,b)=>{let A=k+String(b);return A.length>8e3?A.slice(-8e3):A};d.stdout.on("data",k=>{u=f(u,k)}),d.stderr.on("data",k=>{p=f(p,k)}),d.once("error",k=>{c=k});let g=()=>` Command: ${n===r?r:`${r} (resolved from ${n})`} ${o.join(" ")}. Cwd: ${t.cwd}. Port: ${e}. PATH: ${process.env.PATH??""}.`,h=()=>{let k=[u.trim(),p.trim()].filter(Boolean).join(`
|
|
6
|
+
`).trim();return`${g()}${k?` Output:
|
|
7
|
+
${k}`:""}`},y=()=>{nt(d)};if(t.signal?.aborted)throw await nt(d),new Error(`OpenCode server startup aborted before readiness.${h()}`);t.signal?.addEventListener("abort",y,{once:!0});try{let k=Date.now();for(;Date.now()-k<a;){if(t.signal?.aborted)throw await nt(d),new Error(`OpenCode server startup aborted before readiness.${h()}`);if(c)throw new Error(`OpenCode server failed to start: ${c.message}${h()}`);if(d.exitCode!==null)throw new Error(`OpenCode server exited before readiness.${h()}`);try{if(await Su({baseUrl:l,fetchImpl:i,requestTimeoutMs:s,startupSignal:t.signal,timeoutMessage:`OpenCode GET /api/health timed out after ${s}ms during server readiness.${h()}`,abortMessage:`OpenCode server startup aborted before readiness.${h()}`}))return{baseUrl:l,close:async()=>{await nt(d)}}}catch{if(t.signal?.aborted)throw await nt(d),new Error(`OpenCode server startup aborted before readiness.${h()}`)}await ls(100)}throw await nt(d),new Error(`Timed out waiting for OpenCode server readiness.${h()}`)}finally{t.signal?.removeEventListener("abort",y)}}async function hu(t){for(let e=1;;e+=1)try{return await gu(t)}catch(n){if(e>=3||!/EADDRINUSE|address already in use|bind: address already in use/i.test(Tt(n)))throw n}}async function Su(t){let e=new AbortController,n=()=>e.abort();t.startupSignal?.aborted?e.abort():t.startupSignal?.addEventListener("abort",n,{once:!0});try{return(await cn(t.fetchImpl(`${t.baseUrl}/api/health`,{headers:vo(),signal:e.signal}),{timeoutMs:t.requestTimeoutMs,timeoutMessage:t.timeoutMessage,signal:t.startupSignal,abortMessage:t.abortMessage,onTimeout:()=>e.abort()})).ok}finally{t.startupSignal?.removeEventListener("abort",n)}}function yu(t){let e=Z(t)&&Z(t.payload)?t.payload:t;return Z(e)?e.type==="sync"?{type:typeof e.name=="string"?e.name.replace(/\.\d+$/,""):void 0,properties:Z(e.data)?e.data:{}}:{type:typeof e.type=="string"?e.type:void 0,properties:Z(e.properties)?e.properties:e}:{properties:{}}}function ku(t){return typeof t.sessionID=="string"?t.sessionID:void 0}function vu(t){let e=typeof t.id=="string"?t.id:"opencode-permission",n=typeof t.permission=="string"?t.permission:"permission",r=Array.isArray(t.patterns)?t.patterns.filter(s=>typeof s=="string"):[],o=r.length>0?`OpenCode requests ${n} permission for ${r.join(", ")}.`:`OpenCode requests ${n} permission.`,i=[{kind:"approval",label:"Allow once",decision:"accept",responseDecision:"once"},{kind:"approval",label:"Always allow",decision:"acceptForSession",responseDecision:"always"},{kind:"approval",label:"Reject",decision:"decline",responseDecision:"reject"}];return{requestId:e,kind:"approval",promptText:o,options:i.map(s=>s.label),actions:i,responseMode:"structured"}}function wu(t){let e=typeof t.id=="string"?t.id:"opencode-question",n=typeof t.question=="string"?t.question:typeof t.prompt=="string"?t.prompt:"OpenCode is asking for input.",r=Array.isArray(t.options)?t.options.map(o=>typeof o=="string"?o:Z(o)&&typeof o.label=="string"?o.label:"").filter(Boolean):[];return{requestId:e,kind:"question",promptText:n,options:r,allowsFreeText:!0}}function Pu(t){return Ao(t).result}function Ao(t){let e=Array.isArray(t)?t:Z(t)&&Array.isArray(t.messages)?t.messages:Z(t)&&Array.isArray(t.items)?t.items:[],n=[];for(let r of e){let o=Z(r)&&Z(r.info)?r.info:r;if(!Z(o)||(typeof o.role=="string"?o.role:o.type)!=="assistant")continue;let s=Array.isArray(o.content)?o.content:[],a=Z(r)&&Array.isArray(r.parts)?r.parts:[];for(let d of[...s,...a])Z(d)&&d.type==="text"&&typeof d.text=="string"&&n.push(d.text)}return{count:n.length,result:n.at(-1)}}var Xl,eu,Ro,tu,nu,wo,bo,mn,us=j(()=>{on();Xl="OPENCLAW_OPENCODE_COMMAND",eu=15e3,Ro=6e4,tu=15*6e4,nu=["edit","bash","task","todowrite","external_directory"];wo=class extends Error{constructor(n,r,o,i){super(`OpenCode ${n} ${r} failed with ${o}${i?`: ${i}`:""}`);this.method=n;this.path=r;this.status=o;this.body=i}method;path;status;body};bo=class{constructor(e,n,r=Ro){this.baseUrl=e;this.fetchImpl=n;this.requestTimeoutMs=r}baseUrl;fetchImpl;requestTimeoutMs;async request(e,n,r,o={}){let i=new AbortController,s=!1,a=!1,d=o.timeoutMs??this.requestTimeoutMs,l=`OpenCode ${e} ${n} timed out after ${d}ms.`,u=`OpenCode ${e} ${n} was aborted.`,p=()=>{s=!0,i.abort()};o.signal?.aborted?(s=!0,i.abort()):o.signal?.addEventListener("abort",p,{once:!0});try{let c=await cn(this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:{...vo(),...r===void 0?{}:{"content-type":"application/json"}},body:r===void 0?void 0:JSON.stringify(r),signal:i.signal}),{timeoutMs:d,timeoutMessage:l,signal:o.signal,abortMessage:u,onTimeout:()=>{a=!0,i.abort()}});if(!c.ok){let h=await cn(c.text(),{timeoutMs:d,timeoutMessage:l,signal:o.signal,abortMessage:u,onTimeout:()=>{a=!0,i.abort()}}).catch(()=>"");throw new wo(e,n,c.status,Po(h))}if(c.status===204)return;let f=await cn(c.text(),{timeoutMs:d,timeoutMessage:l,signal:o.signal,abortMessage:u,onTimeout:()=>{a=!0,i.abort()}});if(!f)return;let g=uu(c);if(!g.includes("application/json")&&!g.includes("+json"))throw new Error(cu(e,n,g,f));try{return JSON.parse(f)}catch(h){let y=Po(f);throw new Error(`OpenCode ${e} ${n} returned invalid JSON: ${Tt(h)}${y?`: ${y}`:""}`)}}catch(c){if(i.signal.aborted){if(a)throw new Error(`OpenCode ${e} ${n} timed out after ${d}ms.`);if(s)throw new Error(`OpenCode ${e} ${n} was aborted.`)}throw c}finally{o.signal?.removeEventListener("abort",p)}}async streamEvents(e,n){let r=await this.fetchImpl(`${this.baseUrl}/event`,{headers:vo(),signal:n});if(!r.ok)throw new Error(`OpenCode event stream failed with ${r.status}`);if(!r.body)return;let o=r.body.getReader(),i=new TextDecoder,s="",a=async l=>{let u=l.split(/\r?\n/).filter(p=>p.startsWith("data:")).map(p=>p.slice(5).trimStart()).join(`
|
|
8
|
+
`).trim();!u||u==="[DONE]"||await e(JSON.parse(u))};for(;;){let{done:l,value:u}=await o.read();if(l)break;s+=i.decode(u,{stream:!0});let p=/\r?\n\r?\n/.exec(s);for(;p;){let c=s.slice(0,p.index);s=s.slice(p.index+p[0].length),await a(c),p=/\r?\n\r?\n/.exec(s)}}let d=s.trim();d&&await a(d)}};mn=class{constructor(e={}){this.deps=e}deps;name="opencode";backendKind="opencode-server";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!0,nativePlanArtifacts:!1,worktrees:"plugin-managed"};launch(e){let n=new Te,r=this.deps.fetch??fetch,o,i,s,a=e.resumeSessionId,d=0,l=e.permissionMode??"default",u,p=!e.resumeSessionId,c=!1,f=!1,g=new AbortController,h,y=!1,k=!1,b=!1,A=!1,I=!1,W,S=new Set,R=x=>A?!1:(A=!0,n.enqueue(Re(x)),!0),H=(x,P,J)=>R({success:x,outcome:P,duration_ms:0,total_cost_usd:0,num_turns:d,result:J,session_id:a??""}),_=()=>{a&&W!==a&&(W=a,n.enqueue(Xe({kind:"opencode-server",conversationId:a})))},C=x=>{x&&S.has(x)||(x&&S.add(x),n.enqueue(Ce(x)),x&&u?.requestId===x&&(u=void 0))},M=async()=>{if(i)return i;s??=(async()=>{let x=await(this.deps.createServer??hu)({cwd:e.cwd,signal:e.abortController?.signal,fetch:r,requestTimeoutMs:this.deps.requestTimeoutMs,startupTimeoutMs:this.deps.startupTimeoutMs});if(I||e.abortController?.signal.aborted)throw await x.close().catch(()=>{}),new Error("OpenCode startup was interrupted before session creation.");return o=x,i=new bo(x.baseUrl,r,this.deps.requestTimeoutMs),i})();try{return await s}catch(x){throw s=void 0,x}},F=async(x,P)=>{!i||!a||await i.request("POST",`/permission/${encodeURIComponent(x)}/reply`,{reply:P})},ie=async(x,P)=>{!i||!a||await i.request("POST",`/question/${encodeURIComponent(x)}/reply`,{answers:[[P]]})},q=async x=>{let P=yu(x),J=ku(P.properties);if(!(J&&J!==a)){if((P.type==="session.next.text.delta"||P.type==="message.part.delta")&&P.properties.field!=="reasoning"&&typeof P.properties.delta=="string"){n.enqueue(Ne(P.properties.delta));return}if(P.type==="session.next.tool.called"||P.type==="message.part.updated"){let $=Z(P.properties.part)?P.properties.part:void 0;if(P.type==="message.part.updated"&&$?.type!=="tool"){n.enqueue({type:"activity"});return}let re=typeof P.properties.tool=="string"?P.properties.tool:typeof $?.tool=="string"?$.tool:"tool";n.enqueue(nn(re,P.properties.input));return}if(P.type==="session.next.step.failed"||P.type==="session.error"){let $=Z(P.properties.error)&&typeof P.properties.error.message=="string"?P.properties.error.message:`${P.type} failed`;k&&!b&&(h?.abort(),H(!1,"failed",$));return}if(P.type==="permission.asked"){if(l==="bypassPermissions"){let re=typeof P.properties.id=="string"?P.properties.id:void 0;re&&(await F(re,"once").catch(()=>{}),C(re));return}let $=vu(P.properties);u={requestId:$.requestId,kind:"approval",options:$.options,actions:$.actions??[]},n.enqueue(We($));return}if(P.type==="permission.replied"){let $=typeof P.properties.requestID=="string"?P.properties.requestID:void 0;C($);return}if(P.type==="question.asked"){let $=wu(P.properties);u={requestId:$.requestId,kind:"question",options:$.options,actions:[]},n.enqueue(We($));return}if(P.type==="question.replied"||P.type==="question.rejected"){let $=typeof P.properties.requestID=="string"?P.properties.requestID:void 0;C($);return}(P.type?.startsWith("session.next.")||P.type?.startsWith("message.")||P.type==="session.status"||P.type==="session.idle")&&n.enqueue({type:"activity"})}},Y=()=>{y||!i||(y=!0,i.streamEvents(q,g.signal).catch(x=>{!g.signal.aborted&&k&&!b&&(h?.abort(),H(!1,"failed",Tt(x)))}).finally(()=>{y=!1}))},ce=async(x,P)=>await x.request("GET",`/session/${encodeURIComponent(P)}/message`),je=async(x,P,J,$,re)=>{await x.request("POST",`/session/${encodeURIComponent(P)}/prompt_async`,mu(J,e.model,$),{signal:re})},oo=async(x,P,J,$)=>{let re=Date.now(),Zt=!1,ze=this.deps.turnTimeoutMs??tu;for(;;){if($.aborted)throw new Error("wait aborted");let el=await x.request("GET","/session/status",void 0,{signal:$,timeoutMs:Math.min(this.deps.requestTimeoutMs??Ro,1e4)}),Ei=fu(el,P);Ei||(Zt=!0);let tl=await ce(x,P).catch(()=>{}),nl=Ao(tl);if(Ei&&(Zt||nl.count>J))return;if(Date.now()-re>ze)throw new Error(`Timed out waiting for OpenCode session ${P} to become idle after ${ze}ms.`);await ls(250)}},io=async()=>{let x=await M();if(a){if(e.forkSession&&!c){let $=await x.request("POST",`/session/${encodeURIComponent(a)}/fork`,{});if(!$.id)throw new Error("OpenCode fork did not return a session id.");a=$.id,c=!0,p=!0}else p||(await ce(x,a),p=!0);return _(),Y(),a}let P=du(e.model),J=await x.request("POST","/session",{...P?{model:P}:{},metadata:{client:"openclaw-code-agent"},permission:ss(l)});if(!J.id)throw new Error("OpenCode did not return a session id.");return a=J.id,p=!0,_(),Y(),a},_i=async(x,P,J=x?"completed":"failed")=>{let $=P;if(x&&i&&a){let re=await ce(i,a).catch(()=>{});$=$??Pu(re)}H(x,J,$)},Zd=async x=>{k=!0,b=!1,A=!1;try{let P=await M();if(I)return;let J=await io();if(I)return;n.enqueue(et()),d+=1;let $=f?void 0:e.systemPrompt,re=await ce(P,J).catch(()=>{}),Zt=Ao(re).count,ze=new AbortController;h=ze,await je(P,J,x,$,ze.signal),f=!0,await oo(P,J,Zt,ze.signal),h=void 0,b=!0,await _i(!0)}catch(P){h=void 0,await _i(!1,Tt(P))}finally{k=!1,b=!1}},Xd=typeof e.prompt=="string"?(async function*(){yield{type:"user",text:e.prompt,session_id:e.resumeSessionId??""}})():e.prompt;return(async()=>{try{for await(let x of Xd){if(I)break;let P=au(x).trim();if(P){if(u?.kind==="question"){await ie(u.requestId,P),C(u.requestId);continue}if(await Zd(P),I)break}}}catch(x){I||(k||(A=!1),H(!1,"failed",Tt(x)))}finally{g.abort(),await o?.close().catch(()=>{}),n.close()}})(),{messages:n.messages(),async setPermissionMode(x){a&&await(await M()).request("PATCH",`/session/${encodeURIComponent(a)}`,{permission:ss(x)}),l=x,n.enqueue(tt(x))},async submitPendingInputOption(x){let P=u;if(!P)return!1;if(P.kind==="approval"){let $=P.actions[x],re=$?.kind==="approval"?$.responseDecision:void 0;return re?(await F(P.requestId,re),C(P.requestId),!0):!1}let J=P.options[x];return J?(await ie(P.requestId,J),C(P.requestId),!0):!1},async submitPendingInputText(x){let P=u;return!P||P.kind!=="question"?!1:(await ie(P.requestId,x),C(P.requestId),!0)},async interrupt(){if(I=!0,g.abort(),h?.abort(),k||(A=!1),H(!1,"interrupted"),!i){await o?.close().catch(()=>{});return}if(!a)return;await i.request("POST",`/session/${encodeURIComponent(a)}/abort`).catch(()=>{})}}}buildUserMessage(e,n){return{type:"user",text:e,session_id:n}}}});function xo(t){Io.set(t.name,t)}function Ct(t){let e=Io.get(t);if(!e)throw new Error(`Unknown agent harness: "${t}". Available: ${[...Io.keys()].join(", ")}`);return e}function ps(){return Ct(se())}var Io,To=j(()=>{Fi();is();us();te();Io=new Map;xo(new sn);xo(new pn);xo(new mn)});function T(t){return t.backendRef?.conversationId??t.harnessSessionId}function N(t){return t.id??t.sessionId??t.name??T(t)??t.harnessSessionId}function bu(t){return t.harnessSessionId}function ae(t){let e=[N(t),T(t),bu(t)].filter(n=>!!n);return[...new Set(e)]}function Co(t){return t.harnessName??t.persistedHarness??se()}function Mt(t){if(t.backendRef?.kind==="codex-app-server")return"native-restore";try{return Ct(Co(t)).capabilities.worktrees}catch{return"plugin-managed"}}function Mo(t){return t==="native-execution"}function fn(t){return t==="native-restore"}function Au(t){return!!(t.backendRef?.worktreePath||t.backendRef?.worktreeId)}function de(t){let e=Mt(t);return(Mo(e)||fn(e))&&Au(t)}var Q=j(()=>{te();To()});import{execFileSync as ee}from"child_process";import*as En from"fs";import{tmpdir as Ju}from"os";import{dirname as $s,join as Yu}from"path";function Zu(t){try{return ee("git",["rev-parse","--show-toplevel"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function $n(t){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(E.worktreeDir)return E.worktreeDir;if(t){let e=Zu(t);if(e)return Yu(e,".worktrees")}return Ju()}function Ds(t){return t.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function Dn(t){try{let e=ee("git",["-C",t,"rev-parse","--git-common-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e&&e.endsWith("/.git")?$s(e):void 0}catch{return}}function Xu(){if(Mn!==void 0)return Mn;try{return ee("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Mn=!0,!0}catch{return Mn=!1,!1}}function _e(){if(_n!==void 0)return _n;try{return ee("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),_n=!0,!0}catch{return _n=!1,!1}}function Oo(t){if(!Xu())return!1;try{return ee("git",["rev-parse","--git-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Os(t){try{let e=tp(t);if(!e)return`${$n(t)}`,!0;let n=En.statfsSync(e),r=n.bavail*n.bsize;return np(r)}catch(e){return`${e instanceof Error?e.message:String(e)}`,!0}}function Ot(t,e){try{return ee("git",["-C",t,"rev-parse","--verify",e],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function ep(t){let e=t;for(;;){if(En.existsSync(e))return e;let n=$s(e);if(n===e)return;e=n}}function tp(t){return ep($n(t))}function np(t){return t>=104857600}function Pe(t){let e=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(e)return e;try{let r=ee("git",["-C",t,"rev-parse","--abbrev-ref","origin/HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().replace(/^origin\//,"");if(r)return r}catch{}try{return ee("git",["-C",t,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return ee("git",["-C",t,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{return"main"}}function On(t){try{let n=ee("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n==="HEAD"){`${t}`;return}return n||void 0}catch{return}}function Nt(t,e,n){try{let r=ee("git",["-C",t,"rev-list","--count",`${n}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return parseInt(r.trim(),10)>0}catch{return!1}}function Ns(t,e,n){try{let r=ee("git",["-C",t,"rev-list","--left-right","--count",`${e}...${n}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),[o,i]=r.split(/\s+/);return{ahead:parseInt(o??"0",10)||0,behind:parseInt(i??"0",10)||0}}catch{return}}function Ws(t,e,n){try{return ee("git",["-C",t,"merge-base","--is-ancestor",e,n],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Ls(t,e,n){try{let r=ee("git",["-C",t,"merge-tree","--write-tree",n,e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=ee("git",["-C",t,"rev-parse",`${n}^{tree}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return!!r&&r===o}catch{return!1}}function be(t,e){try{return ee("git",["-C",t,"branch","-D",e],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(n){return`${e}${n instanceof Error?n.message:String(n)}`,!1}}function Bs(t,e){if(e)return e;let n;try{n=ee("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}try{let r=ee("git",["-C",t,"remote","get-url","upstream"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r&&r!==n){let o=r.match(/[:/]([^/]+\/[^/]+?)(?:\.git)?$/);if(o)return o[1]}}catch{}}var Mn,_n,Wt=j(()=>{te()});import{execFileSync as at}from"child_process";import{appendFileSync as rp,existsSync as Ks,mkdirSync as Fs,readFileSync as op,rmSync as No}from"fs";import{relative as ip,sep as qs}from"path";function sp(t,e){return!!(t&&typeof t=="object"&&"code"in t&&t.code===e)}function ap(t){try{return at("git",["-C",t,"rev-parse","--show-toplevel"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function dp(t,e){let n=ap(t);if(!n)return;let r=ip(n,e);if(!r||r.startsWith("..")||r.includes(`..${qs}`))return;let o=`${n}/.git/info/exclude`,i=`${r.split(qs).join("/").replace(/\/$/,"")}/`;try{let s=Ks(o)?op(o,"utf-8"):"";s.split(/\r?\n/).map(d=>d.trim()).some(d=>d===i||d===`/${i}`)||rp(o,`${s.endsWith(`
|
|
9
|
+
`)||s.length===0?"":`
|
|
7
10
|
`}${i}
|
|
8
|
-
`,"utf-8")}catch(
|
|
9
|
-
`).map(
|
|
10
|
-
`).map(
|
|
11
|
-
`).filter(Boolean).map(
|
|
12
|
-
`).some(
|
|
13
|
-
`)}}Ie("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Ie("git",["-C",t,"merge","--ff-only",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let l=!1;if(i)try{Ie("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{l=!0}return{success:!0,fastForward:!0,stashed:i||void 0,stashRef:a,stashPopConflict:l||void 0}}catch(p){try{Ie("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return u(t),{success:!1,error:p instanceof Error?p.message:String(p),stashed:i||void 0,stashRef:a}}}var Nc=De(()=>{});import{execFileSync as Is}from"child_process";function qc(t,e,r,n,o,i){if(!Pr())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let a;if(i)try{let m=Is("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[:/]([^/]+)\/[^/]+(?:\.git)?$/);m&&(a=m[1])}catch{}let u=["pr","create","--base",r];return i&&u.push("--repo",i),a?u.push("--head",`${a}:${e}`):u.push("--head",e),n&&o?u.push("--title",n,"--body",o):u.push("--fill-verbose"),{success:!0,prUrl:Is("gh",u,{cwd:t,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}catch(a){return{success:!1,error:a instanceof Error?a.message:String(a)}}}function Uo(t,e,r){if(!Pr())return{exists:!1,state:"none"};try{let n=["pr","list","--head",e,"--state","all","--json","url,number,title,state","--jq",".[0]"];r&&n.push("--repo",r);let i=Is("gh",n,{cwd:t,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!i)return{exists:!1,state:"none"};let a=JSON.parse(i),u=a.state.toLowerCase();return{exists:!0,state:u==="open"?"open":u==="merged"?"merged":u==="closed"?"closed":"none",url:a.url,number:a.number,title:a.title}}catch(n){return console.warn(`[worktree] Failed to sync PR status for ${e}: ${n instanceof Error?n.message:String(n)}`),{exists:!1,state:"none"}}}function Bc(t,e,r,n){if(!Pr())return!1;try{let o=["pr","comment",String(e),"--body",r];return n&&o.push("--repo",n),Is("gh",o,{cwd:t,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(o){return console.warn(`[worktree] Failed to comment on PR #${e}: ${o instanceof Error?o.message:String(o)}`),!1}}function an(t){if(t.kind==="merge"){let e=t.filesChanged!==void 0?` (${t.filesChanged} files, +${t.insertions??0}/-${t.deletions??0})`:"";return`\u2705 Merged: ${t.branch} \u2192 ${t.base??"main"}${e}`}return t.kind==="pr-updated"?`\u2705 PR updated: ${t.prUrl??""}`:t.targetRepo?`\u2705 PR opened against ${t.targetRepo}: ${t.prUrl??""}`:`\u2705 PR opened: ${t.prUrl??""}`}var Sp=De(()=>{Wo()});import{existsSync as Ip}from"fs";function Wc(){return new Date().toISOString()}function Zv(t){return t.worktreeLifecycle??{state:t.worktreePath||t.worktreeBranch?"provisioned":"none",updatedAt:Wc(),baseBranch:t.worktreeBaseBranch,targetRepo:t.worktreePrTargetRepo,pushRemote:t.worktreePushRemote}}function Xv(t){return t.worktreeLifecycle?.baseBranch??t.worktreeBaseBranch??(Ip(t.workdir)?wr(t.workdir):void 0)}function un(t,e={}){let r=Zv(t),n=Wc(),o=new Set,i=Ip(t.workdir),a=!!(t.worktreePath&&Ip(t.worktreePath)),u=t.worktreeBranch,p=Xv(t),d=!1,l=!1,m=!1,c=!1,h,y,k=t.worktreePrUrl?"open":"none",S=t.worktreePrUrl,x=t.worktreePrNumber;if(i||o.add("repo_missing"),u||o.add("branch_missing"),!a&&t.worktreePath&&o.add("worktree_missing"),e.activeSession&&o.add("active_session"),r.state==="pending_decision"&&o.add("pending_decision"),r.state==="merge_conflict_resolving"&&o.add("merge_conflict_resolving"),i&&u&&(d=qo(t.workdir,u),d||o.add("branch_missing")),a&&t.worktreePath&&(l=jn(t.worktreePath),l&&o.add("dirty_worktree_entries")),i&&d&&p){let or=Ec(t.workdir,u,p);h=or?.ahead,y=or?.behind,m=$c(t.workdir,u,p),m?o.add("topology_merged"):(c=Mc(t.workdir,u,p),c&&o.add("merge_noop_content_already_on_base"),!c&&(h??0)>0&&o.add("unique_content"))}else p||o.add("base_branch_missing");if(e.includePrSync&&i&&u){let or=Uo(t.workdir,u,t.worktreePrTargetRepo??r.targetRepo);k=or.state,S=or.url??S,x=or.number??x}k==="open"&&o.add("pr_open"),k==="merged"&&!m&&!c&&o.add("pr_merged_not_reflected_locally");let R=r.state;m?R="merged":c?R="released":!d&&r.state==="pending_decision"&&(R="cleanup_failed");let $=R==="merged"||R==="released",C=e.activeSession||l||!$&&r.state==="pending_decision"||r.state==="merge_conflict_resolving"||r.state==="pr_open"||k==="open"||o.has("pr_merged_not_reflected_locally"),xe=!C&&(R==="merged"||R==="released"||r.state==="dismissed"||r.state==="no_change"),kr={checkedAt:n,repoExists:i,branchExists:d,worktreeExists:a,activeSession:e.activeSession===!0,dirtyTracked:l,topologyMerged:m,releaseNoopMerge:c,branchAheadCount:h,baseAheadCount:y,prState:k,prUrl:S,prNumber:x,reasons:[...o]};return{lifecycle:r,evidence:kr,derivedState:R,cleanupSafe:xe,preserve:C,reasons:[...o]}}var Ko=De(()=>{Wo();Sp();kp()});var Pt=De(()=>{Wo();kp();Nc();Sp();Ko()});function Gn(t,e){let r=t.resolve(e),n=t.getPersistedSession(e),o=r?ke(r):n?ke(n):void 0;return{activeSession:r,persistedSession:n,persistedRef:o,sessionName:r?.name??n?.name??e,prompt:r?.prompt??n?.prompt,worktreePath:r?.worktreePath??n?.worktreePath,originalWorkdir:r?.originalWorkdir??n?.workdir,branchName:r?.worktreeBranch??n?.worktreeBranch,notificationTarget:r??(n?{id:o??e,name:n.name,harnessSessionId:n.harnessSessionId,backendRef:n.backendRef,route:n.route,originChannel:n.originChannel,originThreadId:n.originThreadId,originSessionKey:n.originSessionKey,goalTaskId:n.goalTaskId}:void 0)}}function Go(t){return[...t.persistedSession?lt(t.persistedSession):[],...t.activeSession?lt(t.activeSession):[]].filter((e,r,n)=>n.indexOf(e)===r)}function Fb(t,e){let r=[e.id,e.backendConversationId,e.harnessSessionId,e.name],n,o;for(let i of r)if(i&&(n??=t.resolve(i),o??=t.getPersistedSession(i),n&&o))break;return{activeSession:n,persistedSession:o}}function Es(t,e,r={}){let{activeSession:n,persistedSession:o}=Fb(t,e),i=un({workdir:e.workdir,worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeBaseBranch:r.baseBranch??o?.worktreeBaseBranch,worktreePrTargetRepo:o?.worktreePrTargetRepo,worktreePushRemote:o?.worktreePushRemote,worktreePrUrl:o?.worktreePrUrl,worktreePrNumber:o?.worktreePrNumber,worktreeLifecycle:o?.worktreeLifecycle},{activeSession:!!(n&&(n.status==="starting"||n.status==="running")),includePrSync:!!(o?.worktreeLifecycle?.state==="pr_open"||o?.worktreePrUrl)});return{activeSession:n,persistedSession:o,resolvedLifecycle:i}}function $s(t){let e=t.list("all").filter(o=>o.worktreePath),r=t.listPersistedSessions().filter(o=>o.worktreePath),n=new Map;for(let o of r){if(!o.worktreePath)continue;let i=q(o),a=o.sessionId??i??o.harnessSessionId;a&&n.set(a,{id:o.sessionId??i??o.harnessSessionId,name:o.name,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,workdir:o.workdir,worktreeMerged:o.worktreeMerged,worktreeMergedAt:o.worktreeMergedAt,worktreePrUrl:o.worktreePrUrl,backendConversationId:i,harnessSessionId:o.harnessSessionId})}for(let o of e)o.worktreePath&&n.set(o.id,{id:o.id,name:o.name,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,workdir:o.originalWorkdir??o.workdir,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0,backendConversationId:q(o),harnessSessionId:o.harnessSessionId});return Array.from(n.values())}function Ms(t,e){return t.id===e||t.name===e||t.backendConversationId===e||t.harnessSessionId===e}function dn(t){switch(t){case"none":return"none";case"provisioned":return"active";case"pending_decision":return"needs decision";case"merge_conflict_resolving":return"conflict resolving";case"pr_open":return"pr open";case"merged":return"merged";case"released":return"released";case"dismissed":return"dismissed";case"no_change":return"no change";case"cleanup_failed":return"cleanup failed";default:return t}}function Os(t){switch(t){case"active_session":return"active session";case"pending_decision":return"pending decision";case"merge_conflict_resolving":return"conflict resolving";case"dirty_tracked_changes":case"dirty_worktree_entries":return"dirty worktree";case"unique_content":return"still has unique content";case"topology_merged":return"merged by ancestry";case"merge_noop_content_already_on_base":return"content already on base";case"pr_open":return"PR open";case"pr_merged_not_reflected_locally":return"merged PR not reflected locally";case"repo_missing":return"repo missing";case"branch_missing":return"branch missing";case"worktree_missing":return"worktree missing";case"base_branch_missing":return"base branch missing";default:return t.replaceAll("_"," ")}}var Vo=De(()=>{Ee();Ko()});function Ls(t,e){return{...e,baseBranch:e.baseBranch??t.worktreeBaseBranch,targetRepo:e.targetRepo??t.worktreePrTargetRepo,pushRemote:e.pushRemote??t.worktreePushRemote}}function Fs(t,e={}){let r=e.updatedAt??new Date().toISOString(),n={pendingWorktreeDecisionSince:e.pendingSince??r,lastWorktreeReminderAt:void 0,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision",worktreeLifecycle:Ls(t,{state:"pending_decision",updatedAt:r,notes:e.notes})};return e.clearResolverSessionId&&(n.autoMergeResolverSessionId=void 0),n}function of(t,e,r,n={}){let o=n.updatedAt??new Date().toISOString();return{autoMergeConflictResolutionAttemptCount:r,autoMergeResolverSessionId:e,pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,lifecycle:"terminal",worktreeState:"merge_conflict_resolving",worktreeLifecycle:Ls(t,{state:"merge_conflict_resolving",updatedAt:o,notes:n.notes})}}function Ns(t,e={}){let r=e.updatedAt??new Date().toISOString(),n=e.resolvedAt??r,o={worktreeMerged:!0,worktreeMergedAt:e.mergedAt??n,lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:Ls(t,{state:"merged",updatedAt:r,resolvedAt:n,resolutionSource:e.resolutionSource??"agent_merge"})};return e.clearResolverSessionId&&(o.autoMergeResolverSessionId=void 0),o}function sf(t,e){let r=e.updatedAt??new Date().toISOString(),n={worktreePrUrl:e.prUrl,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDecisionSnoozedUntil:void 0,worktreeLifecycle:Ls(t,{state:"pr_open",updatedAt:r,resolutionSource:"agent_pr",baseBranch:e.baseBranch,targetRepo:e.targetRepo})};return e.prNumber!==void 0&&(n.worktreePrNumber=e.prNumber),e.disposition!==void 0&&(n.worktreeDisposition=e.disposition),n}var qs=De(()=>{});var gf={};Ct(gf,{buildPrCompletionWakeOutcomeKey:()=>Cp,buildPrMetadata:()=>cf,buildPrOutcomeDetailLines:()=>Rp,formatPrBody:()=>ff,makeAgentPrTool:()=>zo});import{existsSync as Bb}from"fs";function Wb(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function Rp(t){return[t.action==="opened"?`Opened PR for branch ${t.branchName} into ${t.baseBranch}.`:`Updated PR for branch ${t.branchName} into ${t.baseBranch}.`,...t.prUrl?[`PR URL: ${t.prUrl}.`]:[],...t.prNumber?[`PR number: #${t.prNumber}.`]:[],...t.targetRepo?[`Target repository: ${t.targetRepo}.`]:[],...t.commits!==void 0?[`Pushed ${t.commits} new commits (+${t.insertions??0}/-${t.deletions??0}).`]:[]]}function Cp(t){let e=t.prNumber!==void 0?`#${t.prNumber}`:t.prUrl??"unknown-pr",r=t.diffSummary?.commitMessages.map(o=>o.hash.trim()).filter(Boolean).join(","),n=t.action==="updated"?r||[`commits:${t.diffSummary?.commits??"unknown"}`,`insertions:${t.diffSummary?.insertions??"unknown"}`,`deletions:${t.diffSummary?.deletions??"unknown"}`].join(","):"created";return["worktree-pr",t.action,t.targetRepo??"default-repo",e,t.branchName,n].join(":")}function lf(t,e={preserveBlankLines:!0}){return t?.replace(/\r\n/g,`
|
|
11
|
+
`,"utf-8")}catch(s){`${i}${o}${s instanceof Error?s.message:String(s)}`}}function Wo(t,e,n={}){let r=Ds(e),o=$n(t);dp(t,o),Fs(o,{recursive:!0});let i=n.allowExistingBranch===!0,s,a,d=10,l=!1;for(let p=0;p<d;p++){let c=p===0?"":`-${Math.random().toString(16).slice(2,6)}`,f=`${o}/openclaw-worktree-${r}${c}`,g=`agent/${r}${c}`;if(!i&&Ot(t,g))continue;let h=!1;do{h=!1;try{Fs(f,{recursive:!1}),s=f,a=g;break}catch(y){if(sp(y,"EEXIST")){if(i&&p===0&&!l)try{No(f,{recursive:!0,force:!0}),l=!0,h=!0}catch(k){throw new Error(`Failed to recreate existing worktree branch ${g}: could not clear blocked path ${f}: ${k instanceof Error?k.message:String(k)}`)}else if(i&&p===0)throw new Error(`Failed to recreate existing worktree branch ${g}: path ${f} remains blocked after one cleanup attempt`);continue}throw y}}while(h);if(s&&a)break}if(!s||!a)throw new Error(`Failed to create unique worktree directory and branch after ${d} attempts`);let u=Ot(t,a);try{u?at("git",["-C",t,"worktree","add",s,a],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):at("git",["-C",t,"worktree","add","-b",a,s],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(p){try{No(s,{recursive:!0,force:!0})}catch{}throw p}return s}function dt(t){if(!Ks(t))return[];try{let e=at("git",["-C",t,"status","--porcelain","--untracked-files=all"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e?e.split(`
|
|
12
|
+
`).map(n=>n.trim()).filter(Boolean):[]}catch{return[]}}function lt(t){return dt(t).length>0}function me(t,e,n={}){let r=n.destructive===!0,o=dt(e);if(o.length>0&&!r)return`${e}${o[0]}`,!1;try{return at("git",["-C",t,"worktree","remove",...r?["--force"]:[],e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(i){if(`${e}${i instanceof Error?i.message:String(i)}`,!r)return!1;try{return No(e,{recursive:!0,force:!0}),`${e}`,!0}catch(s){return console.error(`[worktree] Both git worktree remove and rmSync failed for ${e}: ${s instanceof Error?s.message:String(s)}`),!1}}}function Nn(t){try{at("git",["-C",t,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}var Lo=j(()=>{Wt()});import{execFileSync as K}from"child_process";import{existsSync as lp}from"fs";function Ie(t,e,n){try{let r=K("git",["-C",t,"rev-list","--count",`${n}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(r.trim(),10),s=K("git",["-C",t,"diff","--shortstat",`${n}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),a=0,d=0,l=0,u=s.match(/(\d+)\s+files?\s+changed/);u&&(a=parseInt(u[1],10));let p=s.match(/(\d+)\s+insertions?\(/);p&&(d=parseInt(p[1],10));let c=s.match(/(\d+)\s+deletions?\(/);c&&(l=parseInt(c[1],10));let g=K("git",["-C",t,"diff","--name-only","--diff-filter=ACMR",`${n}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
13
|
+
`).map(k=>k.trim()).filter(Boolean),y=K("git",["-C",t,"log",`${n}..${e}`,"--format=%h|%s|%an","-n","5"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
14
|
+
`).filter(Boolean).map(k=>{let[b,A,I]=k.split("|");return{hash:b||"",message:A||"",author:I||""}});return{commits:o,filesChanged:a,insertions:d,deletions:l,changedFiles:g,commitMessages:y}}catch(r){`${r instanceof Error?r.message:String(r)}`;return}}function Wn(t,e,n="origin"){try{return K("git",["-C",t,"push",n,e],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(r){return`${e}${r instanceof Error?r.message:String(r)}`,!1}}function Us(t){try{return K("git",["-C",t,"status","--porcelain"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).split(`
|
|
15
|
+
`).some(n=>n.length>0&&!n.startsWith("??")&&!n.startsWith("!!"))}catch{return!1}}function Ln(t,e,n,r="merge",o){let i=!1,s,a=d=>{if(i)try{K("git",["-C",d,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(r==="squash"){if(K("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Us(t)){let c;try{c=K("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(f){return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${f instanceof Error?f.message:String(f)}. Commit or stash changes manually, then retry.`}}if(!c.includes("No local changes to save")){i=!0;try{s=K("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}K("git",["-C",t,"merge","--squash",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),K("git",["-C",t,"commit","-m",`Squash merge ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let p=!1;if(i)try{K("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{p=!0}return{success:!0,stashed:i||void 0,stashRef:s,stashPopConflict:p||void 0}}let d=o&&lp(o),l=d?o:t;if(d||K("git",["-C",t,"checkout",e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Us(t)){let p;try{p=K("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(c){try{K("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${c instanceof Error?c.message:String(c)}. Commit or stash changes manually, then retry.`}}if(!p.includes("No local changes to save")){i=!0;try{s=K("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{K("git",["-C",l,"rebase",n],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{K("git",["-C",l,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{K("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(t),{success:!1,rebaseConflict:!0,stashed:i||void 0,stashRef:s,error:[`Rebase of ${e} onto ${n} hit conflicts.`,"To resolve manually:",` cd ${l}`,` git rebase ${n}`," # resolve conflicts in each file, then:"," git add <file>"," git rebase --continue"," # repeat until rebase finishes, then re-run agent_merge."].join(`
|
|
16
|
+
`)}}K("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),K("git",["-C",t,"merge","--ff-only",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let u=!1;if(i)try{K("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{u=!0}return{success:!0,fastForward:!0,stashed:i||void 0,stashRef:s,stashPopConflict:u||void 0}}catch(d){try{K("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(t),{success:!1,error:d instanceof Error?d.message:String(d),stashed:i||void 0,stashRef:s}}}var Vs=j(()=>{});import{execFileSync as Bn}from"child_process";function Gs(t,e,n,r,o,i){if(!_e())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let s;if(i)try{let p=Bn("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[:/]([^/]+)\/[^/]+(?:\.git)?$/);p&&(s=p[1])}catch{}let a=["pr","create","--base",n];return i&&a.push("--repo",i),s?a.push("--head",`${s}:${e}`):a.push("--head",e),r&&o?a.push("--title",r,"--body",o):a.push("--fill-verbose"),{success:!0,prUrl:Bn("gh",a,{cwd:t,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}function Lt(t,e,n){if(!_e())return{exists:!1,state:"none"};try{let r=["pr","list","--head",e,"--state","all","--json","url,number,title,state","--jq",".[0]"];n&&r.push("--repo",n);let i=Bn("gh",r,{cwd:t,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!i)return{exists:!1,state:"none"};let s=JSON.parse(i),a=s.state.toLowerCase();return{exists:!0,state:a==="open"?"open":a==="merged"?"merged":a==="closed"?"closed":"none",url:s.url,number:s.number,title:s.title}}catch(r){return`${e}${r instanceof Error?r.message:String(r)}`,{exists:!1,state:"none"}}}function Hs(t,e,n,r){if(!_e())return!1;try{let o=["pr","comment",String(e),"--body",n];return r&&o.push("--repo",r),Bn("gh",o,{cwd:t,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(o){return`${e}${o instanceof Error?o.message:String(o)}`,!1}}function qe(t){if(t.kind==="merge"){let e=t.filesChanged!==void 0?` (${t.filesChanged} files, +${t.insertions??0}/-${t.deletions??0})`:"";return`â
Merged: ${t.branch} â ${t.base??"main"}${e}`}return t.kind==="pr-updated"?`â
PR updated: ${t.prUrl??""}`:t.targetRepo?`â
PR opened against ${t.targetRepo}: ${t.prUrl??""}`:`â
PR opened: ${t.prUrl??""}`}var Bo=j(()=>{Wt()});import{existsSync as Fo}from"fs";function js(){return new Date().toISOString()}function up(t){return t.worktreeLifecycle??{state:t.worktreePath||t.worktreeBranch?"provisioned":"none",updatedAt:js(),baseBranch:t.worktreeBaseBranch,targetRepo:t.worktreePrTargetRepo,pushRemote:t.worktreePushRemote}}function pp(t){return t.worktreeLifecycle?.baseBranch??t.worktreeBaseBranch??(Fo(t.workdir)?Pe(t.workdir):void 0)}function Ke(t,e={}){let n=up(t),r=js(),o=new Set,i=Fo(t.workdir),s=!!(t.worktreePath&&Fo(t.worktreePath)),a=t.worktreeBranch,d=pp(t),l=!1,u=!1,p=!1,c=!1,f,g,h=t.worktreePrUrl?"open":"none",y=t.worktreePrUrl,k=t.worktreePrNumber;if(i||o.add("repo_missing"),a||o.add("branch_missing"),!s&&t.worktreePath&&o.add("worktree_missing"),e.activeSession&&o.add("active_session"),n.state==="pending_decision"&&o.add("pending_decision"),n.state==="merge_conflict_resolving"&&o.add("merge_conflict_resolving"),i&&a&&(l=Ot(t.workdir,a),l||o.add("branch_missing")),s&&t.worktreePath&&(u=lt(t.worktreePath),u&&o.add("dirty_worktree_entries")),i&&l&&d){let R=Ns(t.workdir,a,d);f=R?.ahead,g=R?.behind,p=Ws(t.workdir,a,d),p?o.add("topology_merged"):(c=Ls(t.workdir,a,d),c&&o.add("merge_noop_content_already_on_base"),!c&&(f??0)>0&&o.add("unique_content"))}else d||o.add("base_branch_missing");if(e.includePrSync&&i&&a){let R=Lt(t.workdir,a,t.worktreePrTargetRepo??n.targetRepo);h=R.state,y=R.url??y,k=R.number??k}h==="open"&&o.add("pr_open"),h==="merged"&&!p&&!c&&o.add("pr_merged_not_reflected_locally");let b=n.state;p?b="merged":c?b="released":!l&&n.state==="pending_decision"&&(b="cleanup_failed");let A=b==="merged"||b==="released",I=e.activeSession||u||!A&&n.state==="pending_decision"||n.state==="merge_conflict_resolving"||n.state==="pr_open"||h==="open"||o.has("pr_merged_not_reflected_locally"),W=!I&&(b==="merged"||b==="released"||n.state==="dismissed"||n.state==="no_change"),S={checkedAt:r,repoExists:i,branchExists:l,worktreeExists:s,activeSession:e.activeSession===!0,dirtyTracked:u,topologyMerged:p,releaseNoopMerge:c,branchAheadCount:f,baseAheadCount:g,prState:h,prUrl:y,prNumber:k,reasons:[...o]};return{lifecycle:n,evidence:S,derivedState:b,cleanupSafe:W,preserve:I,reasons:[...o]}}var Bt=j(()=>{Wt();Bo();Lo()});var fe=j(()=>{Wt();Lo();Vs();Bo();Bt()});function ut(t,e){let n=t.resolve(e),r=t.getPersistedSession(e),o=n?N(n):r?N(r):void 0;return{activeSession:n,persistedSession:r,persistedRef:o,sessionName:n?.name??r?.name??e,prompt:n?.prompt??r?.prompt,worktreePath:n?.worktreePath??r?.worktreePath,originalWorkdir:n?.originalWorkdir??r?.workdir,branchName:n?.worktreeBranch??r?.worktreeBranch,notificationTarget:n??(r?{id:o??e,name:r.name,harnessSessionId:r.harnessSessionId,backendRef:r.backendRef,route:r.route,originChannel:r.originChannel,originThreadId:r.originThreadId,originSessionKey:r.originSessionKey,goalTaskId:r.goalTaskId}:void 0)}}function qt(t){return[...t.persistedSession?ae(t.persistedSession):[],...t.activeSession?ae(t.activeSession):[]].filter((e,n,r)=>r.indexOf(e)===n)}function Jp(t,e){let n=[e.id,e.backendConversationId,e.harnessSessionId,e.name],r,o;for(let i of n)if(i&&(r??=t.resolve(i),o??=t.getPersistedSession(i),r&&o))break;return{activeSession:r,persistedSession:o}}function Qn(t,e,n={}){let{activeSession:r,persistedSession:o}=Jp(t,e),i=Ke({workdir:e.workdir,worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeBaseBranch:n.baseBranch??o?.worktreeBaseBranch,worktreePrTargetRepo:o?.worktreePrTargetRepo,worktreePushRemote:o?.worktreePushRemote,worktreePrUrl:o?.worktreePrUrl,worktreePrNumber:o?.worktreePrNumber,worktreeLifecycle:o?.worktreeLifecycle},{activeSession:!!(r&&(r.status==="starting"||r.status==="running")),includePrSync:!!(o?.worktreeLifecycle?.state==="pr_open"||o?.worktreePrUrl)});return{activeSession:r,persistedSession:o,resolvedLifecycle:i}}function Jn(t){let e=t.list("all").filter(o=>o.worktreePath),n=t.listPersistedSessions().filter(o=>o.worktreePath),r=new Map;for(let o of n){if(!o.worktreePath)continue;let i=T(o),s=o.sessionId??i??o.harnessSessionId;s&&r.set(s,{id:o.sessionId??i??o.harnessSessionId,name:o.name,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,workdir:o.workdir,worktreeMerged:o.worktreeMerged,worktreeMergedAt:o.worktreeMergedAt,worktreePrUrl:o.worktreePrUrl,backendConversationId:i,harnessSessionId:o.harnessSessionId})}for(let o of e)o.worktreePath&&r.set(o.id,{id:o.id,name:o.name,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,workdir:o.originalWorkdir??o.workdir,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0,backendConversationId:T(o),harnessSessionId:o.harnessSessionId});return Array.from(r.values())}function Yn(t,e){return t.id===e||t.name===e||t.backendConversationId===e||t.harnessSessionId===e}function Ve(t){switch(t){case"none":return"none";case"provisioned":return"active";case"pending_decision":return"needs decision";case"merge_conflict_resolving":return"conflict resolving";case"pr_open":return"pr open";case"merged":return"merged";case"released":return"released";case"dismissed":return"dismissed";case"no_change":return"no change";case"cleanup_failed":return"cleanup failed";default:return t}}function Zn(t){switch(t){case"active_session":return"active session";case"pending_decision":return"pending decision";case"merge_conflict_resolving":return"conflict resolving";case"dirty_tracked_changes":case"dirty_worktree_entries":return"dirty worktree";case"unique_content":return"still has unique content";case"topology_merged":return"merged by ancestry";case"merge_noop_content_already_on_base":return"content already on base";case"pr_open":return"PR open";case"pr_merged_not_reflected_locally":return"merged PR not reflected locally";case"repo_missing":return"repo missing";case"branch_missing":return"branch missing";case"worktree_missing":return"worktree missing";case"base_branch_missing":return"base branch missing";default:return t.replaceAll("_"," ")}}var Kt=j(()=>{Q();Bt()});function fa(t,e={preserveBlankLines:!0}){return t?.replace(/\r\n/g,`
|
|
14
17
|
`).split(`
|
|
15
|
-
`).map(
|
|
16
|
-
`:" ").replace(/[ \t]+/g," ").trim()||void 0}function
|
|
17
|
-
`)}function
|
|
18
|
+
`).map(r=>r.trim()).reduce((r,o)=>o?(r.push(o),r):(e.preserveBlankLines&&r[r.length-1]!==""&&r.push(o),r),[]).join(e.preserveBlankLines?`
|
|
19
|
+
`:" ").replace(/[ \t]+/g," ").trim()||void 0}function Xp(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3)).trimEnd()}...`}function zo(t){return t.replace(/\b[A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd|pwd|credential|credentials|authorization|auth)[A-Za-z0-9_-]*\b\s*[:=]\s*["']?[^"'\s,;)]+/gi,"[redacted credential]").replace(/\b(?:api key|token|secret|password|credential|credentials)\s+\[redacted credential\]/gi,"[redacted credential]").replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{16,}\b/g,"[redacted token]").replace(/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,"[redacted token]").replace(/\bsk-[A-Za-z0-9_-]{20,}\b/g,"[redacted token]").replace(/\bxox[baprs]-[A-Za-z0-9-]{20,}\b/g,"[redacted token]").replace(/\bAKIA[0-9A-Z]{16}\b/g,"[redacted token]").replace(/\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\b/g,"[redacted token]").replace(/\bhttps?:\/\/\S+/gi,"[redacted link]").replace(/\b[A-Z]:\\(?:Users|Documents and Settings)\\[^\s`'")]+/gi,"[redacted path]").replace(/(?:^|[\s(])\/(?:home|Users|var|etc|private|tmp)\/[^\s`'").]+/g,e=>`${e.startsWith(" ")||e.startsWith("(")?e[0]:""}[redacted path]`).replace(new RegExp("\\b[A-Za-z0-9_-]{32,}\\b","g"),"[redacted token]")}function pa(t){return/\b[A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd|pwd|credential|credentials|authorization|auth)[A-Za-z0-9_-]*\b\s*[:=]\s*["']?[^"'\s,;)]+/i.test(t)||/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{16,}\b/.test(t)||/\bgithub_pat_[A-Za-z0-9_]{20,}\b/.test(t)||/\bsk-[A-Za-z0-9_-]{20,}\b/.test(t)||/\bxox[baprs]-[A-Za-z0-9-]{20,}\b/.test(t)||/\bAKIA[0-9A-Z]{16}\b/.test(t)||/\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\b/.test(t)||/\bhttps?:\/\/\S+/i.test(t)||/\b[A-Z]:\\(?:Users|Documents and Settings)\\[^\s`'")]+/i.test(t)||/(?:^|[\s(])\/(?:home|Users|var|etc|private|tmp)\/[^\s`'").]+/.test(t)||new RegExp("\\b[A-Za-z0-9_-]{32,}\\b").test(t)}function ec(t){let e=fa(t);if(!e)return;let n=e.match(/^[^.!?]+[.!?]/)?.[0]??e,r=zo(n).replace(/\s+/g," ").trim();return r?Xp(r,180):void 0}function ga(t){return zo(t.trim()).replace(/\s+/g," ").trim()}function tc(t,e){return t?.commitMessages.map(n=>ga(n.message)).filter(Boolean).slice(0,e)??[]}function nc(){return["Not recorded by agent_pr. Review CI/checks and session output before merging."]}function rc(){return["Generated PR metadata omits full task prompts and redacts sensitive-looking prompt details.","Review touched areas for behavior, security, and privacy impact."]}function oc(t){let e=ec(t.prompt),n=t.diffSummary;return{sessionName:t.sessionName,objective:e,stats:n?{commits:n.commits,filesChanged:n.filesChanged,insertions:n.insertions,deletions:n.deletions}:void 0,changedFiles:n?.changedFiles??[],commitSubjects:tc(n,5),validation:nc(),notes:rc()}}function tr(t,e,n){return Array.isArray(t)&&t.length>0&&t.length<=e&&t.every(r=>typeof r=="string"&&r.trim().length>0&&r.length<=n)}function ic(t,e){let n=fa(t);if(!n)return[];let r=e?.toLowerCase();return n.split(/[.!?\n]/).map(o=>o.trim()).filter(o=>o.length>=24).filter(o=>!r||o.toLowerCase()!==r.replace(/[.!?]$/,"")).map(o=>o.toLowerCase())}function ca(t,e,n){let r=t.toLowerCase();return ic(e,n.objective).some(o=>r.includes(o))}function ma(t){return/^(?:node|next|nuxt|vue|express|nest|three|d3|chart|ember|backbone|require)\.js$/i.test(t)}function sc(t,e){let n=new Set(e.changedFiles);if([...t.matchAll(/(?:^|[^\w.-])((?:\.?[\w-][\w.-]*\/)+(?:\.?[\w-][\w.-]*))(?![\w.-])/g)].map(c=>c[1]).some(c=>/\.[A-Za-z0-9]+$/.test(c)&&!n.has(c)))return!0;let o=new Set(e.changedFiles.filter(c=>!c.includes("/"))),i=String.raw`\.[a-z0-9][\w.-]*`,s=t.matchAll(new RegExp(`[\\\`"'](${i})[\\\`"']`,"g"));for(let c of s)if(!o.has(c[1]))return!0;let a=t.matchAll(new RegExp(String.raw`\b(?:file|files|path|paths|changed|changes|updated?|updates?|modified?|modifies|touched?|touches|added?|adds?|removed?|removes?|deleted?|deletes?)\s+(?:the\s+)?(${i})(?![\w.-])`,"gi"));for(let c of a)if(!o.has(c[1]))return!0;if(o.size===0)return!1;let d=new Set([...o].map(c=>c.match(/\.([A-Za-z0-9]+)$/)?.[1]?.toLowerCase()).filter(c=>!!c)),l=String.raw`[A-Za-z0-9][\w.-]*\.([A-Za-z0-9]+)`,u=t.matchAll(new RegExp(`[\\\`"'](${l})[\\\`"']`,"g"));for(let c of u){let f=c[1],g=c[2]?.toLowerCase();if(g!==void 0&&d.has(g)&&!o.has(f)&&!ma(f))return!0}return[...t.matchAll(new RegExp(String.raw`\b(?:file|files|path|paths|changed|changes|updated?|updates?|modified?|modifies|touched?|touches|added?|adds?|removed?|removes?|deleted?|deletes?)\s+(?:the\s+)?(${l})\b`,"gi"))].some(c=>{let f=c[1],g=c[2]?.toLowerCase();return g!==void 0&&d.has(g)&&!o.has(f)&&!ma(f)})}function Ut(t){return zo(t).replace(/\s+/g," ").trim()}function ac(t,e,n){if(!t||typeof t!="object")return;let r=t;if(typeof r.title!="string"||r.title.trim().length===0||r.title.length>90||!tr(r.summary,5,180)||!tr(r.changes,10,160)||!tr(r.validation,5,160)||!tr(r.notes,5,180)||[r.title,...r.summary,...r.changes,...r.validation,...r.notes].some(a=>pa(a)||ca(a,n,e)))return;let i={title:Ut(r.title),summary:r.summary.map(Ut),changes:r.changes.map(Ut),validation:r.validation.map(Ut),notes:r.notes.map(Ut)},s=[i.title,...i.summary,...i.changes,...i.validation,...i.notes];if(!s.some(a=>!a||pa(a)||ca(a,n,e))&&!s.some(a=>sc(a,e)))return i}async function nr(t){let e=oc(t);if(!t.provider)return{ok:!1,error:"PR metadata generation requires an LLM metadata provider. Pass explicit title and body, or configure a provider before creating the PR.",evidence:e};try{let n=await t.provider.generatePrMetadata(e),r=ac(n,e,t.prompt);return r?{ok:!0,metadata:r,evidence:e}:{ok:!1,error:"LLM-generated PR metadata failed schema or safety validation. Pass explicit title/body or retry after correcting the provider output.",evidence:e}}catch(n){return`${n instanceof Error?n.message:String(n)}`,{ok:!1,error:"PR metadata provider failed. Pass explicit title/body or retry after the provider is healthy.",evidence:e}}}function rr(t){let e=[`OpenClaw Code Agent session: ${t.sessionName}`,"","## Summary",...t.metadata.summary.map(n=>`- ${n}`),"","## Changes",...t.metadata.changes.map(n=>`- ${n}`),""];if(t.diffSummary){let n=t.diffSummary.commitMessages.slice(0,5).map(o=>`- ${o.hash} ${ga(o.message)} (${o.author})`),r=t.diffSummary.commits>5?[`- ...and ${t.diffSummary.commits-5} more`]:[];n.length>0&&e.push("## Commits",...n,...r,"")}return e.push("## Validation",...t.metadata.validation.map(n=>`- ${n}`),"","## Notes / Risks",...t.metadata.notes.map(n=>`- ${n}`),""),e.push("---","Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"),e.join(`
|
|
20
|
+
`)}var Qo=j(()=>{});function or(t,e){return{...e,baseBranch:e.baseBranch??t.worktreeBaseBranch,targetRepo:e.targetRepo??t.worktreePrTargetRepo,pushRemote:e.pushRemote??t.worktreePushRemote}}function ir(t,e={}){let n=e.updatedAt??new Date().toISOString(),r={pendingWorktreeDecisionSince:e.pendingSince??n,lastWorktreeReminderAt:void 0,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision",worktreeLifecycle:or(t,{state:"pending_decision",updatedAt:n,notes:e.notes})};return e.clearResolverSessionId&&(r.autoMergeResolverSessionId=void 0),r}function ha(t,e,n,r={}){let o=r.updatedAt??new Date().toISOString();return{autoMergeConflictResolutionAttemptCount:n,autoMergeResolverSessionId:e,pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,lifecycle:"terminal",worktreeState:"merge_conflict_resolving",worktreeLifecycle:or(t,{state:"merge_conflict_resolving",updatedAt:o,notes:r.notes})}}function sr(t,e={}){let n=e.updatedAt??new Date().toISOString(),r=e.resolvedAt??n,o={worktreeMerged:!0,worktreeMergedAt:e.mergedAt??r,lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:or(t,{state:"merged",updatedAt:n,resolvedAt:r,resolutionSource:e.resolutionSource??"agent_merge"})};return e.clearResolverSessionId&&(o.autoMergeResolverSessionId=void 0),o}function Sa(t,e){let n=e.updatedAt??new Date().toISOString(),r={worktreePrUrl:e.prUrl,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDecisionSnoozedUntil:void 0,worktreeLifecycle:or(t,{state:"pr_open",updatedAt:n,resolutionSource:"agent_pr",baseBranch:e.baseBranch,targetRepo:e.targetRepo})};return e.prNumber!==void 0&&(r.worktreePrNumber=e.prNumber),e.disposition!==void 0&&(r.worktreeDisposition=e.disposition),r}var ar=j(()=>{});var ya={};ol(ya,{buildPrCompletionWakeOutcomeKey:()=>Yo,buildPrMetadata:()=>nr,buildPrOutcomeDetailLines:()=>Jo,formatPrBody:()=>rr,makeAgentPrTool:()=>Vt});import{existsSync as dc}from"fs";function lc(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function Jo(t){return[t.action==="opened"?`Opened PR for branch ${t.branchName} into ${t.baseBranch}.`:`Updated PR for branch ${t.branchName} into ${t.baseBranch}.`,...t.prUrl?[`PR URL: ${t.prUrl}.`]:[],...t.prNumber?[`PR number: #${t.prNumber}.`]:[],...t.targetRepo?[`Target repository: ${t.targetRepo}.`]:[],...t.commits!==void 0?[`Pushed ${t.commits} new commits (+${t.insertions??0}/-${t.deletions??0}).`]:[]]}function Yo(t){let e=t.prNumber!==void 0?`#${t.prNumber}`:t.prUrl??"unknown-pr",n=t.diffSummary?.commitMessages.map(o=>o.hash.trim()).filter(Boolean).join(","),r=t.action==="updated"?n||[`commits:${t.diffSummary?.commits??"unknown"}`,`insertions:${t.diffSummary?.insertions??"unknown"}`,`deletions:${t.diffSummary?.deletions??"unknown"}`].join(","):"created";return["worktree-pr",t.action,t.targetRepo??"default-repo",e,t.branchName,r].join(":")}function Vt(t,e={}){return{name:"agent_pr",description:"Create or update a GitHub PR for a worktree branch. Handles full PR lifecycle: creates new PRs, updates existing open PRs with comments, and handles merged/closed PRs. Pushes the branch, syncs PR state, and persists metadata.",parameters:m.Object({session:m.String({description:"Session name or ID to create/update PR for"}),title:m.Optional(m.String({description:"PR title (default: auto-generated from session name)"})),body:m.Optional(m.String({description:"PR body (default: auto-generated from commit summary)"})),base_branch:m.Optional(m.String({description:"Base branch for the PR (default: detected from repo)"})),force_new:m.Optional(m.Boolean({description:"Force creation of a new PR even if one exists (default: false)"})),target_repo:m.Optional(m.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex'). Auto-detected from 'upstream' remote if not set."}))}),async execute(n,r){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}],meta:{success:!1,state:"error"}};if(!lc(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}],meta:{success:!1,state:"error"}};if(!_e())return{content:[{type:"text",text:"Error: GitHub CLI (gh) is not available. Install it and authenticate to create PRs."}],meta:{success:!1,state:"error"}};let o=ut(v,r.session),i=o.activeSession,s=o.persistedSession;if(!i&&!s)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}],meta:{success:!1,state:"error"}};let{worktreePath:a,originalWorkdir:d,sessionName:l,branchName:u}=o;if(!a||!d)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}],meta:{success:!1,state:"error"}};if(!u)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree ${a}. The worktree may have been removed and no persisted branch name is available.`}],meta:{success:!1,state:"error"}};dc(a)||`${a}${u}${d}`;let p=r.base_branch??Pe(d),c=h=>{let y=Sa({worktreeBaseBranch:s?.worktreeBaseBranch??i?.worktreeBaseBranch??p,worktreePrTargetRepo:s?.worktreePrTargetRepo??i?.worktreePrTargetRepo,worktreePushRemote:s?.worktreePushRemote??i?.worktreePushRemote},{prUrl:h.prUrl,prNumber:h.prNumber,baseBranch:p,targetRepo:h.targetRepo,disposition:h.disposition});for(let k of qt(o))v.updatePersistedSession(k,y)},f=Bs(d,r.target_repo??s?.worktreePrTargetRepo);if(!Wn(d,u))return{content:[{type:"text",text:`â Failed to push ${u} â cannot create/update PR`}],meta:{success:!1,state:"error"}};let g=Lt(d,u,f);if(r.force_new&&g.exists)return{content:[{type:"text",text:`â ī¸ Cannot create new PR: A PR already exists for ${u} (${g.state}).
|
|
18
21
|
|
|
19
|
-
Existing PR: ${
|
|
22
|
+
Existing PR: ${g.url}
|
|
20
23
|
|
|
21
|
-
To create a new PR, you must first close/merge the existing PR manually or use a different branch.`}],meta:{success:!1,state:"error"}};if(
|
|
22
|
-
`),
|
|
23
|
-
...and ${
|
|
24
|
-
`);if(
|
|
24
|
+
To create a new PR, you must first close/merge the existing PR manually or use a different branch.`}],meta:{success:!1,state:"error"}};if(g.exists&&g.state==="open"){let h=Ie(d,u,p);if(h&&h.commits>0){let y=h.commitMessages.slice(0,5).map(I=>`âĸ ${I.hash} ${I.message} (${I.author})`).join(`
|
|
25
|
+
`),k=h.commits>5?`
|
|
26
|
+
...and ${h.commits-5} more commits`:"",b=["đ **New commits pushed**","",`${h.commits} new commits (+${h.insertions} / -${h.deletions})`,"","### Latest commits:",y+k,"","---","đ¤ [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
|
|
27
|
+
`);if(Hs(d,g.number,b,f)){c({prUrl:g.url,prNumber:g.number,targetRepo:f});let I=qe({kind:"pr-updated",branch:u,prUrl:g.url});return v.notifyWorktreeOutcome(o.notificationTarget,I,{completionWakeOutcomeKey:Yo({action:"updated",branchName:u,prUrl:g.url,prNumber:g.number,targetRepo:f,diffSummary:h}),detailLines:Jo({action:"updated",branchName:u,baseBranch:p,prUrl:g.url,prNumber:g.number,targetRepo:f,commits:h.commits,insertions:h.insertions,deletions:h.deletions})}),{content:[{type:"text",text:`${I}
|
|
25
28
|
|
|
26
|
-
|
|
29
|
+
đ Added comment detailing ${h.commits} new commits (+${h.insertions} / -${h.deletions})`}],meta:{success:!0,state:"pr_updated"}}}else return{content:[{type:"text",text:`â ī¸ Pushed to ${g.url} but failed to add comment.
|
|
27
30
|
|
|
28
|
-
${
|
|
31
|
+
${h.commits} new commits (+${h.insertions} / -${h.deletions})`}],meta:{success:!0,state:"pr_open"}}}else return c({prUrl:g.url,prNumber:g.number,targetRepo:f}),{content:[{type:"text",text:`âšī¸ PR already exists and is up to date: ${g.url}
|
|
29
32
|
|
|
30
|
-
No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else if(
|
|
33
|
+
No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else if(g.exists&&g.state==="merged"){let h={...sr({worktreeBaseBranch:s?.worktreeBaseBranch??i?.worktreeBaseBranch??p,worktreePrTargetRepo:s?.worktreePrTargetRepo??i?.worktreePrTargetRepo,worktreePushRemote:s?.worktreePushRemote??i?.worktreePushRemote},{resolutionSource:"agent_pr",clearResolverSessionId:!0}),worktreePrUrl:g.url,worktreePrNumber:g.number,worktreeDisposition:"merged",worktreeDecisionSnoozedUntil:void 0};for(let y of qt(o))v.updatePersistedSession(y,h);return{content:[{type:"text",text:`â
PR was already merged: ${g.url}
|
|
31
34
|
|
|
32
|
-
The worktree branch ${
|
|
35
|
+
The worktree branch ${u} can be cleaned up with agent_merge(delete_branch=true).`}],meta:{success:!0,state:"merged"}}}else{if(g.exists&&g.state==="closed")return{content:[{type:"text",text:`â ī¸ A PR exists but was closed without merging: ${g.url}
|
|
33
36
|
|
|
34
37
|
What would you like to do?
|
|
35
38
|
|
|
@@ -37,202 +40,204 @@ What would you like to do?
|
|
|
37
40
|
2. Close and delete the branch with agent_merge(delete_branch=true), then start a new session/worktree
|
|
38
41
|
3. Manually delete the closed PR on GitHub, then call agent_pr(force_new=true) to create a fresh PR
|
|
39
42
|
|
|
40
|
-
(This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}],meta:{success:!1,state:"closed"}};{let
|
|
41
|
-
`)}function
|
|
42
|
-
`).map(
|
|
43
|
-
`)}function
|
|
44
|
-
`):"",
|
|
45
|
-
`):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",
|
|
43
|
+
(This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}],meta:{success:!1,state:"closed"}};{let h=!r.title||!r.body?Ie(d,u,p):void 0,y;if(!r.title||!r.body){let I=await nr({sessionName:l,prompt:o.prompt,diffSummary:h,provider:e.metadataProvider});if(I.ok===!1)return{content:[{type:"text",text:`â ${I.error}`}],meta:{success:!1,state:"error"}};y=I.metadata}let k=r.title??y.title,b=r.body;b||(b=rr({sessionName:l,metadata:y,diffSummary:h}));let A=Gs(d,u,p,k,b,f);if(A.success&&A.prUrl){let I=Lt(d,u,f);c({prUrl:A.prUrl,prNumber:I.number,targetRepo:f,disposition:"pr-opened"});let W=qe({kind:"pr-opened",branch:u,targetRepo:f,prUrl:A.prUrl});return v.notifyWorktreeOutcome(o.notificationTarget,W,{completionWakeOutcomeKey:Yo({action:"opened",branchName:u,prUrl:A.prUrl,prNumber:I.number,targetRepo:f}),detailLines:Jo({action:"opened",branchName:u,baseBranch:p,prUrl:A.prUrl,prNumber:I.number,targetRepo:f})}),{content:[{type:"text",text:W}],meta:{success:!0,state:"created"}}}else return{content:[{type:"text",text:`â Failed to create PR: ${A.error??"unknown error"}`}],meta:{success:!1,state:"error"}}}}}}}var dr=j(()=>{X();O();fe();Qo();ar();Kt();Qo()});import{readdirSync as wg,statSync as Pg,rmSync as bg}from"fs";import{execFileSync as Ag}from"child_process";import{join as Yd}from"path";X();O();function al(t){return t.length>80?`${t.slice(0,80)}...`:t}function dl(t){return t.worktreePath?!t.originalWorkdir||t.originalWorkdir===t.worktreePath?`${t.worktreePath} (worktree)`:`${t.worktreePath} (worktree of ${t.originalWorkdir})`:t.workdir}function ll(t){let e=["Session launched successfully.",` Name: ${t.sessionName}`,` ID: ${t.sessionId}`,` Harness: ${t.harness}`,` Permission mode: ${t.permissionMode}`,` Plan approval: ${t.planApproval}`,` Worktree strategy: ${t.worktreeStrategy??"off"}`,` Resolved workdir: ${dl(t)}`,` Model: ${t.model??"default"}`,` Prompt: "${al(t.prompt)}"`];return t.reasoningEffort&&e.push(` Reasoning effort: ${t.reasoningEffort}`),t.fastMode&&e.push(" Fast mode: enabled"),t.resumeSessionId?e.push(` Resume: ${t.resumeSessionId}${t.forkSession?" (forked)":""}`):t.forceNewSession&&e.push(" Force new session: true"),t.clearedPersistedCodexResume&&e.push(" Thread state: historical Codex state cleared; starting a fresh thread."),e.push(" Mode: multi-turn (use agent_respond to send follow-up messages)"),e.push("","Use agent_sessions to check status, agent_output to see output."),e.join(`
|
|
44
|
+
`)}function Xt(t,e){return ll({...t,sessionId:e.id,sessionName:e.name,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,worktreeStrategy:e.worktreeStrategy??"off",worktreePath:e.worktreePath,originalWorkdir:e.originalWorkdir})}te();function Ze(t){let{requestedResumeSessionId:e,activeSession:n,persistedSession:r}=t;return e?n?{resumeSessionId:e,clearedPersistedCodexResume:!1}:r?.harness==="codex"&&r.backendRef?.kind!=="codex-app-server"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:e,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}Q();function gn(t){return"id"in t?t.id:t.sessionId}function _t(t){return t.status==="completed"||t.killReason==="done"}function Ru(t){return!_t(t)||!T(t)?!1:t.backendRef?.kind==="codex-app-server"||t.backendRef?.kind==="opencode-server"}function Iu(t){return(t.killReason==="shutdown"||t.killReason==="startup-timeout")&&!T(t)}function Et(t){if(t.status==="running")return{kind:"direct",reason:"already_running"};let e=gn(t);if(_t(t)&&!Ru(t))return{kind:"unavailable",reason:"completed",stableSessionId:e};let n=T(t);if(n){let r="harnessName"in t?void 0:t,{resumeSessionId:o,clearedPersistedCodexResume:i}=Ze({requestedResumeSessionId:n,activeSession:"harnessName"in t?{harnessSessionId:n}:void 0,persistedSession:r?{harness:r.harness,backendRef:r.backendRef}:void 0});return o?{kind:"resume",resumeSessionId:o,stableSessionId:e,clearedPersistedCodexResume:i}:{kind:"unavailable",reason:"legacy_non_resumable",stableSessionId:e,clearedPersistedCodexResume:i}}return Iu(t)?{kind:"relaunch",stableSessionId:e}:{kind:"unavailable",reason:"missing_backend_state",stableSessionId:e}}te();import{existsSync as gs}from"fs";function hn(t,e){if(!e||e.length===0)return!0;if(!t)return!1;let n=t.toLowerCase();return e.some(r=>n.includes(r.toLowerCase()))}Q();function cs(t){return t==null?void 0:String(t).trim()||void 0}function xu(t){return t.trim().replace(/^['"`](.*)['"`]$/s,"$1").trim()}function Tu(t){let e=t.split(/\n\s*\n/,1)[0]?.split(`
|
|
45
|
+
`).map(n=>n.trim()).filter(Boolean)??[];if(e.length!==0)for(let n of e){let r=n.match(/^(Workdir|Repo):\s*(.+)$/),o=xu(r?.[2]??"");if(o.startsWith("/")&&gs(o))return o}}function ms(t,e){return t.workdir!==e.workdir?!1:e.originSessionKey&&t.originSessionKey?t.originSessionKey===e.originSessionKey:!e.originChannel||!t.originChannel?!1:t.originChannel===e.originChannel&&cs(t.originThreadId)===cs(e.originThreadId)}function fs(t){return t.slice(0,3).map(e=>` - ${e.name} [${e.ref}] | status=${e.status}${e.lifecycle?` | lifecycle=${e.lifecycle}`:""}`).join(`
|
|
46
|
+
`)}function Cu(t,e){let n=[],r=[],o=new Set;for(let i of t.list?.("all")??[]){if(!ms(i,e))continue;let s=i.id;if(!o.has(s)){if(o.add(s),i.isExplicitlyResumable){n.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0});continue}(i.status==="starting"||i.status==="running")&&r.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!1})}}for(let i of t.listPersistedSessions?.()??[]){if(!i.resumable||!ms(i,e))continue;let s=N(i)??i.harnessSessionId,a=i.sessionId??T(i)??i.harnessSessionId;!s||!a||o.has(a)||(o.add(a),n.push({ref:s,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0}))}return{resumable:n,active:r}}function Sn(t,e,n){let r=t.workdir||Tu(t.prompt)||e.workspaceDir||E.defaultWorkdir||process.cwd();if(!gs(r))return{kind:"error",text:`Error: Working directory does not exist: ${r}`};let o=t.harness??se(),i=Qe(o),s=t.model??i,a=t.model!==void 0,d=en(o);if(!s&&(o!=="opencode"||d&&d.length>0))return{kind:"error",text:`Error: No default model configured for harness "${o}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${o}.defaultModel or pass model explicitly.`};if(s&&d&&d.length>0&&!hn(s,d))return{kind:"error",text:a?`Error: Model "${s}" is not allowed. Permitted models: ${d.join(", ")}`:`Error: Default model "${s||"undefined"}" is not in allowedModels (${d.join(", ")}). Update your plugin config to set a compatible defaultModel.`};let l=tn(e),u=bt(e,l||At(r)),p=e.sessionKey||void 0,c=Bi(p)??So(e);if(!t.resume_session_id&&!t.force_new_session){let I=Cu(n,{workdir:r,originSessionKey:p,originChannel:u,originThreadId:c});if(I.resumable.length>0||I.active.length>0){let W=I.resumable.length>0?["Linked resumable session(s) already exist for this thread/workdir:",fs(I.resumable),"","Resume the latest one with:",` agent_respond(session='${I.resumable[0].ref}', message='<next instruction>')`,"Fork from it with:",` agent_launch(prompt='<new task>', resume_session_id='${I.resumable[0].ref}', fork_session=true)`].join(`
|
|
47
|
+
`):"",S=I.active.length>0?[I.resumable.length>0?"Linked active session(s):":"Linked active session(s) already exist for this thread/workdir:",fs(I.active),"","Send a follow-up instead of launching a duplicate:",` agent_respond(session='${I.active[0].ref}', message='<next instruction>')`].join(`
|
|
48
|
+
`):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",W,S,["If you intentionally want a brand-new independent session here, call:"," agent_launch(prompt='<new task>', force_new_session=true)"].join(`
|
|
46
49
|
`)].filter(Boolean).join(`
|
|
47
50
|
|
|
48
|
-
`)}}}let
|
|
49
|
-
`)}function
|
|
50
|
-
`)}function
|
|
51
|
-
`),
|
|
52
|
-
`)}function
|
|
53
|
-
`),
|
|
54
|
-
`)}var nn,No,Nn=!1;function fc(t){try{return t?.config?.current?.()}catch{return}}function qn(t,e){if(t&&typeof t=="object"){nn=t,arguments.length>=2?(No=e,Nn=!0):Nn||(No=fc(nn),Nn=!0);return}nn=void 0,No=void 0,Nn=!1}function rs(){return nn}function gc(){return nn?.tasks?.managedFlows??nn?.taskFlow}function hc(){return Nn||(No=fc(nn),Nn=!0),No}var Iv="openclaw-code-agent",xv=160,ns={create(){},progress(){},finalize(){}};function os(t,e){let r=e instanceof Error?e.message:String(e);console.warn(`[SessionTaskLifecycle] ${t} failed: ${r}`)}function Pv(t,e){if(e.applied===!1){let r=e.code?` (${e.code})`:"";console.warn(`[SessionTaskLifecycle] ${t} mutation was not applied${r}`)}}function wv(t){let e=t.prompt.trim().replace(/\s+/g," ");return Qe(e||t.name,xv)}function vv(t){if(t.status==="starting"||t.lifecycle==="starting")return"Starting";if(t.lifecycle==="active")return"Running";if(t.lifecycle==="awaiting_plan_decision")return"Waiting for plan approval";if(t.lifecycle==="awaiting_user_input")return"Waiting for input";if(t.lifecycle==="awaiting_worktree_decision")return"Waiting for worktree decision";if(t.lifecycle==="suspended")return"Suspended after idle timeout"}function bv(t){if(t.status==="completed")return"succeeded";if(t.status==="failed")return"failed";if(t.status==="killed")return t.killReason==="idle-timeout"||t.killReason==="startup-timeout"?"timed_out":"cancelled"}function lp(t,e){return t==="completed"?"Completed":t==="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 Av(t){return t.lifecycle==="awaiting_plan_decision"||t.lifecycle==="awaiting_user_input"||t.lifecycle==="awaiting_worktree_decision"||t.lifecycle==="suspended"}function mp(t,e,r){return{phase:e,integration:"phase-1-managed-task-flow",sessionId:t.id,sessionName:t.name,sessionStatus:t.status,sessionLifecycle:t.lifecycle,summary:r}}function Tv(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.createManaged=="function"&&typeof e.resume=="function"&&typeof e.setWaiting=="function"&&typeof e.finish=="function"&&typeof e.fail=="function"}function yc(t,e){if(e.applied)return e.flow;let r=e.current;return r?.flowId&&typeof r.revision=="number"?r:t}var cp=class{constructor(e){this.taskFlow=e}taskFlow;flow;finalized=!1;lastProgressKey;create(e){if(this.flow||this.finalized)return;let r="Starting",n=Date.now();try{this.flow=this.taskFlow.createManaged({controllerId:Iv,goal:wv(e),status:"running",notifyPolicy:"silent",currentStep:r,stateJson:mp(e,"created",r),createdAt:e.startedAt,updatedAt:n}),this.lastProgressKey=this.progressKey(e,r)}catch(o){os("create",o)}}progress(e){if(!this.flow||this.finalized)return;let r=vv(e);if(!r)return;let n=this.progressKey(e,r);if(n!==this.lastProgressKey)try{let o=mp(e,"progress",r),i=Date.now(),a=Av(e)?this.taskFlow.setWaiting({flowId:this.flow.flowId,expectedRevision:this.flow.revision,currentStep:r,stateJson:o,waitJson:{reason:r,sessionId:e.id},blockedSummary:r,updatedAt:i}):this.taskFlow.resume({flowId:this.flow.flowId,expectedRevision:this.flow.revision,status:"running",currentStep:r,stateJson:o,updatedAt:i});this.flow=yc(this.flow,a),this.lastProgressKey=n}catch(o){os("progress",o)}}finalize(e){if(!this.flow||this.finalized)return;let r=bv(e);if(!r)return;let n=r==="succeeded"?"Completed":r==="failed"?"Failed":lp(e.status,e.killReason);try{let o=e.completedAt??Date.now(),i={...mp(e,"terminal",n),terminalStatus:r,terminalSummary:lp(e.status,e.killReason),...e.status==="failed"&&e.error?{error:e.error}:{}},a=r==="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:lp(e.status,e.killReason),updatedAt:o,endedAt:o});Pv("finalize",a),this.flow=yc(this.flow,a),this.finalized=!0}catch(o){os("finalize",o)}}progressKey(e,r){return`${e.status}:${e.lifecycle}:${r}`}};function is(t){if(!t.sessionKey?.trim())return ns;try{let e=gc()?.fromToolContext;if(typeof e!="function")return ns;let r=e(t);return Tv(r)?new cp(r):ns}catch(e){return os("resolve",e),ns}}function Rv(t){return t instanceof Error?t.message:String(t)}function kc(t,e){return t?("id"in t?t.id:t.sessionId)??e??"unknown-session":e??"unknown-session"}function Cv(t){return!t||typeof t!="object"?!1:typeof t.prompt=="string"}function Ev(t){return!!t&&typeof t=="object"&&typeof t.formatLaunchResult=="function"}function Sc(t){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn \u2014 they stay open for follow-up messages via agent_respond. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:f.Object({prompt:f.String({description:"The task prompt to execute"}),name:f.Optional(f.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:f.Optional(f.String({description:"Working directory (defaults to cwd)"})),model:f.Optional(f.String({description:"Model name to use"})),system_prompt:f.Optional(f.String({description:"Additional system prompt"})),allowed_tools:f.Optional(f.Array(f.String(),{description:"List of allowed tools"})),resume_session_id:f.Optional(f.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:f.Optional(f.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),force_new_session:f.Optional(f.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:f.Optional(f.Union([f.Literal("default"),f.Literal("plan"),f.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:f.Optional(f.Union([f.Literal("ask"),f.Literal("delegate"),f.Literal("approve")],{description:"Plan approval policy for this session: 'ask' (send the full plan 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 buttons), 'approve' (auto-approve after verification). Overrides the plugin-level planApproval setting."})),harness:f.Optional(f.String({description:"Agent harness to use (e.g. 'claude-code'). Defaults to 'claude-code'."})),worktree_strategy:f.Optional(f.Union([f.Literal("off"),f.Literal("manual"),f.Literal("ask"),f.Literal("delegate"),f.Literal("auto-merge"),f.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:f.Optional(f.String({description:"Base branch for worktree merge/PR operations (default: auto-detected or 'main')"})),worktree_pr_target_repo:f.Optional(f.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,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Cv(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};r.agentId&&console.warn(`[agent_launch] \u26A0\uFE0F agentId="${r.agentId}" was passed as a parameter \u2014 this is WRONG. agentId is only for sessions_spawn (OpenClaw sub-agents), not agent_launch (CC sessions). The field is being ignored. ctx.agentId="${t.agentId}" will be used for origin routing instead.`);try{let n=Xi(r,t,I);if(n.kind!=="resolved")return{content:[{type:"text",text:n.text}]};let{workdir:o,harness:i,resolvedModel:a,permissionMode:u,planApproval:p,originChannel:d,originThreadId:l,originSessionKey:m,route:c,resumeSessionId:h,resolvedResumeId:y,clearedPersistedCodexResume:k,reasoningEffort:S,fastMode:x}=n,R=r.resume_session_id?I.resolve(r.resume_session_id)??I.getPersistedSession(r.resume_session_id):void 0,$=!r.fork_session&&R?Fo(R):void 0;if($?.kind==="direct")return{content:[{type:"text",text:`Session ${R.name} [${kc(R,r.resume_session_id)}] is already running. Use agent_respond(session='${r.resume_session_id}', message='<next instruction>') instead of agent_launch(resume_session_id=...).`}]};if($?.kind==="unavailable")return{content:[{type:"text",text:`Resume unavailable for session ${R.name} [${kc(R,r.resume_session_id)}] (${$.reason}). Use agent_launch(prompt='<new task>') for a fresh session or set fork_session=true to fork from prior context.`}]};let C=I.spawn({prompt:r.prompt,sessionIdOverride:r.fork_session?void 0:$?.kind==="resume"||$?.kind==="relaunch"?$.stableSessionId:void 0,name:r.name,workdir:o,model:a,reasoningEffort:S,fastMode:x,systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,resumeSessionId:$?.kind==="resume"?$.resumeSessionId:h,resumeWorktreeFrom:y,forkSession:h?r.fork_session:!1,multiTurn:!0,permissionMode:u,planApproval:p,codexApprovalPolicy:i==="codex"?"never":void 0,originChannel:d,originThreadId:l,originAgentId:t.agentId||void 0,originSessionKey:m,route:c,harness:i,taskLifecycle:is(t),worktreeStrategy:r.worktree_strategy,worktreeBaseBranch:r.worktree_base_branch,worktreePrTargetRepo:r.worktree_pr_target_repo});return{content:[{type:"text",text:Ev(I)?I.formatLaunchResult({prompt:r.prompt,workdir:o,harness:i,permissionMode:u??K.permissionMode,planApproval:p,forceNewSession:r.force_new_session,resumeSessionId:r.resume_session_id,forkSession:r.fork_session,clearedPersistedCodexResume:k},C):Di({prompt:r.prompt,workdir:o,harness:i,permissionMode:u??K.permissionMode,planApproval:p,resumeSessionId:r.resume_session_id,forkSession:r.fork_session,forceNewSession:r.force_new_session,clearedPersistedCodexResume:k},{id:C.id,name:C.name,model:C.model,reasoningEffort:C.reasoningEffort??Ir(i),fastMode:C.fastMode??x,worktreeStrategy:C.worktreeStrategy??r.worktree_strategy??K.defaultWorktreeStrategy??"off",worktreePath:C.worktreePath,originalWorkdir:C.originalWorkdir})}]}}catch(n){let o=Rv(n),i=o.includes("Max sessions")?"":`
|
|
55
|
-
|
|
56
|
-
Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}
|
|
57
|
-
`),[
|
|
58
|
-
${e}`:e,this.deps.emitOutput(e)}noteToolCall(e){let{name:r,input:n,currentPermissionMode:o,permissionMode:i,planModeApproved:a}=e;if(r==="Write"){let u=n;typeof u?.file_path=="string"&&u.file_path.includes("/.claude/plans/")&&this.deps.setPlanFilePath(u.file_path)}r==="AskUserQuestion"?(this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),(o==="plan"||i==="plan")&&!a&&this.deps.markPendingPlanApproval("plan-mode")):(r==="ExitPlanMode"||r==="set_permission_mode")&&!a&&(this.lastTurnHadQuestion=!0,this.deps.markPendingPlanApproval("plan-mode")),this.deps.emitToolUse(r,n)}notePendingInput(){this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),this.waitingForInputFired||(this.waitingForInputFired=!0,this.deps.emitTurnEnd(!0))}clearResolvedPendingInput(e,r){if(!(!e||r?.requestId===e))return r}notePlanArtifact(e,r){if(this.currentTurnPlanArtifact=e,this.deps.setLatestPlanArtifact(e),!r)return;let n=e.markdown.trim();!n||this.currentTurnText.trim()===n||(this.deps.appendOutput(n),this.currentTurnText=n,this.deps.emitOutput(n))}noteSettingsChanged(e){let{oldMode:r,permissionMode:n,planModeApproved:o}=e;if(n)return n!=="plan"&&r==="plan"&&!o&&(this.deps.markPendingPlanApproval("plan-mode"),this.lastTurnHadQuestion=!0),n}finishSuccessfulTurn(e){let{currentPermissionMode:r,permissionMode:n,pendingPlanApproval:o,planModeApproved:i,pendingInputState:a,hasPendingMessages:u}=e,p=o;(r==="plan"||n==="plan")&&!p&&!i&&(this.deps.markPendingPlanApproval("plan-mode"),p=!0);let d=p||this.lastTurnHadQuestion||!!a;if(this.turnInProgress=u,d&&!this.waitingForInputFired)this.waitingForInputFired=!0,p||this.deps.markAwaitingUserInput(),this.deps.emitTurnEnd(!0);else if(!u&&!d){if(this.deps.queueWorktreeFinalizationPrompt?.()){this.turnInProgress=!0;return}this.deps.completeTurn(),this.deps.emitTurnEnd(!1)}}finishTerminalTurn(){this.turnInProgress=!1}finishInterruptedTurn(e){this.turnInProgress=e,this.waitingForInputFired=!1,this.lastTurnHadQuestion=!1,this.currentTurnText="",this.currentTurnPlanArtifact=void 0}resetAfterRun(){this.lastTurnHadQuestion=!1,this.currentTurnText="",this.currentTurnPlanArtifact=void 0}};var ds=class{constructor(e){this.deps=e}deps;applyMessage(e,r){if(e.type==="backend_ref"){this.deps.clearStartupTimer(),this.deps.assignBackendRef({...e.ref}),this.deps.transitionRunning();return}if(e.type==="run_started"){e.runId&&this.deps.noteRunStarted(e.runId);return}if(e.type==="text_delta"){this.deps.noteTextDelta(e.text,r.pendingPlanApproval);return}if(e.type==="tool_call"){this.deps.noteToolCall({name:e.name,input:e.input,currentPermissionMode:r.currentPermissionMode,permissionMode:r.permissionMode,planModeApproved:r.planModeApproved});return}if(e.type==="pending_input"){this.deps.setPendingInputState(e.state),this.deps.notePendingInput();return}if(e.type==="pending_input_resolved"){this.deps.setPendingInputState(this.deps.clearResolvedPendingInput(e.requestId,r.pendingInputState));return}if(e.type==="plan_artifact"){this.deps.notePlanArtifact(e);return}if(e.type==="settings_changed"){let n=this.deps.noteSettingsChanged({oldMode:r.currentPermissionMode,permissionMode:e.permissionMode,planModeApproved:r.planModeApproved});n&&this.deps.setCurrentPermissionMode(n);return}if(e.type==="run_completed"){this.deps.handleRunCompleted(e.data);return}e.type}};Pt();var tb=120*1e3;function xs(t){return t instanceof Error?t.message:String(t)}var Ps=class extends eb{id;name;harnessSessionId;backendRef;harness;harnessHandle;prompt;workdir;model;reasoningEffort;fastMode;systemPrompt;allowedTools;permissionMode;requestedPermissionMode;planApproval;codexApprovalPolicy;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;worktreePath;originalWorkdir;worktreeBranch;worktreeStrategy;worktreeBaseBranch;worktreePrTargetRepo;autoMergeParentSessionId;autoMergeConflictResolutionAttemptCount;autoMergeResolverSessionId;worktreePushRemote;worktreeDisposition;worktreePrUrl;worktreePrNumber;worktreeMerged;worktreeMergedAt;worktreeLifecycle;worktreeState="none";multiTurn;goalTaskId;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;route;pendingInputState;pendingPlanApproval=!1;planApprovalContext;planDecisionVersion=0;actionablePlanDecisionVersion;canonicalPlanPromptVersion;approvalPromptRequiredVersion;approvalPromptVersion;approvalPromptStatus="not_sent";approvalPromptTransport="none";approvalPromptMessageKind="none";approvalPromptLastAttemptAt;approvalPromptDeliveredAt;approvalPromptFailedAt;planFilePath;killReason="unknown";planModeApproved=!1;turnRuntime;harnessEvents;worktreeFinalizationPromptIssued=!1;lifecycle="starting";approvalState="not_required";approvalExecutionState="not_plan_gated";approvalRationale;latestPlanArtifact;latestPlanArtifactVersion;runtimeState="live";deliveryState="idle";canUseTool;autoRespondCount=0;timers=new us;constructor(e,r){super(),this.id=e.sessionIdOverride??ss(8),this.name=r,this.harness=e.harness?_o(e.harness):ic(),this.prompt=e.prompt,this.workdir=e.workdir,this.model=e.model??Mn(this.harness.name),this.reasoningEffort=e.reasoningEffort??Ir(this.harness.name),this.fastMode=this.harness.name==="codex"?e.fastMode??On(this.harness.name):void 0,this.systemPrompt=e.systemPrompt,this.allowedTools=e.allowedTools,this.permissionMode=e.permissionMode??K.permissionMode,this.requestedPermissionMode=e.requestedPermissionMode??this.permissionMode,this.planApproval=e.planApproval??K.planApproval,this.codexApprovalPolicy=this.harness.name==="codex"?"never":void 0,this.currentPermissionMode=this.permissionMode,this.originChannel=e.originChannel,this.originThreadId=e.originThreadId,this.originAgentId=e.originAgentId,this.originSessionKey=e.originSessionKey,this.route=e.route?{...e.route}:void 0,this.backendRef=e.backendRef?{...e.backendRef}:void 0,this.resumeSessionId=e.resumeSessionId,this.forkSession=e.forkSession,this.multiTurn=e.multiTurn??!0,this.goalTaskId=e.goalTaskId,this.worktreeStrategy=e.worktreeStrategy,this.worktreeBaseBranch=e.worktreeBaseBranch,e.worktreePrTargetRepo&&(this.worktreePrTargetRepo=e.worktreePrTargetRepo),e.autoMergeParentSessionId&&(this.autoMergeParentSessionId=e.autoMergeParentSessionId),e.autoMergeConflictResolutionAttemptCount!==void 0&&(this.autoMergeConflictResolutionAttemptCount=e.autoMergeConflictResolutionAttemptCount),e.autoMergeResolverSessionId&&(this.autoMergeResolverSessionId=e.autoMergeResolverSessionId),this.canUseTool=e.canUseTool,this.startedAt=Date.now(),this.abortController=new AbortController,this.turnRuntime=new ps({appendOutput:n=>Ac(this.outputBuffer,this.id,n),emitOutput:n=>this.emit("output",this,n),emitToolUse:(n,o)=>this.emit("toolUse",this,n,o),emitTurnEnd:n=>this.emit("turnEnd",this,n),markPendingPlanApproval:n=>this.markPendingPlanApproval(n),markAwaitingUserInput:()=>this.markAwaitingUserInput(),applyInputRequested:()=>this.applyControlEvent({type:"input.requested"}),completeTurn:()=>{this.applyControlEvent({type:"terminal.entered"}),this.complete("done")},queueWorktreeFinalizationPrompt:()=>this.queueWorktreeFinalizationPrompt(),setPlanFilePath:n=>{this.planFilePath=n},setLatestPlanArtifact:n=>{this.latestPlanArtifact=n;let o=this.pendingPlanApproval?this.actionablePlanDecisionVersion??this.planDecisionVersion:void 0;this.latestPlanArtifactVersion=o&&o>0?o:void 0}}),this.harnessEvents=new ds({clearStartupTimer:()=>this.clearTimer("startup"),assignBackendRef:n=>{this.backendRef=n,this.harnessSessionId=n.conversationId,n.worktreePath&&(this.worktreePath=n.worktreePath,this.originalWorkdir??=this.workdir,this.worktreeBranch??=hs(n.worktreePath),this.worktreeStrategy&&this.worktreeStrategy!=="off"&&this.applyControlEvent({type:"worktree.state_set",worktreeState:"provisioned"}))},noteRunStarted:n=>{this.backendRef&&(this.backendRef={...this.backendRef,runId:n})},transitionRunning:()=>{this._status==="starting"&&this.transition("running")},noteTextDelta:(n,o)=>this.turnRuntime.noteTextDelta(n,o),noteToolCall:n=>this.turnRuntime.noteToolCall(n),setPendingInputState:n=>{this.pendingInputState=n},notePendingInput:()=>this.turnRuntime.notePendingInput(),clearResolvedPendingInput:(n,o)=>this.turnRuntime.clearResolvedPendingInput(n,o),notePlanArtifact:n=>this.turnRuntime.notePlanArtifact(n.artifact,n.finalized),noteSettingsChanged:n=>this.turnRuntime.noteSettingsChanged(n),setCurrentPermissionMode:n=>{this.currentPermissionMode=n,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:n})},handleRunCompleted:n=>{let o=n.outcome??(n.success?"completed":"failed");this.result={subtype:o==="interrupted"?"interrupted":n.success?"success":"error",duration_ms:n.duration_ms,total_cost_usd:n.total_cost_usd,num_turns:n.num_turns,result:n.result,is_error:o==="failed",session_id:n.session_id},this.costUsd=n.total_cost_usd;let i=this.multiTurn&&this.messageStream&&o==="interrupted",a=this.multiTurn&&this.messageStream&&o==="completed";i?(this.resetIdleTimer(),this.turnRuntime.finishInterruptedTurn(this.messageStream?.hasPending()===!0)):a?(this.resetIdleTimer(),this.turnRuntime.finishSuccessfulTurn({currentPermissionMode:this.currentPermissionMode,permissionMode:this.permissionMode,pendingPlanApproval:this.pendingPlanApproval,planModeApproved:this.planModeApproved,pendingInputState:this.pendingInputState,hasPendingMessages:this.messageStream?.hasPending()===!0})):(this.turnRuntime.finishTerminalTurn(),this.transitionToTerminal(o==="completed"?"completed":"failed")),this.turnRuntime.resetAfterRun(),this.pendingInputState=void 0}}),this.applyControlEvent({type:"initialize",hasWorktree:!!(this.worktreeStrategy&&this.worktreeStrategy!=="off")}),(e.planModeApproved!==void 0||e.approvalState!==void 0||e.approvalExecutionState!==void 0||e.approvalRationale!==void 0||e.pendingPlanApproval!==void 0||e.planApprovalContext!==void 0||e.planDecisionVersion!==void 0||e.actionablePlanDecisionVersion!==void 0||e.canonicalPlanPromptVersion!==void 0||e.approvalPromptRequiredVersion!==void 0||e.approvalPromptVersion!==void 0||e.approvalPromptStatus!==void 0||e.approvalPromptTransport!==void 0||e.approvalPromptMessageKind!==void 0||e.approvalPromptLastAttemptAt!==void 0||e.approvalPromptDeliveredAt!==void 0||e.approvalPromptFailedAt!==void 0)&&this.applyControlPatch({...e.planModeApproved!==void 0?{planModeApproved:e.planModeApproved}:{},...e.approvalState!==void 0?{approvalState:e.approvalState}:{},...e.approvalExecutionState!==void 0?{approvalExecutionState:e.approvalExecutionState}:{},...e.pendingPlanApproval!==void 0?{pendingPlanApproval:e.pendingPlanApproval}:{},...e.planApprovalContext!==void 0?{planApprovalContext:e.planApprovalContext}:{},...e.planDecisionVersion!==void 0?{planDecisionVersion:e.planDecisionVersion}:{},...e.actionablePlanDecisionVersion!==void 0?{actionablePlanDecisionVersion:e.actionablePlanDecisionVersion}:{},...e.canonicalPlanPromptVersion!==void 0?{canonicalPlanPromptVersion:e.canonicalPlanPromptVersion}:{},...e.approvalPromptRequiredVersion!==void 0?{approvalPromptRequiredVersion:e.approvalPromptRequiredVersion}:{},...e.approvalPromptVersion!==void 0?{approvalPromptVersion:e.approvalPromptVersion}:{},...e.approvalPromptStatus!==void 0?{approvalPromptStatus:e.approvalPromptStatus}:{},...e.approvalPromptTransport!==void 0?{approvalPromptTransport:e.approvalPromptTransport}:{},...e.approvalPromptMessageKind!==void 0?{approvalPromptMessageKind:e.approvalPromptMessageKind}:{},...e.approvalPromptLastAttemptAt!==void 0?{approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt}:{},...e.approvalPromptDeliveredAt!==void 0?{approvalPromptDeliveredAt:e.approvalPromptDeliveredAt}:{},...e.approvalPromptFailedAt!==void 0?{approvalPromptFailedAt:e.approvalPromptFailedAt}:{}}),this.approvalRationale=e.approvalRationale}get status(){return this._status}get harnessName(){return this.harness.name}get backendKind(){return this.harness.backendKind}get backendCapabilities(){return this.harness.capabilities}get backendConversationId(){return q(this)}get waitingForInputFired(){return this.turnRuntime.waitingForInputFired}set waitingForInputFired(e){this.turnRuntime.waitingForInputFired=e}get lastTurnHadQuestion(){return this.turnRuntime.lastTurnHadQuestion}set lastTurnHadQuestion(e){this.turnRuntime.lastTurnHadQuestion=e}get turnInProgress(){return this.turnRuntime.turnInProgress}set turnInProgress(e){this.turnRuntime.turnInProgress=e}get currentTurnText(){return this.turnRuntime.currentTurnText}set currentTurnText(e){this.turnRuntime.currentTurnText=e}get currentTurnPlanArtifact(){return this.turnRuntime.currentTurnPlanArtifact}set currentTurnPlanArtifact(e){this.turnRuntime.currentTurnPlanArtifact=e}get duration(){return(this.completedAt??Date.now())-this.startedAt}get phase(){return this.lifecycle}get isExplicitlyResumable(){return this.status!=="running"&&this.status!=="completed"&&this.killReason!=="done"&&!!this.backendConversationId}transition(e){if(!Pc[this._status].includes(e))throw new Error(`Session state error: cannot transition from ${this._status} to ${e}. This is an internal error \u2014 please report it.`);let r=this._status;this._status=e,this.applyControlEvent({type:"status.transition",status:e}),this.emit("statusChange",this,e,r)}setTimer(e,r,n){this.timers.set(e,r,n)}clearTimer(e){this.timers.clear(e)}clearAllTimers(){this.timers.clearAll()}markPendingPlanApproval(e){let r=this.latestPlanArtifactVersion;this.approvalRationale=void 0,this.applyControlEvent({type:"plan.requested",context:e});let n=this.actionablePlanDecisionVersion??this.planDecisionVersion;this.currentTurnPlanArtifact&&n>0?(this.latestPlanArtifact=this.currentTurnPlanArtifact,this.latestPlanArtifactVersion=n):r!==n&&(this.latestPlanArtifact=void 0,this.latestPlanArtifactVersion=void 0)}clearPendingPlanApproval(){this.applyControlEvent({type:"plan.cleared"})}markAwaitingUserInput(){this.applyControlEvent({type:"input.requested"})}queueWorktreeFinalizationPrompt(){if(!this.multiTurn||!this.messageStream||!this.worktreePath||!this.worktreeStrategy||this.worktreeStrategy==="off"||this.worktreeFinalizationPromptIssued)return!1;let e=Kn(this.worktreePath);if(e.length===0)return!1;this.worktreeFinalizationPromptIssued=!0;let r=e.slice(0,20).map(i=>`- ${i}`).join(`
|
|
59
|
-
`),
|
|
60
|
-
- ...and ${e.length-20} more`:"",o=["Your worktree still has uncommitted changes, so this session cannot finish yet.","",`Worktree: ${this.worktreePath}`,`Branch: ${this.worktreeBranch??"(unknown)"}`,"","Dirty entries:",`${
|
|
61
|
-
`);return this.messageStream.push(this.harness.buildUserMessage(o,this.backendConversationId??"")),!0}async start(){try{let e;this.multiTurn?(this.messageStream=new
|
|
62
|
-
|
|
63
|
-
${e}`)}else if((this.pendingPlanApproval||this.approvalState==="changes_requested")&&!this.planModeApproved&&(this.approvalState!=="changes_requested"&&this.applyControlEvent({type:"plan.changes_requested"}),
|
|
64
|
-
|
|
65
|
-
${e}`,this.harnessHandle?.setPermissionMode))try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan",this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:"plan"})}catch(
|
|
66
|
-
`);return e.at(-1)===""&&e.pop(),e}function
|
|
67
|
-
`)}function
|
|
68
|
-
`)}function
|
|
69
|
-
Backend session: ${
|
|
70
|
-
(no persisted output available: ${e})${o}`}function
|
|
51
|
+
`)}}}let f=t.resume_session_id,g=f?n.resolve?.(f):void 0,h=f?n.getPersistedSession?.(f):void 0;if(f){let I=n.resolveBackendConversationId?.(f)??n.resolveHarnessSessionId?.(f);if(!I)return{kind:"error",text:`Error: Could not resolve resume_session_id "${f}" to a session ID. Use agent_sessions to list available sessions.`};f=I}let{resumeSessionId:y,clearedPersistedCodexResume:k}=Ze({requestedResumeSessionId:f,activeSession:g?{harnessSessionId:g.backendConversationId??g.harnessSessionId}:void 0,persistedSession:h?{harness:h.harness,backendRef:h.backendRef}:void 0}),b=t.permission_mode??E.permissionMode,A=t.plan_approval??E.planApproval;return{kind:"resolved",workdir:r,harness:o,resolvedModel:s,permissionMode:b,planApproval:A,originChannel:u,originThreadId:c,originSessionKey:p,route:Ye(e,u,p),resumeSessionId:y,resolvedResumeId:f,clearedPersistedCodexResume:k,reasoningEffort:xe(o),fastMode:Je(o)}}Q();function $t(t){let e=t.harness?.trim(),n=t.model?.trim();return e&&n?`${e} | ${n}`:e?`${e} | default`:n}function yn(t){let e=$t(t);return e?` | ${e}`:""}function ve(t){let e=Math.floor(t/1e3),n=Math.floor(e/60),r=e%60;return n>0?`${n}m${r}s`:`${r}s`}var Mu=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 Ss(t){let n=t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!Mu.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var hs={starting:"đĄ",running:"đĸ",completed:"â
",failed:"â",killed:"â",awaiting_plan_decision:"đ",awaiting_user_input:"â",awaiting_worktree_decision:"đŋ",suspended:"â¸ī¸",terminal:"đ"};function _u(t){let e=t.worktreeLifecycle?.state??t.worktreeState;return t.worktreeMerged||e==="merged"?"[merged â]":e==="released"?"[released]":t.worktreePrUrl?`[PR: ${t.worktreePrUrl}]`:e==="pr_open"?"[PR open]":e==="dismissed"?"[dismissed]":e==="no_change"?"[no change]":"[not merged]"}function ys(t){let e=hs[t.phase]??hs[t.status]??"â",n=ve(t.duration),r=t.multiTurn?"multi-turn":"single",o=t.prompt.length>80?t.prompt.slice(0,80)+"...":t.prompt,i=t.costUsd>0?` | $${t.costUsd.toFixed(2)}`:"",s=[`${e} ${t.name} [${t.id}] (${n}${i}) â ${r}`,` đ ${t.workdir}`,` đ "${o}"`];t.worktreePath&&t.worktreeBranch&&s.push(` đŋ Worktree: ${t.worktreeBranch} ${_u(t)}`),t.phase!==t.status&&s.push(` âī¸ Phase: ${t.phase}`),t.lifecycle&&t.lifecycle!==t.phase&&s.push(` đ Lifecycle: ${t.lifecycle}`),(t.requestedPermissionMode||t.currentPermissionMode||t.approvalExecutionState)&&s.push(` đ Approval: ${t.approvalExecutionState??"unknown"} (requested=${t.requestedPermissionMode??"unknown"}, effective=${t.currentPermissionMode??"unknown"})`),t.resumable&&s.push(" âŠī¸ Resumable: yes"),t.harness?s.push(` đ§° Harness | model: ${$t({harness:t.harness,model:t.model})}`):t.model&&s.push(` đ§° Harness | model: ${t.model}`);let a=T(t);return a&&s.push(` đ Backend ID: ${a}`),t.resumeSessionId&&s.push(` âŠī¸ Resumed from: ${t.resumeSessionId}${t.forkSession?" (forked)":""}`),s.join(`
|
|
52
|
+
`)}function kn(t,e){let n=t.sessionsWithDuration>0?t.totalDurationMs/t.sessionsWithDuration:0,{completed:r,failed:o,killed:i}=t.sessionsByStatus,s=["đ OpenClaw Code Agent Stats","","đ Sessions",` Launched: ${t.totalLaunched}`,` Running: ${e}`,` Completed: ${r}`,` Failed: ${o}`,` Killed: ${i}`,"",`âąī¸ Average duration: ${n>0?ve(n):"n/a"}`];if(t.mostExpensive){let a=t.mostExpensive;s.push("","đ Notable session",` ${a.name} [${a.id}]`,` đ "${a.prompt}"`)}return s.join(`
|
|
53
|
+
`)}function ne(t,e){return e<=0?"":t.length<=e?t:e<=3?".".repeat(e):t.slice(0,e-3)+"..."}function vn(t,e){let n=t.split(`
|
|
54
|
+
`),r=[],o=0;for(let i=n.length-1;i>=0;i--){let s=n[i].length+(r.length>0?1:0);if(o+s>e&&r.length>0)break;r.unshift(n[i]),o+=s}return r.join(`
|
|
55
|
+
`)}function ks(t,e){let n=t.split(`
|
|
56
|
+
`),r=[],o=0;for(let i=0;i<n.length;i++){let s=n[i].length+(r.length>0?1:0);if(o+s>e&&r.length>0)break;r.push(n[i]),o+=s}return r.join(`
|
|
57
|
+
`)}var Be,Dt,rt=!1;function vs(t){try{return t?.config?.current?.()}catch{return}}function ot(t,e){if(t&&typeof t=="object"){Be=t,arguments.length>=2?(Dt=e,rt=!0):rt||(Dt=vs(Be),rt=!0);return}Be=void 0,Dt=void 0,rt=!1}function wn(){return Be}function ws(){return Be?.tasks?.managedFlows??Be?.taskFlow}function Ps(){return rt||(Dt=vs(Be),rt=!0),Dt}var Eu="openclaw-code-agent",$u=160,Pn={create(){},progress(){},finalize(){}};function bn(t,e){let n=e instanceof Error?e.message:String(e);`${t}${n}`}function Du(t,e){if(e.applied===!1){let n=e.code?` (${e.code})`:"";`${t}${n}`}}function Ou(t){let e=t.prompt.trim().replace(/\s+/g," ");return ne(e||t.name,$u)}function Nu(t){if(t.status==="starting"||t.lifecycle==="starting")return"Starting";if(t.lifecycle==="active")return"Running";if(t.lifecycle==="awaiting_plan_decision")return"Waiting for plan approval";if(t.lifecycle==="awaiting_user_input")return"Waiting for input";if(t.lifecycle==="awaiting_worktree_decision")return"Waiting for worktree decision";if(t.lifecycle==="suspended")return"Suspended after idle timeout"}function Wu(t){if(t.status==="completed")return"succeeded";if(t.status==="failed")return"failed";if(t.status==="killed")return t.killReason==="idle-timeout"||t.killReason==="startup-timeout"?"timed_out":"cancelled"}function _o(t,e){return t==="completed"?"Completed":t==="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 Lu(t){return t.lifecycle==="awaiting_plan_decision"||t.lifecycle==="awaiting_user_input"||t.lifecycle==="awaiting_worktree_decision"||t.lifecycle==="suspended"}function Eo(t,e,n){return{phase:e,integration:"phase-1-managed-task-flow",sessionId:t.id,sessionName:t.name,sessionStatus:t.status,sessionLifecycle:t.lifecycle,summary:n}}function Bu(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.createManaged=="function"&&typeof e.resume=="function"&&typeof e.setWaiting=="function"&&typeof e.finish=="function"&&typeof e.fail=="function"}function bs(t,e){if(e.applied)return e.flow;let n=e.current;return n?.flowId&&typeof n.revision=="number"?n:t}var $o=class{constructor(e){this.taskFlow=e}taskFlow;flow;finalized=!1;lastProgressKey;create(e){if(this.flow||this.finalized)return;let n="Starting",r=Date.now();try{this.flow=this.taskFlow.createManaged({controllerId:Eu,goal:Ou(e),status:"running",notifyPolicy:"silent",currentStep:n,stateJson:Eo(e,"created",n),createdAt:e.startedAt,updatedAt:r}),this.lastProgressKey=this.progressKey(e,n)}catch(o){bn("create",o)}}progress(e){if(!this.flow||this.finalized)return;let n=Nu(e);if(!n)return;let r=this.progressKey(e,n);if(r!==this.lastProgressKey)try{let o=Eo(e,"progress",n),i=Date.now(),s=Lu(e)?this.taskFlow.setWaiting({flowId:this.flow.flowId,expectedRevision:this.flow.revision,currentStep:n,stateJson:o,waitJson:{reason:n,sessionId:e.id},blockedSummary:n,updatedAt:i}):this.taskFlow.resume({flowId:this.flow.flowId,expectedRevision:this.flow.revision,status:"running",currentStep:n,stateJson:o,updatedAt:i});this.flow=bs(this.flow,s),this.lastProgressKey=r}catch(o){bn("progress",o)}}finalize(e){if(!this.flow||this.finalized)return;let n=Wu(e);if(!n)return;let r=n==="succeeded"?"Completed":n==="failed"?"Failed":_o(e.status,e.killReason);try{let o=e.completedAt??Date.now(),i={...Eo(e,"terminal",r),terminalStatus:n,terminalSummary:_o(e.status,e.killReason),...e.status==="failed"&&e.error?{error:e.error}:{}},s=n==="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:_o(e.status,e.killReason),updatedAt:o,endedAt:o});Du("finalize",s),this.flow=bs(this.flow,s),this.finalized=!0}catch(o){bn("finalize",o)}}progressKey(e,n){return`${e.status}:${e.lifecycle}:${n}`}};function An(t){if(!t.sessionKey?.trim())return Pn;try{let e=ws()?.fromToolContext;if(typeof e!="function")return Pn;let n=e(t);return Bu(n)?new $o(n):Pn}catch(e){return bn("resolve",e),Pn}}function Fu(t){return t instanceof Error?t.message:String(t)}function As(t,e){return t?("id"in t?t.id:t.sessionId)??e??"unknown-session":e??"unknown-session"}function qu(t){return!t||typeof t!="object"?!1:typeof t.prompt=="string"}function Ku(t){return!!t&&typeof t=="object"&&typeof t.formatLaunchResult=="function"}function Rs(t){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:m.Object({prompt:m.String({description:"The task prompt to execute"}),name:m.Optional(m.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:m.Optional(m.String({description:"Working directory (defaults to cwd)"})),model:m.Optional(m.String({description:"Model name to use"})),system_prompt:m.Optional(m.String({description:"Additional system prompt"})),allowed_tools:m.Optional(m.Array(m.String(),{description:"List of allowed tools"})),resume_session_id:m.Optional(m.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:m.Optional(m.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),force_new_session:m.Optional(m.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:m.Optional(m.Union([m.Literal("default"),m.Literal("plan"),m.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:m.Optional(m.Union([m.Literal("ask"),m.Literal("delegate"),m.Literal("approve")],{description:"Plan approval policy for this session: 'ask' (send the full plan 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 buttons), 'approve' (auto-approve after verification). Overrides the plugin-level planApproval setting."})),harness:m.Optional(m.String({description:"Agent harness to use ('claude-code', 'codex', or experimental 'opencode'). Defaults to the plugin defaultHarness."})),worktree_strategy:m.Optional(m.Union([m.Literal("off"),m.Literal("manual"),m.Literal("ask"),m.Literal("delegate"),m.Literal("auto-merge"),m.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:m.Optional(m.String({description:"Base branch for worktree merge/PR operations (default: auto-detected or 'main')"})),worktree_pr_target_repo:m.Optional(m.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,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!qu(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};n.agentId&&`${n.agentId}${t.agentId}`;try{let r=Sn(n,t,v);if(r.kind!=="resolved")return{content:[{type:"text",text:r.text}]};let{workdir:o,harness:i,resolvedModel:s,permissionMode:a,planApproval:d,originChannel:l,originThreadId:u,originSessionKey:p,route:c,resumeSessionId:f,resolvedResumeId:g,clearedPersistedCodexResume:h,reasoningEffort:y,fastMode:k}=r,b=n.resume_session_id?v.resolve(n.resume_session_id)??v.getPersistedSession(n.resume_session_id):void 0,A=!n.fork_session&&b?Et(b):void 0;if(A?.kind==="direct")return{content:[{type:"text",text:`Session ${b.name} [${As(b,n.resume_session_id)}] is already running. Use agent_respond(session='${n.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} [${As(b,n.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=v.spawn({prompt:n.prompt,sessionIdOverride:n.fork_session?void 0:A?.kind==="resume"||A?.kind==="relaunch"?A.stableSessionId:void 0,name:n.name,workdir:o,model:s,reasoningEffort:y,fastMode:k,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:A?.kind==="resume"?A.resumeSessionId:f,resumeWorktreeFrom:g,forkSession:f?n.fork_session:!1,multiTurn:!0,permissionMode:a,planApproval:d,codexApprovalPolicy:i==="codex"?"never":void 0,originChannel:l,originThreadId:u,originAgentId:t.agentId||void 0,originSessionKey:p,route:c,harness:i,taskLifecycle:An(t),worktreeStrategy:n.worktree_strategy,worktreeBaseBranch:n.worktree_base_branch,worktreePrTargetRepo:n.worktree_pr_target_repo});return{content:[{type:"text",text:Ku(v)?v.formatLaunchResult({prompt:n.prompt,workdir:o,harness:i,permissionMode:a??E.permissionMode,planApproval:d,forceNewSession:n.force_new_session,resumeSessionId:n.resume_session_id,forkSession:n.fork_session,clearedPersistedCodexResume:h},I):Xt({prompt:n.prompt,workdir:o,harness:i,permissionMode:a??E.permissionMode,planApproval:d,resumeSessionId:n.resume_session_id,forkSession:n.fork_session,forceNewSession:n.force_new_session,clearedPersistedCodexResume:h},{id:I.id,name:I.name,model:I.model,reasoningEffort:I.reasoningEffort??xe(i),fastMode:I.fastMode??k,worktreeStrategy:I.worktreeStrategy??n.worktree_strategy??E.defaultWorktreeStrategy??"off",worktreePath:I.worktreePath,originalWorkdir:I.originalWorkdir})}]}}catch(r){let o=Fu(r),i=o.includes("Max sessions")?"":`
|
|
58
|
+
|
|
59
|
+
Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}X();O();te();import{existsSync as qo,readFileSync as Qs}from"fs";import{EventEmitter as cp}from"events";import{webcrypto as xs}from"node:crypto";var Is="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Uu=128,Fe,it;function Vu(t){if(t<0||t>1024)throw new RangeError("Wrong ID size");!Fe||Fe.length<t?(Fe=Buffer.allocUnsafe(t*Uu),xs.getRandomValues(Fe),it=0):it+t>Fe.length&&(xs.getRandomValues(Fe),it=0),it+=t}function Rn(t=21){Vu(t|=0);let e="";for(let n=it-t;n<it;n++)e+=Is[Fe[n]&63];return e}To();te();Q();var Ts={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]};function V(t,e){return Object.hasOwn(t,e)}var Cs=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]);function Gu(t){return t.requestedPermissionMode!=="plan"?"not_plan_gated":t.pendingPlanApproval?"awaiting_approval":t.planModeApproved?"approved_then_implemented":t.currentPermissionMode!=="plan"?"implemented_without_required_approval":"awaiting_plan_output"}function oe(t){return{...t,approvalExecutionState:Gu(t)}}function Do(t,e){switch(e.type){case"initialize":return oe({...t,worktreeState:e.hasWorktree&&t.worktreeState==="none"?"provisioned":t.worktreeState,lifecycle:t.status==="starting"?"starting":t.lifecycle,runtimeState:t.status==="starting"?"live":t.runtimeState});case"status.transition":return e.status==="starting"?oe({...t,status:e.status,lifecycle:"starting",runtimeState:"live"}):e.status==="running"?oe({...t,status:e.status,lifecycle:t.lifecycle==="starting"||t.lifecycle==="suspended"?"active":t.lifecycle,runtimeState:"live"}):oe({...t,status:e.status,runtimeState:"stopped",lifecycle:t.lifecycle==="suspended"?"suspended":"terminal"});case"permission.mode_changed":return oe({...t,currentPermissionMode:e.currentPermissionMode});case"turn.started":return oe({...t,lifecycle:"active",runtimeState:"live"});case"input.requested":return oe({...t,lifecycle:t.pendingPlanApproval?"awaiting_plan_decision":"awaiting_user_input"});case"plan.requested":if(t.planModeApproved)return t;{let n=t.pendingPlanApproval&&t.approvalState==="pending"&&t.planApprovalContext===e.context,r=t.pendingPlanApproval&&t.approvalState==="changes_requested"&&t.planApprovalContext===e.context&&t.planDecisionVersion>0,o=!t.pendingPlanApproval&&t.approvalState==="changes_requested"&&t.planApprovalContext===e.context&&t.planDecisionVersion>0,i=n||r||o?t.planDecisionVersion:t.planDecisionVersion+1;return oe({...t,pendingPlanApproval:!0,planApprovalContext:e.context,approvalState:"pending",planDecisionVersion:i,actionablePlanDecisionVersion:i,canonicalPlanPromptVersion:n?t.canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:n?t.approvalPromptRequiredVersion:void 0,approvalPromptVersion:n?t.approvalPromptVersion:void 0,approvalPromptStatus:n?t.approvalPromptStatus:"not_sent",approvalPromptTransport:n?t.approvalPromptTransport:"none",approvalPromptMessageKind:n?t.approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:n?t.approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:n?t.approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:n?t.approvalPromptFailedAt:void 0,lifecycle:"awaiting_plan_decision"})}case"plan.cleared":return oe({...t,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,approvalState:t.approvalState==="pending"?"not_required":t.approvalState});case"plan.approved":return oe({...t,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,planModeApproved:!0,approvalState:"approved",planDecisionVersion:t.planDecisionVersion+1,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",lifecycle:t.status==="running"?"active":t.lifecycle});case"plan.changes_requested":return oe({...t,pendingPlanApproval:!0,approvalState:"changes_requested",planDecisionVersion:t.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 oe({...t,lifecycle:e.suspended?"suspended":"terminal",runtimeState:"stopped"});case"worktree.decision_requested":return oe({...t,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"});case"worktree.state_set":return oe({...t,worktreeState:e.worktreeState,lifecycle:e.worktreeState==="pending_decision"?"awaiting_worktree_decision":Cs.has(e.worktreeState)?"terminal":t.lifecycle});case"delivery.state_set":return oe({...t,deliveryState:e.deliveryState})}}function Ms(t,e){let n={...t,...V(e,"lifecycle")?{lifecycle:e.lifecycle}:{},...V(e,"approvalState")?{approvalState:e.approvalState}:{},...V(e,"approvalExecutionState")?{approvalExecutionState:e.approvalExecutionState}:{},...V(e,"worktreeState")?{worktreeState:e.worktreeState}:{},...V(e,"runtimeState")?{runtimeState:e.runtimeState}:{},...V(e,"deliveryState")?{deliveryState:e.deliveryState}:{},...V(e,"requestedPermissionMode")?{requestedPermissionMode:e.requestedPermissionMode}:{},...V(e,"currentPermissionMode")?{currentPermissionMode:e.currentPermissionMode}:{},...V(e,"pendingPlanApproval")?{pendingPlanApproval:e.pendingPlanApproval}:{},...V(e,"planApprovalContext")?{planApprovalContext:e.planApprovalContext}:{},...V(e,"planDecisionVersion")?{planDecisionVersion:e.planDecisionVersion}:{},...V(e,"actionablePlanDecisionVersion")?{actionablePlanDecisionVersion:e.actionablePlanDecisionVersion}:{},...V(e,"canonicalPlanPromptVersion")?{canonicalPlanPromptVersion:e.canonicalPlanPromptVersion}:{},...V(e,"approvalPromptRequiredVersion")?{approvalPromptRequiredVersion:e.approvalPromptRequiredVersion}:{},...V(e,"approvalPromptVersion")?{approvalPromptVersion:e.approvalPromptVersion}:{},...V(e,"approvalPromptStatus")?{approvalPromptStatus:e.approvalPromptStatus}:{},...V(e,"approvalPromptTransport")?{approvalPromptTransport:e.approvalPromptTransport}:{},...V(e,"approvalPromptMessageKind")?{approvalPromptMessageKind:e.approvalPromptMessageKind}:{},...V(e,"approvalPromptLastAttemptAt")?{approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt}:{},...V(e,"approvalPromptDeliveredAt")?{approvalPromptDeliveredAt:e.approvalPromptDeliveredAt}:{},...V(e,"approvalPromptFailedAt")?{approvalPromptFailedAt:e.approvalPromptFailedAt}:{},...V(e,"planModeApproved")?{planModeApproved:e.planModeApproved}:{}};return e.approvalState==="changes_requested"&&e.pendingPlanApproval===void 0&&(n={...n,pendingPlanApproval:!1}),n.pendingPlanApproval?n={...n,approvalState:"pending",actionablePlanDecisionVersion:n.actionablePlanDecisionVersion??n.planDecisionVersion,lifecycle:"awaiting_plan_decision"}:n.approvalState==="changes_requested"&&(n={...n,actionablePlanDecisionVersion:void 0,lifecycle:"awaiting_user_input"}),V(e,"pendingWorktreeDecisionSince")&&e.pendingWorktreeDecisionSince!==void 0||n.worktreeState==="pending_decision"?n=Do(n,{type:"worktree.decision_requested"}):Cs.has(n.worktreeState)&&(n={...n,lifecycle:"terminal"}),oe(n)}var In=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{appendFileSync as Hu}from"fs";import{tmpdir as ju}from"os";import{join as zu}from"path";var _s=2e3;function st(t){return zu(ju(),`openclaw-agent-${t}.txt`)}function Qu(t,e){if(!e)return;let n=e.split(`
|
|
60
|
+
`),[r="",...o]=n;t.length===0?t.push(r):t[t.length-1]+=r;for(let i of o)t.push(i)}function Es(t,e,n){Qu(t,n),t.length>_s&&t.splice(0,t.length-_s);try{Hu(st(e),n,"utf-8")}catch{}return t}var xn=class{timers=new Map;get size(){return this.timers.size}set(e,n,r){this.clear(e);let o=setTimeout(r,n);o.unref?.(),this.timers.set(e,o)}clear(e){let n=this.timers.get(e);n&&(clearTimeout(n),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var Tn=class{constructor(e){this.deps=e}deps;waitingForInputFired=!1;lastTurnHadQuestion=!1;turnInProgress=!0;currentTurnText="";currentTurnPlanArtifact;beginUserTurn(){this.waitingForInputFired=!1,this.turnInProgress=!0,this.currentTurnText="",this.currentTurnPlanArtifact=void 0,this.lastTurnHadQuestion=!1}noteTextDelta(e,n){this.waitingForInputFired=!1,n||(this.lastTurnHadQuestion=!1),this.deps.appendOutput(e),this.currentTurnText+=this.currentTurnText?`
|
|
61
|
+
${e}`:e,this.deps.emitOutput(e)}noteToolCall(e){let{name:n,input:r,currentPermissionMode:o,permissionMode:i,planModeApproved:s}=e;if(n==="Write"){let a=r;typeof a?.file_path=="string"&&a.file_path.includes("/.claude/plans/")&&this.deps.setPlanFilePath(a.file_path)}n==="AskUserQuestion"?(this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),(o==="plan"||i==="plan")&&!s&&this.deps.markPendingPlanApproval("plan-mode")):(n==="ExitPlanMode"||n==="set_permission_mode")&&!s&&(this.lastTurnHadQuestion=!0,this.deps.markPendingPlanApproval("plan-mode")),this.deps.emitToolUse(n,r)}notePendingInput(){this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),this.waitingForInputFired||(this.waitingForInputFired=!0,this.deps.emitTurnEnd(!0))}clearResolvedPendingInput(e,n){if(!(!e||n?.requestId===e))return n}notePlanArtifact(e,n){if(this.currentTurnPlanArtifact=e,this.deps.setLatestPlanArtifact(e),!n)return;let r=e.markdown.trim();!r||this.currentTurnText.trim()===r||(this.deps.appendOutput(r),this.currentTurnText=r,this.deps.emitOutput(r))}noteSettingsChanged(e){let{oldMode:n,permissionMode:r,planModeApproved:o}=e;if(r)return r!=="plan"&&n==="plan"&&!o&&(this.deps.markPendingPlanApproval("plan-mode"),this.lastTurnHadQuestion=!0),r}finishSuccessfulTurn(e){let{currentPermissionMode:n,permissionMode:r,pendingPlanApproval:o,planModeApproved:i,pendingInputState:s,hasPendingMessages:a}=e,d=o;(n==="plan"||r==="plan")&&!d&&!i&&(this.deps.markPendingPlanApproval("plan-mode"),d=!0);let l=d||this.lastTurnHadQuestion||!!s;if(this.turnInProgress=a,l&&!this.waitingForInputFired)this.waitingForInputFired=!0,d||this.deps.markAwaitingUserInput(),this.deps.emitTurnEnd(!0);else if(!a&&!l){if(this.deps.queueWorktreeFinalizationPrompt?.()){this.turnInProgress=!0;return}this.deps.completeTurn(),this.deps.emitTurnEnd(!1)}}finishTerminalTurn(){this.turnInProgress=!1}finishInterruptedTurn(e){this.turnInProgress=e,this.waitingForInputFired=!1,this.lastTurnHadQuestion=!1,this.currentTurnText="",this.currentTurnPlanArtifact=void 0}resetAfterRun(){this.lastTurnHadQuestion=!1,this.currentTurnText="",this.currentTurnPlanArtifact=void 0}};var Cn=class{constructor(e){this.deps=e}deps;applyMessage(e,n){if(e.type==="backend_ref"){this.deps.clearStartupTimer(),this.deps.assignBackendRef({...e.ref}),this.deps.transitionRunning();return}if(e.type==="run_started"){e.runId&&this.deps.noteRunStarted(e.runId);return}if(e.type==="text_delta"){this.deps.noteTextDelta(e.text,n.pendingPlanApproval);return}if(e.type==="tool_call"){this.deps.noteToolCall({name:e.name,input:e.input,currentPermissionMode:n.currentPermissionMode,permissionMode:n.permissionMode,planModeApproved:n.planModeApproved});return}if(e.type==="pending_input"){this.deps.setPendingInputState(e.state),this.deps.notePendingInput();return}if(e.type==="pending_input_resolved"){this.deps.setPendingInputState(this.deps.clearResolvedPendingInput(e.requestId,n.pendingInputState));return}if(e.type==="plan_artifact"){this.deps.notePlanArtifact(e);return}if(e.type==="settings_changed"){let r=this.deps.noteSettingsChanged({oldMode:n.currentPermissionMode,permissionMode:e.permissionMode,planModeApproved:n.planModeApproved});r&&this.deps.setCurrentPermissionMode(r);return}if(e.type==="run_completed"){this.deps.handleRunCompleted(e.data);return}e.type}};fe();var mp=120*1e3;function Fn(t){return t instanceof Error?t.message:String(t)}var qn=class extends cp{id;name;harnessSessionId;backendRef;harness;harnessHandle;prompt;workdir;model;reasoningEffort;fastMode;systemPrompt;allowedTools;permissionMode;requestedPermissionMode;planApproval;codexApprovalPolicy;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;worktreePath;originalWorkdir;worktreeBranch;worktreeStrategy;worktreeBaseBranch;worktreePrTargetRepo;autoMergeParentSessionId;autoMergeConflictResolutionAttemptCount;autoMergeResolverSessionId;worktreePushRemote;worktreeDisposition;worktreePrUrl;worktreePrNumber;worktreeMerged;worktreeMergedAt;worktreeLifecycle;worktreeState="none";multiTurn;goalTaskId;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;route;pendingInputState;pendingPlanApproval=!1;planApprovalContext;planDecisionVersion=0;actionablePlanDecisionVersion;canonicalPlanPromptVersion;approvalPromptRequiredVersion;approvalPromptVersion;approvalPromptStatus="not_sent";approvalPromptTransport="none";approvalPromptMessageKind="none";approvalPromptLastAttemptAt;approvalPromptDeliveredAt;approvalPromptFailedAt;planFilePath;killReason="unknown";planModeApproved=!1;turnRuntime;harnessEvents;worktreeFinalizationPromptIssued=!1;lifecycle="starting";approvalState="not_required";approvalExecutionState="not_plan_gated";approvalRationale;latestPlanArtifact;latestPlanArtifactVersion;runtimeState="live";deliveryState="idle";canUseTool;autoRespondCount=0;timers=new xn;constructor(e,n){super(),this.id=e.sessionIdOverride??Rn(8),this.name=n,this.harness=e.harness?Ct(e.harness):ps(),this.prompt=e.prompt,this.workdir=e.workdir,this.model=e.model??Qe(this.harness.name),this.reasoningEffort=e.reasoningEffort??xe(this.harness.name),this.fastMode=this.harness.name==="codex"?e.fastMode??Je(this.harness.name):void 0,this.systemPrompt=e.systemPrompt,this.allowedTools=e.allowedTools,this.permissionMode=e.permissionMode??E.permissionMode,this.requestedPermissionMode=e.requestedPermissionMode??this.permissionMode,this.planApproval=e.planApproval??E.planApproval,this.codexApprovalPolicy=this.harness.name==="codex"?"never":void 0,this.currentPermissionMode=this.permissionMode,this.originChannel=e.originChannel,this.originThreadId=e.originThreadId,this.originAgentId=e.originAgentId,this.originSessionKey=e.originSessionKey,this.route=e.route?{...e.route}:void 0,this.backendRef=e.backendRef?{...e.backendRef}:void 0,this.resumeSessionId=e.resumeSessionId,this.forkSession=e.forkSession,this.multiTurn=e.multiTurn??!0,this.goalTaskId=e.goalTaskId,this.worktreeStrategy=e.worktreeStrategy,this.worktreeBaseBranch=e.worktreeBaseBranch,e.worktreePrTargetRepo&&(this.worktreePrTargetRepo=e.worktreePrTargetRepo),e.autoMergeParentSessionId&&(this.autoMergeParentSessionId=e.autoMergeParentSessionId),e.autoMergeConflictResolutionAttemptCount!==void 0&&(this.autoMergeConflictResolutionAttemptCount=e.autoMergeConflictResolutionAttemptCount),e.autoMergeResolverSessionId&&(this.autoMergeResolverSessionId=e.autoMergeResolverSessionId),this.canUseTool=e.canUseTool,this.startedAt=Date.now(),this.abortController=new AbortController,this.turnRuntime=new Tn({appendOutput:r=>Es(this.outputBuffer,this.id,r),emitOutput:r=>this.emit("output",this,r),emitToolUse:(r,o)=>this.emit("toolUse",this,r,o),emitTurnEnd:r=>this.emit("turnEnd",this,r),markPendingPlanApproval:r=>this.markPendingPlanApproval(r),markAwaitingUserInput:()=>this.markAwaitingUserInput(),applyInputRequested:()=>this.applyControlEvent({type:"input.requested"}),completeTurn:()=>{this.applyControlEvent({type:"terminal.entered"}),this.complete("done")},queueWorktreeFinalizationPrompt:()=>this.queueWorktreeFinalizationPrompt(),setPlanFilePath:r=>{this.planFilePath=r},setLatestPlanArtifact:r=>{this.latestPlanArtifact=r;let o=this.pendingPlanApproval?this.actionablePlanDecisionVersion??this.planDecisionVersion:void 0;this.latestPlanArtifactVersion=o&&o>0?o:void 0}}),this.harnessEvents=new Cn({clearStartupTimer:()=>this.clearTimer("startup"),assignBackendRef:r=>{this.backendRef=r,this.harnessSessionId=r.conversationId,r.worktreePath&&(this.worktreePath=r.worktreePath,this.originalWorkdir??=this.workdir,this.worktreeBranch??=On(r.worktreePath),this.worktreeStrategy&&this.worktreeStrategy!=="off"&&this.applyControlEvent({type:"worktree.state_set",worktreeState:"provisioned"}))},noteRunStarted:r=>{this.backendRef&&(this.backendRef={...this.backendRef,runId:r})},transitionRunning:()=>{this._status==="starting"&&this.transition("running")},noteTextDelta:(r,o)=>this.turnRuntime.noteTextDelta(r,o),noteToolCall:r=>this.turnRuntime.noteToolCall(r),setPendingInputState:r=>{this.pendingInputState=r},notePendingInput:()=>this.turnRuntime.notePendingInput(),clearResolvedPendingInput:(r,o)=>this.turnRuntime.clearResolvedPendingInput(r,o),notePlanArtifact:r=>this.turnRuntime.notePlanArtifact(r.artifact,r.finalized),noteSettingsChanged:r=>this.turnRuntime.noteSettingsChanged(r),setCurrentPermissionMode:r=>{this.currentPermissionMode=r,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:r})},handleRunCompleted:r=>{let o=r.outcome??(r.success?"completed":"failed");this.result={subtype:o==="interrupted"?"interrupted":r.success?"success":"error",duration_ms:r.duration_ms,total_cost_usd:r.total_cost_usd,num_turns:r.num_turns,result:r.result,is_error:o==="failed",session_id:r.session_id},this.costUsd=r.total_cost_usd;let i=this.multiTurn&&this.messageStream&&o==="interrupted",s=this.multiTurn&&this.messageStream&&o==="completed";i?(this.resetIdleTimer(),this.turnRuntime.finishInterruptedTurn(this.messageStream?.hasPending()===!0)):s?(this.resetIdleTimer(),this.turnRuntime.finishSuccessfulTurn({currentPermissionMode:this.currentPermissionMode,permissionMode:this.permissionMode,pendingPlanApproval:this.pendingPlanApproval,planModeApproved:this.planModeApproved,pendingInputState:this.pendingInputState,hasPendingMessages:this.messageStream?.hasPending()===!0})):(this.turnRuntime.finishTerminalTurn(),this.transitionToTerminal(o==="completed"?"completed":"failed")),this.turnRuntime.resetAfterRun(),this.pendingInputState=void 0}}),this.applyControlEvent({type:"initialize",hasWorktree:!!(this.worktreeStrategy&&this.worktreeStrategy!=="off")}),(e.planModeApproved!==void 0||e.approvalState!==void 0||e.approvalExecutionState!==void 0||e.approvalRationale!==void 0||e.pendingPlanApproval!==void 0||e.planApprovalContext!==void 0||e.planDecisionVersion!==void 0||e.actionablePlanDecisionVersion!==void 0||e.canonicalPlanPromptVersion!==void 0||e.approvalPromptRequiredVersion!==void 0||e.approvalPromptVersion!==void 0||e.approvalPromptStatus!==void 0||e.approvalPromptTransport!==void 0||e.approvalPromptMessageKind!==void 0||e.approvalPromptLastAttemptAt!==void 0||e.approvalPromptDeliveredAt!==void 0||e.approvalPromptFailedAt!==void 0)&&this.applyControlPatch({...e.planModeApproved!==void 0?{planModeApproved:e.planModeApproved}:{},...e.approvalState!==void 0?{approvalState:e.approvalState}:{},...e.approvalExecutionState!==void 0?{approvalExecutionState:e.approvalExecutionState}:{},...e.pendingPlanApproval!==void 0?{pendingPlanApproval:e.pendingPlanApproval}:{},...e.planApprovalContext!==void 0?{planApprovalContext:e.planApprovalContext}:{},...e.planDecisionVersion!==void 0?{planDecisionVersion:e.planDecisionVersion}:{},...e.actionablePlanDecisionVersion!==void 0?{actionablePlanDecisionVersion:e.actionablePlanDecisionVersion}:{},...e.canonicalPlanPromptVersion!==void 0?{canonicalPlanPromptVersion:e.canonicalPlanPromptVersion}:{},...e.approvalPromptRequiredVersion!==void 0?{approvalPromptRequiredVersion:e.approvalPromptRequiredVersion}:{},...e.approvalPromptVersion!==void 0?{approvalPromptVersion:e.approvalPromptVersion}:{},...e.approvalPromptStatus!==void 0?{approvalPromptStatus:e.approvalPromptStatus}:{},...e.approvalPromptTransport!==void 0?{approvalPromptTransport:e.approvalPromptTransport}:{},...e.approvalPromptMessageKind!==void 0?{approvalPromptMessageKind:e.approvalPromptMessageKind}:{},...e.approvalPromptLastAttemptAt!==void 0?{approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt}:{},...e.approvalPromptDeliveredAt!==void 0?{approvalPromptDeliveredAt:e.approvalPromptDeliveredAt}:{},...e.approvalPromptFailedAt!==void 0?{approvalPromptFailedAt:e.approvalPromptFailedAt}:{}}),this.approvalRationale=e.approvalRationale}get status(){return this._status}get harnessName(){return this.harness.name}get backendKind(){return this.harness.backendKind}get backendCapabilities(){return this.harness.capabilities}get backendConversationId(){return T(this)}approvalSnapshot(){return{requestedPermissionMode:this.requestedPermissionMode,currentPermissionMode:this.currentPermissionMode,approvalExecutionState:this.approvalExecutionState,approvalRationale:this.approvalRationale,planModeApproved:this.controlStateSnapshot().planModeApproved,pendingPlanApproval:this.pendingPlanApproval,planApprovalContext:this.planApprovalContext,planDecisionVersion:this.planDecisionVersion,actionablePlanDecisionVersion:this.actionablePlanDecisionVersion,canonicalPlanPromptVersion:this.canonicalPlanPromptVersion,approvalPromptRequiredVersion:this.approvalPromptRequiredVersion,approvalPromptVersion:this.approvalPromptVersion,approvalPromptStatus:this.approvalPromptStatus,approvalPromptTransport:this.approvalPromptTransport,approvalPromptMessageKind:this.approvalPromptMessageKind,approvalPromptLastAttemptAt:this.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:this.approvalPromptDeliveredAt,approvalPromptFailedAt:this.approvalPromptFailedAt,planApproval:this.planApproval,codexApprovalPolicy:this.codexApprovalPolicy}}worktreeSnapshot(){return{worktreePath:this.worktreePath,worktreeBranch:this.worktreeBranch,worktreeStrategy:this.worktreeStrategy,worktreeBaseBranch:this.worktreeBaseBranch,worktreePrTargetRepo:this.worktreePrTargetRepo,autoMergeParentSessionId:this.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:this.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:this.autoMergeResolverSessionId,worktreeLifecycle:this.worktreeLifecycle}}backendSnapshot(){return{harnessSessionId:this.harnessSessionId,backendRef:this.backendRef,harness:this.harnessName,backendKind:this.backendKind,backendConversationId:this.backendConversationId}}routingSnapshot(){return{route:this.route,originAgentId:this.originAgentId,originChannel:this.originChannel,originThreadId:this.originThreadId,originSessionKey:this.originSessionKey}}get waitingForInputFired(){return this.turnRuntime.waitingForInputFired}set waitingForInputFired(e){this.turnRuntime.waitingForInputFired=e}get lastTurnHadQuestion(){return this.turnRuntime.lastTurnHadQuestion}set lastTurnHadQuestion(e){this.turnRuntime.lastTurnHadQuestion=e}get turnInProgress(){return this.turnRuntime.turnInProgress}set turnInProgress(e){this.turnRuntime.turnInProgress=e}get currentTurnText(){return this.turnRuntime.currentTurnText}set currentTurnText(e){this.turnRuntime.currentTurnText=e}get currentTurnPlanArtifact(){return this.turnRuntime.currentTurnPlanArtifact}set currentTurnPlanArtifact(e){this.turnRuntime.currentTurnPlanArtifact=e}get duration(){return(this.completedAt??Date.now())-this.startedAt}get phase(){return this.lifecycle}get isExplicitlyResumable(){return this.status!=="running"&&this.status!=="completed"&&this.killReason!=="done"&&!!this.backendConversationId}transition(e){if(!Ts[this._status].includes(e))throw new Error(`Session state error: cannot transition from ${this._status} to ${e}. This is an internal error â please report it.`);let n=this._status;this._status=e,this.applyControlEvent({type:"status.transition",status:e}),this.emit("statusChange",this,e,n)}setTimer(e,n,r){this.timers.set(e,n,r)}clearTimer(e){this.timers.clear(e)}clearAllTimers(){this.timers.clearAll()}markPendingPlanApproval(e){let n=this.latestPlanArtifactVersion;this.approvalRationale=void 0,this.applyControlEvent({type:"plan.requested",context:e});let r=this.actionablePlanDecisionVersion??this.planDecisionVersion;this.currentTurnPlanArtifact&&r>0?(this.latestPlanArtifact=this.currentTurnPlanArtifact,this.latestPlanArtifactVersion=r):n!==r&&(this.latestPlanArtifact=void 0,this.latestPlanArtifactVersion=void 0)}clearPendingPlanApproval(){this.applyControlEvent({type:"plan.cleared"})}markAwaitingUserInput(){this.applyControlEvent({type:"input.requested"})}queueWorktreeFinalizationPrompt(){if(!this.multiTurn||!this.messageStream||!this.worktreePath||!this.worktreeStrategy||this.worktreeStrategy==="off"||this.worktreeFinalizationPromptIssued)return!1;let e=dt(this.worktreePath);if(e.length===0)return!1;this.worktreeFinalizationPromptIssued=!0;let n=e.slice(0,20).map(i=>`- ${i}`).join(`
|
|
62
|
+
`),r=e.length>20?`
|
|
63
|
+
- ...and ${e.length-20} more`:"",o=["Your worktree still has uncommitted changes, so this session cannot finish yet.","",`Worktree: ${this.worktreePath}`,`Branch: ${this.worktreeBranch??"(unknown)"}`,"","Dirty entries:",`${n}${r}`,"","Before finishing, run `git status --short` in the worktree and do exactly one of these:","1. If these are real task changes, commit them on the worktree branch with `git add` and `git commit`.","2. If these are temporary or unrelated artifacts, remove or restore them so the worktree is clean.","3. If no repository changes were intended, leave the worktree clean and say that no changes were needed.","","Do not finish again until `git status --short` is clean or all real task changes are committed."].join(`
|
|
64
|
+
`);return this.messageStream.push(this.harness.buildUserMessage(o,this.backendConversationId??"")),!0}async start(){try{let e;this.multiTurn?(this.messageStream=new In,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),e=this.messageStream):e=this.prompt;let n=this.harness.launch({prompt:e,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,fastMode:this.fastMode,permissionMode:this.permissionMode,codexApprovalPolicy:this.codexApprovalPolicy,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,backendRef:this.backendRef,worktreeStrategy:this.worktreeStrategy,originalWorkdir:this.originalWorkdir??this.workdir,abortController:this.abortController,mcpServers:Ni(),canUseTool:this.canUseTool});this.harnessHandle=n,this.setTimer("startup",mp,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(e){let n=e instanceof Error?e.message:String(e);this.transitionToTerminal("failed",{error:n});return}this.consumeMessages(this.harnessHandle.messages).catch(e=>{let n=e instanceof Error?e.message:String(e),r=e instanceof Error?e.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${n}`,r),this.isActive&&this.transitionToTerminal("failed",{error:n})})}async sendMessage(e){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.turnRuntime.beginUserTurn(),this.applyControlEvent({type:"turn.started"});let n=e;if(this.pendingModeSwitch){let r=this.pendingModeSwitch,o=!1,i=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(r),this.currentPermissionMode=r,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:r}),this.pendingModeSwitch=void 0,i=!0,o=!0}catch(s){throw console.error(`[Session ${this.id}] setPermissionMode(${r}) FAILED: ${Fn(s)}`),this.markPendingPlanApproval(this.planApprovalContext??"plan-mode"),new Error(`Failed to switch permission mode to ${r}: ${Fn(s)}`)}else this.pendingModeSwitch=void 0,i=!0,o=!0,`${this.id}${this.currentPermissionMode}`;i&&(this.clearPendingPlanApproval(),r!=="plan"&&this.applyControlEvent({type:"plan.approved"})),o&&(n=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
|
|
65
|
+
|
|
66
|
+
${e}`)}else if((this.pendingPlanApproval||this.approvalState==="changes_requested")&&!this.planModeApproved&&(this.approvalState!=="changes_requested"&&this.applyControlEvent({type:"plan.changes_requested"}),n=`[SYSTEM: The user wants changes to your plan. Revise the plan based on their feedback below, then re-submit your revised plan for approval. Do NOT start implementing yet.]
|
|
67
|
+
|
|
68
|
+
${e}`,this.harnessHandle?.setPermissionMode))try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan",this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:"plan"})}catch(r){`${this.id}${Fn(r)}`}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(n,this.backendConversationId??""));else if(this.harnessHandle?.streamInput){let r=this.harness.buildUserMessage(n,this.backendConversationId??"");async function*o(){yield r}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){return!this.turnInProgress||!this.harnessHandle?.interrupt?!1:(await this.harnessHandle.interrupt(),!0)}async submitPendingInputOption(e){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputOption)return!1;let n=await this.harnessHandle.submitPendingInputOption(e);return n&&(this.waitingForInputFired=!1),n}async submitPendingInputText(e){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputText)return!1;let n=await this.harnessHandle.submitPendingInputText(e);return n&&(this.waitingForInputFired=!1),n}switchPermissionMode(e){this.pendingModeSwitch=e}get isActive(){return this._status==="starting"||this._status==="running"}kill(e){this.transitionToTerminal("killed",{reason:e})}complete(e="done"){this.transitionToTerminal("completed",{reason:e})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(e){return e===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-e)}resetIdleTimer(){if(!this.multiTurn)return;let e=(E.idleTimeoutMinutes??15)*60*1e3;this.setTimer("idle",e,()=>{this._status==="running"&&(this.applyControlEvent({type:"terminal.entered",suspended:!0}),this.kill("idle-timeout"))})}teardown(){this.clearAllTimers(),this.completedAt||(this.completedAt=Date.now()),this.messageStream&&this.messageStream.end(),this.harnessHandle?.interrupt&&this.harnessHandle.interrupt().catch(e=>{`${this.id}${Fn(e)}`}),this.abortController.abort(),this.applyControlEvent({type:"terminal.entered",suspended:this.lifecycle==="suspended"})}transitionToTerminal(e,n={}){this.isActive&&(this.turnInProgress=!1,n.reason&&(this.killReason=n.reason),n.error!==void 0&&(this.error=n.error),this.completedAt=Date.now(),this.applyControlEvent({type:"terminal.entered",suspended:e==="killed"&&n.reason==="idle-timeout"}),this.transition(e),this.teardown())}async consumeMessages(e){for await(let n of e){if(!this.isActive)break;this.resetIdleTimer(),this.harnessEvents.applyMessage(n,{pendingPlanApproval:this.pendingPlanApproval,currentPermissionMode:this.currentPermissionMode,permissionMode:this.permissionMode,planModeApproved:this.planModeApproved,pendingInputState:this.pendingInputState})}}controlStateSnapshot(){return{status:this._status,lifecycle:this.lifecycle,approvalState:this.approvalState,approvalExecutionState:this.approvalExecutionState,worktreeState:this.worktreeState,runtimeState:this.runtimeState,deliveryState:this.deliveryState,requestedPermissionMode:this.requestedPermissionMode,currentPermissionMode:this.currentPermissionMode,pendingPlanApproval:this.pendingPlanApproval,planApprovalContext:this.planApprovalContext,planDecisionVersion:this.planDecisionVersion,actionablePlanDecisionVersion:this.actionablePlanDecisionVersion,canonicalPlanPromptVersion:this.canonicalPlanPromptVersion,approvalPromptRequiredVersion:this.approvalPromptRequiredVersion,approvalPromptVersion:this.approvalPromptVersion,approvalPromptStatus:this.approvalPromptStatus,approvalPromptTransport:this.approvalPromptTransport,approvalPromptMessageKind:this.approvalPromptMessageKind,approvalPromptLastAttemptAt:this.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:this.approvalPromptDeliveredAt,approvalPromptFailedAt:this.approvalPromptFailedAt,planModeApproved:this.planModeApproved}}applyControlEvent(e){let n=Do(this.controlStateSnapshot(),e);this.applyControlState(n)}applyControlPatch(e){let n=Ms(this.controlStateSnapshot(),e);this.applyControlState(n)}setControlField(e,n){this.applyControlPatch({[e]:n})}applyControlState(e){let n=this.lifecycle;this.lifecycle=e.lifecycle,this.approvalState=e.approvalState,this.approvalExecutionState=e.approvalExecutionState,this.worktreeState=e.worktreeState,this.runtimeState=e.runtimeState,this.deliveryState=e.deliveryState,this.pendingPlanApproval=e.pendingPlanApproval,this.planApprovalContext=e.planApprovalContext,this.planDecisionVersion=e.planDecisionVersion,this.actionablePlanDecisionVersion=e.actionablePlanDecisionVersion,this.canonicalPlanPromptVersion=e.canonicalPlanPromptVersion,this.approvalPromptRequiredVersion=e.approvalPromptRequiredVersion,this.approvalPromptVersion=e.approvalPromptVersion,this.approvalPromptStatus=e.approvalPromptStatus,this.approvalPromptTransport=e.approvalPromptTransport,this.approvalPromptMessageKind=e.approvalPromptMessageKind,this.approvalPromptLastAttemptAt=e.approvalPromptLastAttemptAt,this.approvalPromptDeliveredAt=e.approvalPromptDeliveredAt,this.approvalPromptFailedAt=e.approvalPromptFailedAt,this.planModeApproved=e.planModeApproved,n!==this.lifecycle&&this.emit("lifecycleChange",this,this.lifecycle,n)}};var fp=50,gp=1,hp=new Set(["starting","running","completed","failed","killed"]),Sp=5,yp=1440*60*1e3,Kn=new Set(["merged","released","dismissed","no_change"]);function kp(t){let e=Number(t);return!Number.isFinite(e)||e<gp?fp:Math.floor(e)}function vp(t){return typeof t=="string"&&hp.has(t)}function wp(t){let e=t.split(`
|
|
69
|
+
`);return e.at(-1)===""&&e.pop(),e}function Ko(t){return t.backendRef?.conversationId??t.harnessSessionId}function Pp(t,e){return e&&Kn.has(e)&&(!t||!Kn.has(t))?e:t??e}function bp(t,e){return e&&Kn.has(e.state)&&(!t||!Kn.has(t.state))?e:t??e}function Js(t,e,n){let r=Qs(t,"utf-8"),o=wp(r);return e.full?o:o.slice(-n)}function Ap(t,e,n){if(t.status!=="starting"&&t.status!=="running")return null;let r=st(t.id);if(!qo(r))return null;try{return Js(r,e,n)}catch{return null}}function Rp(t){let e=ve(t.duration),n=` | Cost: $${t.costUsd.toFixed(4)}`,r=t.phase?` | Phase: ${t.phase}`:"",o=t.lifecycle&&t.lifecycle!==t.phase?` | Lifecycle: ${t.lifecycle}`:"";return[`Session: ${t.name} [${t.id}] | Status: ${t.status.toUpperCase()}${r}${o}${n} | Duration: ${e}`,`${"â".repeat(60)}`].join(`
|
|
70
|
+
`)}function Ys(t,e){let n=t.name||t.sessionId||Ko(t)||"unknown",r=t.lifecycle?` | Phase: ${t.lifecycle}`:"";return[`Session: ${n} | Status: ${t.status.toUpperCase()}${r} | Cost: $${t.costUsd.toFixed(4)}`,e,`${"â".repeat(60)}`].join(`
|
|
71
|
+
`)}function Ip(t){return`(retrieved from ${t.outputPath} â evicted from runtime cache â showing persisted output)`}function xp(t){return t.outputPath?`(persisted session metadata recovered; output file is unavailable at ${t.outputPath})`:"(persisted session metadata recovered; no output file was recorded)"}function zs(t,e){let n=Ys(t,xp(t)),r=Ko(t),o=r?`
|
|
72
|
+
Backend session: ${r}`:"";return`${n}
|
|
73
|
+
(no persisted output available: ${e})${o}`}function Tp(t){let e=[];return t.error&&e.push(`Error: ${t.error}`),t.result?.result&&e.push(`Result: ${t.result.result}`),t.result&&e.push(`Result status: ${t.result.subtype}`),e.length>0?`
|
|
71
74
|
(no output yet)
|
|
72
75
|
${e.join(`
|
|
73
76
|
`)}`:`
|
|
74
|
-
(no output yet)`}function
|
|
75
|
-
`),
|
|
76
|
-
${
|
|
77
|
-
(output file was empty)`}catch(
|
|
78
|
-
${
|
|
79
|
-
`)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(
|
|
80
|
-
${
|
|
77
|
+
(no output yet)`}function Un(t,e,n={}){let r=kp(n.lines),o=t.resolve(e);if(!o){let l=t.getPersistedSession(e);if(l?.outputPath&&qo(l.outputPath))try{let u=Js(l.outputPath,n,r).join(`
|
|
78
|
+
`),p=Ys(l,Ip(l));return u?`${p}
|
|
79
|
+
${u}`:`${p}
|
|
80
|
+
(output file was empty)`}catch(u){let p=u instanceof Error?u.message:String(u);return`Error: Session "${e}" was cleaned up (expired) and output file could not be read: ${p}`}return l?.outputPath?zs(l,`output file is missing at ${l.outputPath}`):l?zs(l,"no outputPath is stored for this recovered session"):`Error: Session "${e}" not found.`}let i=Ap(o,n,r),s=i&&i.length>0?i:n.full?o.getOutput():o.getOutput(r),a=Rp(o),d=s.length===0?`${a}${Tp(o)}`:`${a}
|
|
81
|
+
${s.join(`
|
|
82
|
+
`)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(qo(o.planFilePath)){let l=Qs(o.planFilePath,"utf-8"),u="â".repeat(60);return`${d}
|
|
83
|
+
${u}
|
|
81
84
|
Plan file: ${o.planFilePath}
|
|
82
|
-
${
|
|
83
|
-
${
|
|
84
|
-
|
|
85
|
-
`)}function
|
|
86
|
-
|
|
87
|
-
`;function
|
|
88
|
-
`)}}let
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
`)}}catch(p){return{text:`Error sending message to session ${r.name} [${r.id}]: ${vp(p)}`,isError:!0}}}function Cb(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.message=="string"&&(e.approval_rationale===void 0||typeof e.approval_rationale=="string")}function Xc(t){return{name:"agent_respond",description:"Send a follow-up message to a running coding agent session. The session must be running. All sessions are multi-turn.",parameters:f.Object({session:f.String({description:"Session name or ID to respond to"}),message:f.String({description:"The message to send to the session"}),interrupt:f.Optional(f.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:f.Optional(f.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."})),approve:f.Optional(f.Boolean({description:"Set to true to escalate session permissions to bypassPermissions. Works in two scenarios: (1) approve a pending plan in plan mode, or (2) escalate a default-mode session to skip remaining OpenClaw approval checkpoints. No-op if already in bypassPermissions mode. In plan mode without a pending plan, this flag is ignored."})),approval_rationale:f.Optional(f.String({description:"Optional structured rationale for a direct delegated plan approval. Use this instead of embedding the rationale in message text when approve=true for a pending plan."}))}),async execute(e,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Cb(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve?, approval_rationale? }."}]};let n=await Et(I,{session:r.session,message:r.message,interrupt:r.interrupt,userInitiated:r.userInitiated,approve:r.approve,approvalRationale:r.approval_rationale});return{isError:n.isError??!1,content:[{type:"text",text:n.text}]}}}}ze();pe();function Eb(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.summary=="string"}function ef(t){return{name:"agent_request_plan_approval",description:"Send a plan-approval decision prompt to the user for a session that is already waiting on plan approval. Reuses the plugin's Approve/Revise/Reject buttons so the user can decide directly from the message.",parameters:f.Object({session:f.String({description:"Session name or ID awaiting plan approval"}),summary:f.String({description:"Concise user-facing summary of scope, risk, and any concerns that should accompany the approval buttons"})}),async execute(e,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Eb(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, summary }."}]};let n=I.requestPlanApprovalFromUser(r.session,r.summary);return{isError:n.startsWith("Error:"),content:[{type:"text",text:n}]}}}}ze();pe();Je();var Tp=["off","manual","ask","delegate","auto-merge","auto-pr"],Cs=new Set(Tp),$b=["low","medium","high","xhigh","max"],tf=new Set($b);function Mb(t){return typeof t=="string"&&Cs.has(t)}var Ob=f.Union(Tp.map(t=>f.Literal(t)),{description:"Optional worktree strategy for the planning session. Use auto-pr when the follow-up should branch and open/update a PR after approved implementation."});function _b(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.offer_id=="string"&&typeof e.offer_text=="string"&&typeof e.plan_prompt=="string"&&typeof e.plan_workdir=="string"&&(e.plan_worktree_strategy==null||Mb(e.plan_worktree_strategy))&&(e.plan_name==null||typeof e.plan_name=="string")&&(e.target_channel==null||typeof e.target_channel=="string")&&(e.target_thread_id==null||typeof e.target_thread_id=="string"||typeof e.target_thread_id=="number")&&(e.target_session_key==null||typeof e.target_session_key=="string")}function Db(t,e){let r=_n(t,e.target_channel,e.target_session_key);if(r)return e.target_thread_id!=null&&(r.threadId=String(e.target_thread_id)),r}async function Lb(t,e){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=Db(t,e);return!r?.provider||!r.target?{content:[{type:"text",text:"Error: Could not resolve a direct delivery route for the plan offer."}]}:(I.sendPlanOffer({offerId:e.offer_id,route:r,text:e.offer_text,planName:e.plan_name??e.offer_id,planPrompt:e.plan_prompt,planWorkdir:e.plan_workdir,planWorktreeStrategy:e.plan_worktree_strategy}),{content:[{type:"text",text:`Interactive plan offer queued for ${r.provider}|${r.target}${r.threadId?`#${r.threadId}`:""}.`}]})}function rf(t){return{name:"agent_send_plan_offer",description:"Post a user-facing message to the current or explicit chat route with human-gated Start Plan and Dismiss inline buttons. Use this when an external workflow wants the user to open a plan-only code-agent session from the message.",parameters:f.Object({offer_id:f.String({description:"Stable offer identifier, for example 'plugin-readiness-v2026.5.5'."}),offer_text:f.String({description:"Final user-facing text to deliver."}),plan_prompt:f.String({description:"Prompt to seed into the plan-only session when the user clicks Start Plan."}),plan_workdir:f.String({description:"Working directory for the planning session."}),plan_worktree_strategy:f.Optional(Ob),plan_name:f.Optional(f.String({description:"Optional explicit session name for the planning session."})),target_channel:f.Optional(f.String({description:"Optional explicit route like 'telegram|<chat-id>'."})),target_thread_id:f.Optional(f.Union([f.String(),f.Number()],{description:"Optional explicit topic/thread id."})),target_session_key:f.Optional(f.String({description:"Optional explicit session key for wake routing."}))}),async execute(e,r){return _b(r)?Lb(t,r):{content:[{type:"text",text:"Error: Invalid parameters. Expected { offer_id, offer_text, plan_prompt, plan_workdir }."}]}}}}ze();pe();function nf(t){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:f.Object({}),async execute(e,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=I.getMetrics(),o=I.list("running").length;return{content:[{type:"text",text:es(n,o)}]}}}}ze();Je();pe();Pt();Vo();import{existsSync as _s}from"fs";function Nb(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function qb(t){return t.mergeResult.stashPopConflict?[`Pre-merge stash pop conflicted; run git stash show ${t.mergeResult.stashRef??"stash@{0}"} in ${t.repoDir} to review stashed changes.`]:t.mergeResult.stashed?[`Pre-existing changes on ${t.baseBranch} were auto-stashed and restored.`]:[]}function Ds(t){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:f.Object({session:f.String({description:"Session name or ID to merge"}),base_branch:f.Optional(f.String({description:"Base branch to merge into (default: main)"})),strategy:f.Optional(f.Union([f.Literal("merge"),f.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:f.Optional(f.Boolean({description:"Push the base branch after successful merge (default: false)"})),delete_branch:f.Optional(f.Boolean({description:"Delete the worktree branch after successful merge (default: true)"}))}),async execute(e,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Nb(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let n=Gn(I,r.session),o=n.activeSession,i=n.persistedSession;if(!o&&!i)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let{worktreePath:a,originalWorkdir:u,branchName:p}=n;if(!a||!u)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}]};if(!p)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree at ${a}. The worktree may have been removed and no persisted branch name is available.`}]};_s(a)||console.info(`[agent_merge] Worktree directory ${a} no longer exists; proceeding with merge via originalWorkdir (${u})`);let d=u;if(!_s(u))return{content:[{type:"text",text:`Error: originalWorkdir "${u}" does not exist.`}]};let l=r.base_branch??wr(d),m=l,c=r.strategy??"merge",h=r.push===!0,y=r.delete_branch!==!1;if(i?.worktreeLifecycle?.state==="merged"||i?.worktreeMerged)return{content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" is already merged.`}]};if(_s(a)&&!Bo(d,p,m)&&jn(a))return{content:[{type:"text",text:[`\u274C Merge blocked: session "${r.session}" has uncommitted worktree changes but branch ${p} has no commits ahead of ${m}.`,`Worktree: ${a}`,"Resume or inspect the session, then commit real task changes or clean temporary files before retrying agent_merge."].join(`
|
|
93
|
-
`)}]};let
|
|
94
|
-
|
|
95
|
-
(Pre-existing changes on ${
|
|
96
|
-
|
|
97
|
-
${
|
|
98
|
-
`);try{let
|
|
99
|
-
`)}]}}}}
|
|
100
|
-
`).trim()}]}}}}
|
|
101
|
-
`)}function
|
|
102
|
-
`).map(
|
|
103
|
-
`);return o.length<=
|
|
104
|
-
`)}function
|
|
105
|
-
`)}
|
|
106
|
-
|
|
107
|
-
`)}]}}}}ze();pe();function iA(t){return!!t&&typeof t=="object"&&typeof t.task=="string"}function xf(t){return{name:"goal_stop",description:"Stop an explicit goal task and kill its underlying agent session.",parameters:f.Object({task:f.String({description:"Goal task name or ID"})}),async execute(e,r){if(!me)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!iA(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task }."}]};let n=me.stopTask(r.task);return n?{content:[{type:"text",text:n.action==="already_terminal"?`Task is already ${n.task.status}.`:`Task "${n.task.name}" (${n.task.id}) stopped.`}]}:{content:[{type:"text",text:`Error: Goal task "${r.task}" not found.`}]}}}}ze();pe();function sA(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.task=="string"&&typeof e.goal=="string"}function Mp(t,e){switch(t.action){case"updated":return`Task "${t.task.name}" (${t.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 t.task.status!=="waiting_for_user"?`Task is already ${t.task.status}.`:`Error: Goal task "${t.task.name}" is ${t.task.status} and cannot be edited.`}}function Pf(t){return{name:"goal_edit",description:"Edit the goal text for an active goal task without stopping or relaunching its session.",parameters:f.Object({task:f.String({description:"Goal task name or ID"}),goal:f.String({description:"Replacement goal text"})}),async execute(e,r){if(!me)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!sA(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task, goal }."}]};let n=me.editTask(r.task,r.goal);return{content:[{type:"text",text:Mp(n,r.task)}]}}}}pe();Ws();import{createHash as aA}from"crypto";var wt="code-agent";var uA=new Set(["1","true","yes","on"]);function pA(){let t=process.env.OPENCLAW_CODE_AGENT_BUTTON_DIAGNOSTICS?.trim().toLowerCase();return!!(t&&uA.has(t))}function Vn(t){if(!(typeof t!="string"||t.length===0))return aA("sha256").update(t).digest("hex").slice(0,12)}function wf(t){return typeof t.callbackData=="string"?t.callbackData:typeof t.value=="string"?t.value:void 0}function Pe(t){let e=(t??[]).filter(n=>Array.isArray(n)&&n.length>0),r=e.flat();return{buttonRows:e.length||void 0,buttonCount:r.length||void 0,buttonLabels:r.length>0?r.map(n=>typeof n.label=="string"?n.label:void 0):void 0,callbackByteLengths:r.length>0?r.map(n=>{let o=wf(n);return o?Buffer.byteLength(o,"utf8"):void 0}):void 0,callbackHashes:r.length>0?r.map(n=>Vn(wf(n))):void 0,buttonStyles:r.length>0?r.map(n=>typeof n.style=="string"?n.style:void 0):void 0}}function Ar(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function bf(t){let e=Ar(t),r=Array.isArray(e?.blocks)?e.blocks:void 0;if(r)return r.map(n=>Ar(n)?.type).filter(n=>typeof n=="string"&&n.length>0)}function Af(t){let e=Ar(t),r=Array.isArray(e?.blocks)?e.blocks:void 0;if(!r)return;let n=r.map(o=>{let i=Ar(o);return i?.type!=="buttons"||!Array.isArray(i.buttons)?[]:i.buttons}).filter(o=>o.length>0);return n.length>0?n:void 0}function _p(t){let e=Af(t);return{presentationBlockTypes:bf(t),...Pe(e)}}function Dp(t){let e=Ar(t),r=e?.interactive,n=Ar(e?.channelData),o=Ar(n?.telegram),i=Array.isArray(o?.buttons)?o.buttons:void 0;return{renderedPayloadKeys:e?Object.keys(e).sort():void 0,interactiveBlockTypes:bf(r),...vf("interactive",Pe(Af(r))),...vf("telegramChannelData",Pe(i)),hasPresentation:!!e?.presentation,hasInteractive:!!r,hasTelegramChannelDataButtons:!!i?.some(a=>a.length>0)}}function Tf(t){let e=Ar(t);return e?{sendResultKeys:Object.keys(e).sort(),messageId:Op(e.messageId),chatId:Op(e.chatId),telegramThreadId:Op(e.messageThreadId??e.threadId),channel:typeof e.channel=="string"?e.channel:void 0}:{sendResultType:typeof t}}function Op(t){return typeof t=="string"||typeof t=="number"?t:void 0}function vf(t,e){let r={};for(let[n,o]of Object.entries(e))o!==void 0&&(r[`${t}${n.charAt(0).toUpperCase()}${n.slice(1)}`]=o);return r}function ie(t,e){if(!pA())return;let r=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0));console.info(`[CodeAgentButtonDiagnostics] ${JSON.stringify({event:t,callbackNamespace:wt,...r})}`)}function dA(t){let e=t.trim().replace(new RegExp(`^${wt}:`),"");return e||null}async function Gs(t,e,r=!1){try{await ct(t,{text:e,alreadyAcknowledged:r})}catch(n){let o=n instanceof Error?n.message:String(n);console.warn(`[callback-handler] Failed to resolve worktree prompt: ${o}`)}}function Vs(t){if(t&&typeof t=="object"&&"content"in t&&Array.isArray(t.content)){let e=t.content[0];return typeof e?.text=="string"?e.text:"(done)"}return"(done)"}function Rf(t){if(t&&typeof t=="object"&&"meta"in t){let e=t.meta;if(typeof e?.success=="boolean")return e.success}return Lp(Vs(t))}function Lp(t){return!/^\s*(?:Error\b:?|â|â ī¸)/.test(t)}function lA(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}function mA(t,e){if(lA(t.kind)){if(!e)return"This plan decision is stale because the session is no longer available.";if(t.planDecisionVersion!=null&&(e.actionablePlanDecisionVersion??e.planDecisionVersion)!=null&&t.planDecisionVersion!==(e.actionablePlanDecisionVersion??e.planDecisionVersion))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(t.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(t.kind==="plan-request-changes"&&e.approvalState==="changes_requested")return"Changes were already requested for this plan. Send your feedback to the agent instead."}}function cA(t){let e="callback"in t?t.callback?.payload??t.callback?.data:void 0,r="interaction"in t?t.interaction?.payload:void 0;return e??r??""}function Jo(t){let e=t instanceof Error?t.message:String(t);return/message is not modified/i.test(e)}function fA(t){let e=t instanceof Error?t.message:String(t);return/empty message/i.test(e)}async function ct(t,e={}){let r=t.respond,{alreadyAcknowledged:n=!1,forceTelegramMarkupEdit:o=!1,text:i}=e;if(t.channel==="telegram"){if(typeof i=="string"&&typeof r.editMessage=="function")try{await r.editMessage({text:i,buttons:[]}),typeof r.clearButtons=="function"&&await r.clearButtons();return}catch(u){if(Jo(u)){typeof r.clearButtons=="function"&&await r.clearButtons();return}let p=u instanceof Error?u.message:String(u);console.warn(`[callback-handler] Failed to edit Telegram worktree prompt before clearing buttons: ${p}`)}if(o&&typeof r.editButtons=="function")try{await r.editButtons({buttons:[]}),typeof r.clearButtons=="function"&&await r.clearButtons();return}catch(u){if(Jo(u)){typeof r.clearButtons=="function"&&await r.clearButtons();return}let p=u instanceof Error?u.message:String(u);console.warn(`[callback-handler] Failed to edit Telegram button markup before clearing buttons: ${p}`)}let a="callback"in t&&typeof t.callback?.messageText=="string"?t.callback.messageText:void 0;if(o&&typeof a=="string"&&typeof r.editMessage=="function")try{await r.editMessage({text:a,buttons:[]}),typeof r.clearButtons=="function"&&await r.clearButtons();return}catch(u){if(Jo(u)){typeof r.clearButtons=="function"&&await r.clearButtons();return}let p=u instanceof Error?u.message:String(u);console.warn(`[callback-handler] Failed to edit Telegram message markup before clearing buttons: ${p}`)}typeof r.clearButtons=="function"&&await r.clearButtons();return}if(typeof r.clearComponents=="function")try{await r.clearComponents(typeof i=="string"?{text:i}:void 0);return}catch(a){if(Jo(a))return;if(fA(a)){if(typeof i!="string"&&n)return;if(typeof i!="string"&&typeof r.acknowledge=="function"){await r.acknowledge();return}typeof i!="string"&&typeof r.acknowledge!="function"&&console.warn("[callback-handler] clearComponents failed with empty-message error and no acknowledge fallback available")}else{if(typeof i!="string")throw a;{let u=a instanceof Error?a.message:String(a);console.warn(`[callback-handler] clearComponents failed before text fallback: ${u}`)}}}if(typeof i=="string"&&typeof r.editMessage=="function")try{await r.editMessage({text:i})}catch(a){if(!Jo(a)){let u=a instanceof Error?a.message:String(a);console.warn(`[callback-handler] Failed to edit worktree prompt before clearing interactive state: ${u}`)}}typeof r.clearButtons=="function"&&await r.clearButtons()}async function gA(t){let e=t.respond;if(typeof e.acknowledge!="function")return!1;try{return await e.acknowledge(),!0}catch(r){let n=r instanceof Error?r.message:String(r);return console.warn(`[callback-handler] Failed to acknowledge callback before processing: ${n}`),!1}}async function we(t,e){if(t.channel==="telegram"){await t.respond.reply({text:e});return}await t.respond.reply({text:e,ephemeral:!0})}function Cf(t="telegram"){return ie("callback_handler_registered",{channel:t,namespace:wt}),{channel:t,namespace:wt,handler:async e=>{let r=await gA(e);if(!e.auth.isAuthorizedSender)return await we(e,"\u26D4 Unauthorized."),{handled:!0};let n=cA(e),o=dA(n);if(ie("callback_received",{channel:e.channel,namespace:wt,payloadByteLength:Buffer.byteLength(n,"utf8"),tokenHash:Vn(o),isAuthorizedSender:e.auth.isAuthorizedSender}),!o)return await we(e,"\u26A0\uFE0F Unrecognized callback payload."),{handled:!0};if(!I)return await we(e,"\u26A0\uFE0F Code agent service not running."),{handled:!0};let i=I.getActionToken(o);if(ie("callback_token_lookup_completed",{channel:e.channel,namespace:wt,tokenHash:Vn(o),tokenFound:!!i,actionKind:i?.kind,sessionId:i?.sessionId,planDecisionVersion:i?.planDecisionVersion}),!i)return await ct(e,{alreadyAcknowledged:r}),e.channel!=="telegram"&&await we(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};let a=i.sessionId,u=I.resolve?.(a)??I.getPersistedSession?.(a),p=u?.name??a,d=mA(i,u);if(ie("callback_plan_validation_completed",{channel:e.channel,namespace:wt,tokenHash:Vn(o),actionKind:i.kind,sessionId:a,sessionName:p,planDecisionVersion:i.planDecisionVersion,valid:!d}),d)return await ct(e,{alreadyAcknowledged:r}),await we(e,`\u26A0\uFE0F ${d}`),{handled:!0};let l=I.consumeActionToken(o);if(ie("callback_token_consume_completed",{channel:e.channel,namespace:wt,tokenHash:Vn(o),consumed:!!l,actionKind:l?.kind,sessionId:l?.sessionId,planDecisionVersion:l?.planDecisionVersion}),!l)return await ct(e,{alreadyAcknowledged:r,forceTelegramMarkupEdit:i.kind==="plan-offer-start"||i.kind==="plan-offer-dismiss"}),e.channel!=="telegram"&&await we(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};switch(l.kind){case"worktree-merge":{let m=await Ds().execute("callback",{session:a}),c=Vs(m);Rf(m)&&await Gs(e,`\u2705 Merge selected for [${p}]`,r),await we(e,c);break}case"worktree-decide-later":{let m=I.snoozeWorktreeDecision(a),c=Lp(m);c&&await Gs(e,`\u23ED\uFE0F Deferred for [${p}]`,r),await we(e,c?"\u23ED\uFE0F Snoozed 24h":m);break}case"worktree-dismiss":{let m=await I.dismissWorktree(a),c=Lp(m);c&&await Gs(e,`\u{1F5D1}\uFE0F Discarded for [${p}]`,r),await we(e,c?"\u2705 Discarded":m);break}case"worktree-create-pr":case"worktree-update-pr":{let m=await zo().execute("callback",{session:a}),c=Vs(m);Rf(m)&&await Gs(e,i.kind==="worktree-update-pr"?`\u{1F4EC} PR update selected for [${p}]`:`\u{1F4EC} PR selected for [${p}]`,r),await we(e,c);break}case"worktree-view-pr":{await ct(e,{alreadyAcknowledged:r});let m=I.getPersistedSession?.(a),c=i.targetUrl??m?.worktreePrUrl;await we(e,c?`PR: ${c}`:"\u26A0\uFE0F PR URL is no longer available.");break}case"plan-approve":{await ct(e,{alreadyAcknowledged:r}),I.clearPlanDecisionTokens(a);let m=await Et(I,{session:a,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});m.isError&&await we(e,`\u26A0\uFE0F ${m.text}`);break}case"plan-reject":{await ct(e,{alreadyAcknowledged:r});let m=bp(I,a);await we(e,`\u274C ${m.text}`);break}case"plan-request-changes":{await ct(e,{alreadyAcknowledged:r});let m=Ap(I,a);await we(e,`\u270F\uFE0F ${m.text}`);break}case"plan-offer-start":{if(!l.launchPrompt||!l.launchWorkdir){await ct(e,{alreadyAcknowledged:r,forceTelegramMarkupEdit:!0}),await we(e,"\u26A0\uFE0F This action is missing the plan launch context.");break}let m;try{m=I.launchPlanOffer({route:l.route,prompt:l.launchPrompt,workdir:l.launchWorkdir,name:l.launchName,worktreeStrategy:l.launchWorktreeStrategy})}catch(c){let h=c instanceof Error?c.message:String(c);await we(e,`\u26A0\uFE0F Failed to start planning session: ${h}`);break}await ct(e,{alreadyAcknowledged:r,forceTelegramMarkupEdit:!0}),await we(e,`\u25B6\uFE0F Planning session started: ${m.name} [${m.id}]`);break}case"plan-offer-dismiss":{await ct(e,{alreadyAcknowledged:r,forceTelegramMarkupEdit:!0}),await we(e,"\u2705 Dismissed.");break}case"session-restart":case"session-resume":{await ct(e,{alreadyAcknowledged:r});let m=await Et(I,{session:a,message:"Continue where you left off.",userInitiated:!0});await we(e,m.isError?`\u26A0\uFE0F ${m.text}`:`\u25B6\uFE0F ${m.text}`);break}case"view-output":{await ct(e,{alreadyAcknowledged:r});let m=await Ts().execute("callback",{session:a,lines:50});await we(e,Vs(m));break}case"question-answer":{if(await ct(e,{alreadyAcknowledged:r}),i.optionIndex==null){await we(e,"\u26A0\uFE0F Invalid question-answer action.");break}await I.resolvePendingInputOption(a,i.optionIndex),await we(e,"\u2705 Answer submitted.");break}default:{await ct(e,{alreadyAcknowledged:r}),await we(e,"\u26A0\uFE0F Unknown callback action.");break}}return{handled:!0}}}}pe();Je();function Hn(t){return Ef(t).map(e=>e.value)}function Ef(t){return Array.from(t.matchAll(/"[^"]*"|'[^']*'|\S+/g),e=>{let r=e[0],n=e.index??0;return{value:hA(r),raw:r,start:n,end:n+r.length}})}function Qo(t){let[e]=Ef(t);if(e)return{value:e.value,rest:t.slice(e.end).trimStart()}}function hA(t){return t.length>1&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function yA(t){return t instanceof Error?t.message:String(t)}function kA(t){let e=Hn(t),r,n=e;return e[0]==="--name"&&e[1]&&(r=e[1],n=e.slice(2)),{name:r,prompt:n.join(" ").trim()}}function $f(t){t.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /agent [--name <name>] <prompt>"};let{name:n,prompt:o}=kA(r);if(!o)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let i=Xi({prompt:o,name:n},e,I);if(i.kind!=="resolved")return{text:i.text};let a=I.spawn({prompt:o,name:n,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:is(e)});return{text:I.formatLaunchResult({prompt:o,workdir:i.workdir,harness:i.harness,permissionMode:i.permissionMode??K.permissionMode,planApproval:i.planApproval},a)}}catch(i){let a=yA(i),u=a.includes("Max sessions")?"":`
|
|
108
|
-
|
|
109
|
-
Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${
|
|
110
|
-
/agent_respond --interrupt <id-or-name> <message>`};let
|
|
111
|
-
|
|
112
|
-
`)}
|
|
113
|
-
`):
|
|
114
|
-
`)
|
|
115
|
-
`);
|
|
116
|
-
`);let e=t.verifierCommands.map(r=>`- ${r.label}: ${r.command}`).join(`
|
|
85
|
+
${u}
|
|
86
|
+
${l}`}}catch{}return d}function Vn(t,e="all",n,r={}){let o=t.listPersistedSessions()??[],s=Cp(t.list("all"),o);if(e!=="all"&&(s=s.filter(a=>a.status===e)),n&&(s=s.filter(a=>a.originChannel===n)),r.full){let a=Date.now()-yp;s=s.filter(d=>(d.startedAt??0)>=a)}else s=s.slice(0,Sp);return s.length===0?"No sessions found.":s.map(a=>ys(a)).join(`
|
|
87
|
+
|
|
88
|
+
`)}function Cp(t,e){let n=new Map;for(let r of e){if(!vp(r.status))continue;let o=r.completedAt??Date.now(),i=r.createdAt??o,s=Ko(r),a=r.sessionId??`persisted:${s??r.harnessSessionId}`;n.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})}for(let r of t){let o=n.get(r.id);n.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:Pp(r.worktreeState,o?.worktreeState),worktreeLifecycle:bp(r.worktreeLifecycle,o?.worktreeLifecycle),worktreeMerged:r.worktreeMerged??o?.worktreeMerged,worktreeMergedAt:r.worktreeMergedAt??o?.worktreeMergedAt,worktreePrUrl:r.worktreePrUrl??o?.worktreePrUrl})}return[...n.values()].sort((r,o)=>(o.startedAt??0)-(r.startedAt??0))}function Mp(t){if(!t||typeof t!="object")return"all";let e=t.status;switch(e){case"running":case"completed":case"failed":case"killed":case"all":return e;default:return"all"}}function Zs(t){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:m.Object({status:m.Optional(m.Union([m.Literal("all"),m.Literal("running"),m.Literal("completed"),m.Literal("failed"),m.Literal("killed")],{description:'Filter by status (default "all")'})),full:m.Optional(m.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=Mp(n),o=t?.workspaceDir?At(t.workspaceDir):void 0,i=!!(n&&typeof n=="object"&&n.full===!0);return{content:[{type:"text",text:Vn(v,r,o,{full:i})}]}}}}X();O();function Gn(t,e,n){let r=t.resolve(e);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`:n==="completed"?(r.complete(),`Session ${r.name} [${r.id}] marked as completed.`):(t.kill(r.id),`Session ${r.name} [${r.id}] has been terminated.`):`Error: Session "${e}" not found.`}function _p(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session!="string"?!1:e.reason===void 0?!0:e.reason==="completed"||e.reason==="killed"}function Xs(t){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:m.Object({session:m.String({description:"Session name or ID to terminate"}),reason:m.Optional(m.Union([m.Literal("completed"),m.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends â
notification). 'killed' (default) terminates it."}))}),async execute(e,n){return v?_p(n)?{content:[{type:"text",text:Gn(v,n.session,n.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."}]}}}}X();O();function Ep(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function Hn(t){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:m.Object({session:m.String({description:"Session name or ID to get output from"}),lines:m.Optional(m.Number({description:"Number of recent lines to show (default 50)"})),full:m.Optional(m.Boolean({description:"Show all available output"}))}),async execute(e,n){return v?Ep(n)?{content:[{type:"text",text:Un(v,n.session,{full:n.full,lines:n.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."}]}}}}X();O();te();Q();var $p=10;function Vo(t){return t instanceof Error?t.message:String(t)}function Ue(t){return N(t)??t.harnessSessionId??"unknown-session"}function Dp(t){if(!(!t.worktreeStrategy||t.worktreeStrategy==="off"))return gn(t)??N(t)??T(t)}function ea(t){return t.status!=="running"&&!!t.pendingPlanApproval&&!!T(t)}function Op(t){let e=t.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 Ft(t,e,n){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='${Ue(t)}', 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='${Ue(t)}', 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='${Ue(t)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${Ue(t)}', message='<next instruction>') to continue the running session.`,o=n?` ${n}`:"";return{text:`Resume unavailable for session ${t.name} [${Ue(t)}] (${e}).${o} ${r}`,isError:!0}}async function ta(t,e,n){try{let r={prompt:e.prompt,sessionIdOverride:gn(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 t.spawnAndAwaitRunning(r,{notifyLaunch:!1});return t.notifySession(o,`âļī¸ [${o.name}] Relaunched fresh`),{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} [${Ue(e)}]: ${Vo(r)}`,isError:!0}}}var Np=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
|
|
89
|
+
|
|
90
|
+
`;function na(t){let e=t?.replace(/\s+/g," ").trim();if(e)return ne(e,240)}function Uo(t){if(t.approvalState==="changes_requested"&&!jn(t))return`Plan changes were already requested for session ${t.name}. Wait for the revised plan before approving.`;if(t.approvalState==="rejected")return`Plan for session ${t.name} was already rejected.`}function jn(t){return t.pendingPlanApproval?(t.approvalState==="changes_requested"?t.actionablePlanDecisionVersion:t.actionablePlanDecisionVersion??t.planDecisionVersion)>0:!1}function Wp(t){return Uo(t)?!1:jn(t)||t.currentPermissionMode==="plan"}function Lp(t,e){let n=t.updatePersistedSession;if(typeof n!="function")return;let r=e.controlStateSnapshot();n.call(t,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 Bp(t){return(t.planDecisionVersion??0)+1}function ra(t,e){let n={approvalState:e,lifecycle:e==="rejected"?"terminal":"awaiting_user_input",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:Bp(t),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"&&(n.runtimeState="stopped"),n}function oa(t,e){let n=t;typeof n.applyControlPatch=="function"&&n.applyControlPatch(e),Object.assign(t,e)}function Go(t,e){let n=t.resolve(e),r=n?void 0:t.getPersistedSession(e),o=n??r,i=o?.name??e;if(t.clearPlanDecisionTokens?.(e),!o)return{text:`Plan rejected for [${i}].`,isError:!1};let s=ra(o,"rejected");return n?(oa(n,s),t.updatePersistedSession?.(e,s),t.kill(n.id,"user"),{text:`Plan rejected for [${n.name}]. Session stopped.`}):(t.updatePersistedSession?.(e,s),{text:`Plan rejected for [${i}]. Session remains stopped.`})}function Ho(t,e){let n=t.resolve(e),r=n?void 0:t.getPersistedSession(e),o=n??r,i=o?.name??e;if(t.clearPlanDecisionTokens?.(e),o){let s=ra(o,"changes_requested");n&&oa(n,s),t.updatePersistedSession?.(e,s)}return{text:`Type your revision feedback for [${i}] and I'll forward it to the agent.`}}async function Fp(t,e,n,r={}){let o=Et(e);if(!(o.kind==="resume"||ea(e)))return;let s=!!(r.approve&&Wp(e)),a=s?na(r.approvalRationale):void 0;try{if(o.kind!=="resume")return o.kind==="relaunch"?ta(t,e,n):Ft(e,o.reason);let d={prompt:s?Np+n:n,sessionIdOverride:o.stableSessionId,workdir:e.workdir,name:e.name,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,resumeSessionId:o.resumeSessionId,resumeWorktreeFrom:Dp(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: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:"approved_then_implemented",approvalRationale:a,planModeApproved:!0}:{},harness:"harnessName"in e?e.harnessName:e.harness},l=await t.spawnAndAwaitRunning(d,{notifyLaunch:!1});return s?(t.notifySession(l,`đ [${l.name}] Plan approved (resumed)`,"plan-approved"),{text:`Plan approved for session ${l.name} [${l.id}]. Session resumed in bypassPermissions mode. Use agent_output to see the response.`}):(t.notifySession(l,`âļī¸ [${l.name}] Auto-resumed`),{text:`Auto-resumed session ${l.name} [${l.id}]. Use agent_output to see the response.`})}catch(d){return Ft(e,"missing_backend_state",`Backend resume failed: ${Vo(d)}`)}}async function he(t,e){let n=t.resolve(e.session),r=n?void 0:t.getPersistedSession(e.session);if(!n&&!r)return{text:`Error: Session "${e.session}" not found.`,isError:!0};let o=n??r,i=o.status==="running"?{kind:"direct"}:Et(o),s=!e.approve&&o.lifecycle==="awaiting_plan_decision"&&o.pendingPlanApproval&&e.userInitiated?Op(e.message):void 0;if(s==="approve")return he(t,{...e,message:"Approved. Go ahead.",approve:!0});if(s==="revise")return Ho(t,n?.id??r?.sessionId??e.session);if(s==="reject")return Go(t,n?.id??r?.sessionId??e.session);if(e.approve){let d=Uo(o);if(d)return{text:d,isError:!0}}if(i.kind==="resume"||ea(o)){let d=await Fp(t,o,e.message,{approve:e.approve,approvalRationale:e.approvalRationale});if(d)return d}else{if(i.kind==="relaunch")return ta(t,o,e.message);if(i.kind==="unavailable")return Ft(o,i.reason)}if(!n)return _t(r)?Ft(r,"completed"):{text:`Error: Session ${r.name} [${Ue(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(n.status!=="running")return _t(n)?Ft(n,"completed"):{text:`Error: Session ${n.name} [${n.id}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};let a=E.maxAutoResponds??$p;if(e.userInitiated)n.resetAutoRespond();else if(n.autoRespondCount>=a)return{text:`â ī¸ Auto-respond limit reached (${n.autoRespondCount}/${a}). Ask the user to provide the answer for session ${n.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};try{if(e.approve){let g=Uo(n);if(g)return{text:g,isError:!0}}if(!e.approve&&n.pendingInputState?.allowsFreeText&&await n.submitPendingInputText?.(e.message)===!0){if(e.userInitiated){let h=ne(e.message,100);t.notifySession(n,`âĒī¸ [${n.name}] "${h}"`,"agent-respond")}e.userInitiated||n.incrementAutoRespond();let g=ne(e.message,80);return{text:[`Pending input answered for session ${n.name} [${n.id}].`,` Message: "${g}"`,"Use agent_output to see the response."].join(`
|
|
91
|
+
`)}}let l=!1;e.interrupt&&(l=await n.interrupt());let u=!!(e.approve&&jn(n)),p=u?na(e.approvalRationale):void 0,c="";if(e.approve&&jn(n)?(n.switchPermissionMode("bypassPermissions"),n.approvalRationale=p):e.approve&&n.currentPermissionMode==="default"?n.switchPermissionMode("bypassPermissions"):e.approve&&n.currentPermissionMode==="bypassPermissions"?c=`
|
|
92
|
+
âšī¸ approve=true was set but session is already in bypassPermissions mode.`:e.approve?c=`
|
|
93
|
+
â ī¸ approve=true was set but session has no pending plan approval.`:(n.pendingPlanApproval||n.approvalState==="changes_requested")&&(c=`
|
|
94
|
+
âšī¸ Session has a pending plan â sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`),await n.sendMessage(e.message),u&&Lp(t,n),u)t.notifySession(n,`đ [${n.name}] Plan approved`,"plan-approved");else if(e.userInitiated){let g=ne(e.message,100);t.notifySession(n,`âĒī¸ [${n.name}] "${g}"`,"agent-respond")}e.userInitiated||n.incrementAutoRespond();let f=ne(e.message,80);return u?{text:`Plan approved for session ${n.name} [${n.id}]. Use agent_output to see the response.`}:{text:[`Message sent to session ${n.name} [${n.id}].`,l?" (redirected active turn first)":e.interrupt?" (no active turn to interrupt)":"",` Message: "${f}"`,c,"Use agent_output to see the response."].filter(Boolean).join(`
|
|
95
|
+
`)}}catch(d){return{text:`Error sending message to session ${n.name} [${n.id}]: ${Vo(d)}`,isError:!0}}}function qp(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.message=="string"&&(e.approval_rationale===void 0||typeof e.approval_rationale=="string")}function ia(t){return{name:"agent_respond",description:"Send a follow-up message to a running coding agent session. The session must be running. All sessions are multi-turn.",parameters:m.Object({session:m.String({description:"Session name or ID to respond to"}),message:m.String({description:"The message to send to the session"}),interrupt:m.Optional(m.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:m.Optional(m.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."})),approve:m.Optional(m.Boolean({description:"Set to true to escalate session permissions to bypassPermissions. Works in two scenarios: (1) approve a pending plan in plan mode, or (2) escalate a default-mode session to skip remaining OpenClaw approval checkpoints. No-op if already in bypassPermissions mode. In plan mode without a pending plan, this flag is ignored."})),approval_rationale:m.Optional(m.String({description:"Optional structured rationale for a direct delegated plan approval. Use this instead of embedding the rationale in message text when approve=true for a pending plan."}))}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!qp(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve?, approval_rationale? }."}]};let r=await he(v,{session:n.session,message:n.message,interrupt:n.interrupt,userInitiated:n.userInitiated,approve:n.approve,approvalRationale:n.approval_rationale});return{isError:r.isError??!1,content:[{type:"text",text:r.text}]}}}}X();O();function Kp(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.summary=="string"}function sa(t){return{name:"agent_request_plan_approval",description:"Send a plan-approval decision prompt to the user for a session that is already waiting on plan approval. Reuses the plugin's Approve/Revise/Reject buttons so the user can decide directly from the message.",parameters:m.Object({session:m.String({description:"Session name or ID awaiting plan approval"}),summary:m.String({description:"Concise user-facing summary of scope, risk, and any concerns that should accompany the approval buttons"})}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Kp(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, summary }."}]};let r=v.requestPlanApprovalFromUser(n.session,n.summary);return{isError:r.startsWith("Error:"),content:[{type:"text",text:r}]}}}}X();O();function Up(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.summary=="string"}function aa(t){return{name:"agent_request_worktree_decision",description:"Send a worktree Merge/Open PR/Later/Discard decision prompt to the user for a delegated worktree session that is awaiting human choice.",parameters:m.Object({session:m.String({description:"Delegated session name or ID awaiting a worktree decision"}),summary:m.String({description:"Concise user-facing summary of scope, risk, and why human choice is needed"})}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Up(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, summary }."}]};let r=v.requestWorktreeDecisionFromUser(n.session,n.summary);return{isError:r.startsWith("Error:"),content:[{type:"text",text:r}]}}}}X();O();te();var jo=["off","manual","ask","delegate","auto-merge","auto-pr"],zn=new Set(jo),Vp=["low","medium","high","xhigh","max"],da=new Set(Vp);function Gp(t){return typeof t=="string"&&zn.has(t)}var Hp=m.Union(jo.map(t=>m.Literal(t)),{description:"Optional worktree strategy for the planning session. Use auto-pr when the follow-up should branch and open/update a PR after approved implementation."});function jp(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.offer_id=="string"&&typeof e.offer_text=="string"&&typeof e.plan_prompt=="string"&&typeof e.plan_workdir=="string"&&(e.plan_worktree_strategy==null||Gp(e.plan_worktree_strategy))&&(e.plan_name==null||typeof e.plan_name=="string")&&(e.target_channel==null||typeof e.target_channel=="string")&&(e.target_thread_id==null||typeof e.target_thread_id=="string"||typeof e.target_thread_id=="number")&&(e.target_session_key==null||typeof e.target_session_key=="string")}function zp(t,e){let n=Ye(t,e.target_channel,e.target_session_key);if(n)return e.target_thread_id!=null&&(n.threadId=String(e.target_thread_id)),n}async function Qp(t,e){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=zp(t,e);return!n?.provider||!n.target?{content:[{type:"text",text:"Error: Could not resolve a direct delivery route for the plan offer."}]}:(v.sendPlanOffer({offerId:e.offer_id,route:n,text:e.offer_text,planName:e.plan_name??e.offer_id,planPrompt:e.plan_prompt,planWorkdir:e.plan_workdir,planWorktreeStrategy:e.plan_worktree_strategy}),{content:[{type:"text",text:`Interactive plan offer queued for ${n.provider}|${n.target}${n.threadId?`#${n.threadId}`:""}.`}]})}function la(t){return{name:"agent_send_plan_offer",description:"Post a user-facing message to the current or explicit chat route with human-gated Start Plan and Dismiss inline buttons. Use this when an external workflow wants the user to open a plan-only code-agent session from the message.",parameters:m.Object({offer_id:m.String({description:"Stable offer identifier, for example 'plugin-readiness-v2026.5.5'."}),offer_text:m.String({description:"Final user-facing text to deliver."}),plan_prompt:m.String({description:"Prompt to seed into the plan-only session when the user clicks Start Plan."}),plan_workdir:m.String({description:"Working directory for the planning session."}),plan_worktree_strategy:m.Optional(Hp),plan_name:m.Optional(m.String({description:"Optional explicit session name for the planning session."})),target_channel:m.Optional(m.String({description:"Optional explicit route like 'telegram|<chat-id>'."})),target_thread_id:m.Optional(m.Union([m.String(),m.Number()],{description:"Optional explicit topic/thread id."})),target_session_key:m.Optional(m.String({description:"Optional explicit session key for wake routing."}))}),async execute(e,n){return jp(n)?Qp(t,n):{content:[{type:"text",text:"Error: Invalid parameters. Expected { offer_id, offer_text, plan_prompt, plan_workdir }."}]}}}}X();O();function ua(t){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:m.Object({}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=v.getMetrics(),o=v.list("running").length;return{content:[{type:"text",text:kn(r,o)}]}}}}X();te();O();fe();Kt();import{existsSync as Xn}from"fs";function Yp(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function Zp(t){return t.mergeResult.stashPopConflict?[`Pre-merge stash pop conflicted; run git stash show ${t.mergeResult.stashRef??"stash@{0}"} in ${t.repoDir} to review stashed changes.`]:t.mergeResult.stashed?[`Pre-existing changes on ${t.baseBranch} were auto-stashed and restored.`]:[]}function er(t){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:m.Object({session:m.String({description:"Session name or ID to merge"}),base_branch:m.Optional(m.String({description:"Base branch to merge into (default: main)"})),strategy:m.Optional(m.Union([m.Literal("merge"),m.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:m.Optional(m.Boolean({description:"Push the base branch after successful merge (default: false)"})),delete_branch:m.Optional(m.Boolean({description:"Delete the worktree branch after successful merge (default: true)"}))}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Yp(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let r=ut(v,n.session),o=r.activeSession,i=r.persistedSession;if(!o&&!i)return{content:[{type:"text",text:`Error: Session "${n.session}" not found.`}]};let{worktreePath:s,originalWorkdir:a,branchName:d}=r;if(!s||!a)return{content:[{type:"text",text:`Error: Session "${n.session}" does not have a worktree.`}]};if(!d)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.`}]};Xn(s)||`${s}${a}`;let l=a;if(!Xn(a))return{content:[{type:"text",text:`Error: originalWorkdir "${a}" does not exist.`}]};let u=n.base_branch??Pe(l),p=u,c=n.strategy??"merge",f=n.push===!0,g=n.delete_branch!==!1;if(i?.worktreeLifecycle?.state==="merged"||i?.worktreeMerged)return{content:[{type:"text",text:`âšī¸ Session "${n.session}" is already merged.`}]};if(Xn(s)&&!Nt(l,d,p)&<(s))return{content:[{type:"text",text:[`â Merge blocked: session "${n.session}" has uncommitted worktree changes but branch ${d} has no commits ahead of ${p}.`,`Worktree: ${s}`,"Resume or inspect the session, then commit real task changes or clean temporary files before retrying agent_merge."].join(`
|
|
96
|
+
`)}]};let h={content:[{type:"text",text:"â Merge did not run (internal error)"}]},y=r.persistedRef;return await v.enqueueMerge(l,async()=>{let k=v.getPersistedSession(n.session);if(k?.worktreeLifecycle?.state==="merged"||k?.worktreeMerged){h={content:[{type:"text",text:`âšī¸ Session "${n.session}" was already merged while waiting in queue.`}]};return}let b=Ie(l,d,u),A=Ln(l,d,p,c,s);if(A.success){let I=Zp({mergeResult:A,repoDir:l,baseBranch:p});if(f&&!Wn(l,p)){let M=`â ī¸ Merged ${d} â ${p} locally, but failed to push ${p}`;v.notifyWorktreeOutcome(r.notificationTarget,M,{detailLines:[`Branch ${d} was merged into ${p} in the local repository.`,`Pushing ${p} failed; remote state may not include the merge.`,"Cleanup was skipped so the branch/worktree remains available for follow-up.",...I]}),h={content:[{type:"text",text:M}]};return}g&&be(l,d);let W=!1;if(Xn(s)&&(W=me(l,s),Nn(l)),k)for(let M of qt({...r,persistedSession:k}))v.updatePersistedSession(M,{worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,lifecycle:"terminal",worktreeState:"merged",worktreeDisposition:"merged",worktreeLifecycle:{state:"merged",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"agent_merge",baseBranch:u,targetRepo:k.worktreePrTargetRepo,pushRemote:k.worktreePushRemote}});let S=qe({kind:"merge",branch:d,base:u,filesChanged:b?.filesChanged,insertions:b?.insertions,deletions:b?.deletions});v.notifyWorktreeOutcome(r.notificationTarget,S,{detailLines:[A.fastForward?"Merge type: fast-forward.":"Merge type: merge commit.",f?`Pushed ${p}.`:`Did not push ${p}; push was not requested.`,g?W?"Branch and worktree cleaned up.":"Branch deleted; worktree cleanup skipped.":"Branch/worktree cleanup was not requested.",...I]});let C=`â
${A.fastForward?"⥠Fast-forward":"đ Merge commit"}: ${d} â ${p}.${f?" Pushed.":""}${g?W?" Branch and worktree cleaned up.":" Branch deleted; worktree cleanup skipped.":""}`;A.stashPopConflict?C+=`
|
|
97
|
+
â ī¸ Pre-merge stash pop conflicted â run \`git stash show ${A.stashRef??"stash@{0}"}\` in ${l} to review stashed changes.`:A.stashed&&(C+=`
|
|
98
|
+
(Pre-existing changes on ${p} were auto-stashed and restored.)`),h={content:[{type:"text",text:C}]}}else if(A.rebaseConflict)h={content:[{type:"text",text:`â ī¸ Rebase conflicts â manual resolution required:
|
|
99
|
+
|
|
100
|
+
${A.error}`}]};else if(A.conflictFiles&&A.conflictFiles.length>0){let I=["Resolve merge conflicts in the following files and commit the resolution:","",...A.conflictFiles.map(W=>`- ${W}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${d}"`].join(`
|
|
101
|
+
`);try{let W=v.spawn({prompt:I,workdir:l,name:`${n.session}-conflict-resolver`,harness:se(),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});h={content:[{type:"text",text:`â ī¸ Merge conflicts in ${A.conflictFiles.length} file(s) â spawned conflict resolver session: ${W.name}`}]}}catch(W){h={content:[{type:"text",text:`â Merge conflicts detected, but failed to spawn resolver: ${W instanceof Error?W.message:String(W)}`}]}}}else h={content:[{type:"text",text:A.dirtyError?`â Merge blocked: ${A.error}`:`â Merge failed: ${A.error??"unknown error"}`}]}}),h}}}dr();X();O();Q();fe();Kt();function uc(t){return!!t&&typeof t=="object"}function ka(t){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:m.Object({workdir:m.Optional(m.String({description:"Restrict cleanup to sessions rooted in this repository"})),base_branch:m.Optional(m.String({description:"Override base branch for lifecycle resolution"})),mode:m.Optional(m.Union([m.Literal("preview_safe"),m.Literal("clean_safe"),m.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:m.Optional(m.Boolean({description:"Deprecated. Safe cleanup never removes live sessions."})),force:m.Optional(m.Boolean({description:"Deprecated alias for skip_session_check."})),dry_run:m.Optional(m.Boolean({description:"Show what would be cleaned without deleting anything."})),session:m.Optional(m.String({description:"Session name or ID to clean or dismiss."})),dismiss_session:m.Optional(m.Boolean({description:"When true and session is provided, permanently dismiss the worktree."}))}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!uc(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { workdir?, base_branch?, mode?, dry_run?, session?, dismiss_session? }."}]};let r=n.session,o=n.mode??(n.dry_run===!0?"preview_safe":"clean_safe"),i=o!=="clean_safe",s=o==="preview_all"||o==="clean_safe";if(r&&n.dismiss_session===!0)return{content:[{type:"text",text:await v.dismissWorktree(r)}]};let a=Jn(v);if(r&&(a=a.filter(f=>Yn(f,r)),a.length===0)){let f=ut(v,r);if(!f.persistedSession&&!f.activeSession)return{content:[{type:"text",text:`Error: Session "${r}" not found.`}]}}if(n.workdir&&(a=a.filter(f=>f.workdir===n.workdir)),a.length===0)return{content:[{type:"text",text:"No managed worktrees matched the requested scope."}]};let d=[],l=[],u=[],p=[];for(let f of a){let{persistedSession:g,activeSession:h,resolvedLifecycle:y}=Qn(v,f,{baseBranch:n.base_branch});if(!y.cleanupSafe){if(s){let k=y.reasons.length>0?y.reasons.map(Zn).join(", "):Ve(y.derivedState);l.push(`${f.name} [kept: ${k}]`)}continue}if(d.push(`${f.name} (${Ve(y.derivedState)})`),!i)try{let k=f.workdir;if(!((g??h)&&de(g??h))&&f.worktreePath&&me(k,f.worktreePath,{destructive:!1}),f.worktreeBranch&&be(k,f.worktreeBranch),g){let A=y.derivedState==="merged"||y.derivedState==="released"?y.derivedState:y.lifecycle.state;v.updatePersistedSession(f.id,{worktreePath:void 0,worktreeBranch:void 0,lifecycle:"terminal",worktreeState:"none",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeMerged:A==="merged"?!0:g.worktreeMerged,worktreeMergedAt:A==="merged"?g.worktreeMergedAt??new Date().toISOString():g.worktreeMergedAt,worktreeLifecycle:{...g.worktreeLifecycle??y.lifecycle,state:A,updatedAt:new Date().toISOString(),resolvedAt:g.worktreeLifecycle?.resolvedAt??new Date().toISOString(),resolutionSource:g.worktreeLifecycle?.resolutionSource??"maintenance",baseBranch:n.base_branch??y.lifecycle.baseBranch??g.worktreeBaseBranch,targetRepo:g.worktreePrTargetRepo,pushRemote:g.worktreePushRemote,notes:y.reasons}})}u.push(`${f.name} (${Ve(y.derivedState)})`)}catch(k){p.push(`${f.name}: ${k instanceof Error?k.message:String(k)}`)}}let c=[o==="clean_safe"?"Clean all safe:":o==="preview_all"?"Worktree lifecycle review:":"Clean all safe preview:"];return c.push(` SAFE ${i?"NOW":"FOUND"} (${d.length}): ${d.join(", ")||"(none)"}`),s&&c.push(` KEPT (${l.length}): ${l.join(", ")||"(none)"}`),i||(c.push(` CLEANED (${u.length}): ${u.join(", ")||"(none)"}`),c.push(` FAILURES (${p.length}): ${p.join(", ")||"(none)"}`)),{content:[{type:"text",text:c.join(`
|
|
102
|
+
`)}]}}}}X();O();Kt();function pc(t){return!0}function va(t){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:m.Object({session:m.Optional(m.String({description:"Session name or ID to show status for (optional, shows all if omitted)"}))}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!pc(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let r=n.session,o=Jn(v);if(r&&(o=o.filter(s=>Yn(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:d}=Qn(v,s),l=d.cleanupSafe?"safe now":d.preserve?"preserve":"blocked";i.push(`Session: ${s.name} [${s.id}]`),i.push(` Branch: ${s.worktreeBranch??"(unknown)"} â ${d.lifecycle.baseBranch??a?.worktreeBaseBranch??"main"}`),i.push(` Repo: ${s.workdir}`),i.push(` Lifecycle:${Ve(d.lifecycle.state)}`),d.derivedState!==d.lifecycle.state&&i.push(` Derived: ${Ve(d.derivedState)}`),i.push(` Cleanup: ${l}`),d.evidence.prUrl&&i.push(` PR: ${d.evidence.prUrl} (${d.evidence.prState??"unknown"})`),(d.evidence.branchAheadCount!=null||d.evidence.baseAheadCount!=null)&&i.push(` Ahead: ${d.evidence.branchAheadCount??0} ahead / ${d.evidence.baseAheadCount??0} behind`),i.push(` Reasons: ${d.reasons.length>0?d.reasons.map(Zn).join(", "):"none"}`),i.push("")}return{content:[{type:"text",text:i.join(`
|
|
103
|
+
`).trim()}]}}}}X();O();te();import{existsSync as cc}from"fs";function mc(t=[]){return t.map((e,n)=>({label:`check-${n+1}`,command:e.trim()})).filter(e=>e.command.length>0)}function lr(t,e){let n=t.goal.trim();if(!n)return{kind:"error",text:"Error: goal must not be empty."};let r=t.workdir||e.workspaceDir||E.defaultWorkdir||process.cwd();if(!cc(r))return{kind:"error",text:`Error: Working directory does not exist: ${r}`};let o=mc(t.verifierCommands),i=t.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=t.harness??se(),a=t.model??Qe(s),d=en(s);if(!a&&(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(a&&!hn(a,d))return{kind:"error",text:`Error: Model "${a}" is not allowed. Permitted models: ${d?.join(", ")}`};let l=e.sessionKey||void 0,u=tn(e),p=bt(e,u),c=Ye(e,p,l);return{kind:"resolved",goal:n,name:t.name,workdir:r,model:a,reasoningEffort:xe(s),fastMode:Je(s),systemPrompt:t.systemPrompt,allowedTools:t.allowedTools,maxIterations:t.maxIterations,permissionMode:t.permissionMode??"bypassPermissions",harness:s,loopMode:i,completionPromise:t.completionPromise,originChannel:p,originThreadId:c?.threadId,originAgentId:e.agentId||void 0,originSessionKey:l,route:c,verifierCommands:o}}function ur(t,e){return["Goal task launched.",` Name: ${t.name}`,` ID: ${t.id}`,` Dir: ${t.workdir}`,` Session: ${t.sessionName} [${t.sessionId}]`,` Harness: ${e.harness}`,` Model: ${e.model??"default"}`,...e.fastMode?[" Fast mode: enabled"]:[],` Loop mode: ${t.loopMode}`,` Max controller iterations: ${t.maxIterations}`,` Goal: "${e.goal.length>100?`${e.goal.slice(0,100)}...`:e.goal}"`,...t.loopMode==="ralph"?[` Completion promise: ${t.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 goal_status to follow progress or goal_stop to terminate the task."].join(`
|
|
104
|
+
`)}function fc(t){return!t||typeof t!="object"?!1:typeof t.goal=="string"}function wa(t){return{name:"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:m.Object({goal:m.String({description:"End goal for the autonomous task"}),verifier_commands:m.Optional(m.Array(m.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:m.Optional(m.String({description:"Short task name (kebab-case preferred)"})),workdir:m.Optional(m.String({description:"Working directory (defaults to cwd / configured workspace)"})),model:m.Optional(m.String({description:"Model name to use"})),system_prompt:m.Optional(m.String({description:"Additional system prompt"})),allowed_tools:m.Optional(m.Array(m.String(),{description:"Allowed tools for the underlying agent session"})),max_iterations:m.Optional(m.Number({description:"Maximum verifier-driven repair iterations",minimum:1})),goal_mode:m.Optional(m.Union([m.Literal("ralph"),m.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:m.Optional(m.String({description:"Exact completion promise for Ralph-mode loops. Defaults to 'DONE'."})),permission_mode:m.Optional(m.Union([m.Literal("default"),m.Literal("plan"),m.Literal("bypassPermissions")],{description:"Permission mode for the underlying agent session. Defaults to bypassPermissions for autonomous goal loops."})),harness:m.Optional(m.String({description:"Agent harness to use ('claude-code', 'codex', or experimental 'opencode')."}))}),async execute(e,n){if(!B)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!fc(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { goal }."}]};let r=lr({goal:n.goal,verifierCommands:n.verifier_commands,name:n.name,workdir:n.workdir,model:n.model,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,maxIterations:n.max_iterations,permissionMode:n.permission_mode,harness:n.harness,goalMode:n.goal_mode,completionPromise:n.completion_promise},t);if(r.kind!=="resolved")return{content:[{type:"text",text:r.text}]};try{let o=await B.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:ur(o,r)}]}}catch(o){return{content:[{type:"text",text:`Error launching goal task: ${o instanceof Error?o.message:String(o)}`}]}}}}}X();function Zo(t,e){return t.split(`
|
|
105
|
+
`).map(n=>`${e}${n}`)}function Pa(t,e){return t.length<=e?t:`${t.slice(0,e-3).trimEnd()}...`}function gc(t,e=8,n=600){let r=t.map(i=>i.trimEnd()).filter(i=>i.trim().length>0);if(r.length===0)return;let o=r.slice(-e).join(`
|
|
106
|
+
`);return o.length<=n?o:`...${o.slice(-(n-3))}`}function hc(t,e){let n=e?.trim(),r=(t??"").split(/\r?\n/).map(o=>o.trim().replace(/^[-*]\s+/,"")).filter(o=>o.length>0).filter(o=>!(n&&o===n)).filter(o=>!/^<promise>.*<\/promise>$/.test(o));return r.length===0?[]:r.slice(-3).map(o=>Pa(o,180))}function Sc(t){let e=(t??"").split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0);return e.length===0?[]:e.slice(0,2).map(n=>Pa(n,180))}function pr(t){let e=[],n=Sc(t.verifierSummary),r=hc(t.output,t.completionPromise);if(n.length===0&&r.length===0)return;t.completionDetected===!0&&e.push("Completion was claimed, but the loop is continuing after verification.");for(let i of n)e.push(`Verifier: ${i}`);let o=Math.max(0,3-e.length);if(o>0)for(let i of r.slice(-o))e.push(`Agent: ${i}`);return["Iteration summary:",...e.map(i=>`- ${i}`)].join(`
|
|
107
|
+
`)}function Xo(t){if(t)return{phase:t.phase,awaitingInput:t.isAwaitingInput??!!t.pendingInputState,latestOutput:gc(t.getOutput(20))}}function ei(t,e,n){let r=t.loopMode??"verifier",o=[`${t.name} [${t.id}]`,` Status: ${t.status}`,...r==="ralph"?[" Loop mode: ralph",` Iteration: ${t.iteration}/${t.maxIterations}`]:[` Repair iteration: ${t.iteration}/${t.maxIterations}`],` Workdir: ${t.workdir}`];return r==="ralph"&&t.completionPromise&&o.push(` Completion promise: ${t.completionPromise}`),t.sessionId&&o.push(` Session: ${t.sessionName??"(unknown)"} [${t.sessionId}]`),e?.phase&&o.push(` Phase: ${e.phase}`),e?.awaitingInput!==void 0&&o.push(` Awaiting input: ${e.awaitingInput?"yes":"no"}`),n&&o.push(...Zo(n," ")),t.lastVerifierSummary&&(o.push(" Last verifier:"),o.push(...Zo(t.lastVerifierSummary," "))),e?.latestOutput&&(o.push(" Latest activity:"),o.push(...Zo(e.latestOutput," "))),t.waitingForUserReason&&o.push(` Waiting on user: ${t.waitingForUserReason}`),t.failureReason&&o.push(` Failure: ${t.failureReason}`),o.join(`
|
|
108
|
+
`)}var Se="Error: GoalController not initialized. The code-agent service must be running.";function cr(t,e,n){let r=n?.trim();if(r){let i=t.getTask(r);if(!i)return`Error: Goal task "${r}" not found.`;let s=i.sessionId?e(i.sessionId):void 0;return ei(i,Xo(s))}let o=t.listTasks();return o.length===0?"No goal tasks found.":o.map(i=>{let s=i.sessionId?e(i.sessionId):void 0;return ei(i,Xo(s))}).join(`
|
|
109
|
+
|
|
110
|
+
`)}function mr(t,e){return t?t.action==="already_terminal"?`Task is already ${t.task.status}.`:`Task "${t.task.name}" (${t.task.id}) stopped.`:`Error: Goal task "${e}" not found.`}function fr(t,e){switch(t.action){case"updated":return`Task "${t.task.name}" (${t.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 t.task.status!=="waiting_for_user"?`Task is already ${t.task.status}.`:`Error: Goal task "${t.task.name}" is ${t.task.status} and cannot be edited.`}}O();function ba(t){return{name:"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:m.Object({task:m.Optional(m.String({description:"Task name or ID. Omit to list all tasks."}))}),async execute(e,n){if(!B)return{content:[{type:"text",text:Se}]};let r=n&&typeof n=="object"&&typeof n.task=="string"?n.task:void 0;return{content:[{type:"text",text:cr(B,o=>v?.resolve(o),r)}]}}}}X();O();function yc(t){return!!t&&typeof t=="object"&&typeof t.task=="string"}function Aa(t){return{name:"goal_stop",description:"Stop an explicit goal task and kill its underlying agent session.",parameters:m.Object({task:m.String({description:"Goal task name or ID"})}),async execute(e,n){if(!B)return{content:[{type:"text",text:Se}]};if(!yc(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task }."}]};let r=B.stopTask(n.task);return{content:[{type:"text",text:mr(r,n.task)}]}}}}X();O();function kc(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.task=="string"&&typeof e.goal=="string"}function Ra(t){return{name:"goal_edit",description:"Edit the goal text for an active goal task without stopping or relaunching its session.",parameters:m.Object({task:m.String({description:"Goal task name or ID"}),goal:m.String({description:"Replacement goal text"})}),async execute(e,n){if(!B)return{content:[{type:"text",text:Se}]};if(!kc(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task, goal }."}]};let r=B.editTask(n.task,n.goal);return{content:[{type:"text",text:fr(r,n.task)}]}}}}O();dr();import{createHash as vc}from"crypto";var ge="code-agent";var wc=new Set(["1","true","yes","on"]);function ni(){let t=process.env.OPENCLAW_CODE_AGENT_BUTTON_DIAGNOSTICS?.trim().toLowerCase();return!!(t&&wc.has(t))}function pt(t){if(!(typeof t!="string"||t.length===0))return vc("sha256").update(t).digest("hex").slice(0,12)}function Ia(t){return typeof t.callbackData=="string"?t.callbackData:typeof t.value=="string"?t.value:void 0}function G(t){let e=(t??[]).filter(r=>Array.isArray(r)&&r.length>0),n=e.flat();return{buttonRows:e.length||void 0,buttonCount:n.length||void 0,buttonLabels:n.length>0?n.map(r=>typeof r.label=="string"?r.label:void 0):void 0,callbackByteLengths:n.length>0?n.map(r=>{let o=Ia(r);return o?Buffer.byteLength(o,"utf8"):void 0}):void 0,callbackHashes:n.length>0?n.map(r=>pt(Ia(r))):void 0,buttonStyles:n.length>0?n.map(r=>typeof r.style=="string"?r.style:void 0):void 0}}function Ee(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Ta(t){let e=Ee(t),n=Array.isArray(e?.blocks)?e.blocks:void 0;if(n)return n.map(r=>Ee(r)?.type).filter(r=>typeof r=="string"&&r.length>0)}function Ca(t){let e=Ee(t),n=Array.isArray(e?.blocks)?e.blocks:void 0;if(!n)return;let r=n.map(o=>{let i=Ee(o);return i?.type!=="buttons"||!Array.isArray(i.buttons)?[]:i.buttons}).filter(o=>o.length>0);return r.length>0?r:void 0}function ri(t){let e=Ca(t);return{presentationBlockTypes:Ta(t),...G(e)}}function oi(t){let e=Ee(t),n=e?.interactive,r=Ee(e?.channelData),o=Ee(r?.telegram),i=Array.isArray(o?.buttons)?o.buttons:void 0;return{renderedPayloadKeys:e?Object.keys(e).sort():void 0,interactiveBlockTypes:Ta(n),...xa("interactive",G(Ca(n))),...xa("telegramChannelData",G(i)),hasPresentation:!!e?.presentation,hasInteractive:!!n,hasTelegramChannelDataButtons:!!i?.some(s=>s.length>0)}}function Ma(t){let e=Ee(t);return e?{sendResultKeys:Object.keys(e).sort(),messageId:ti(e.messageId),chatId:ti(e.chatId),telegramThreadId:ti(e.messageThreadId??e.threadId),channel:typeof e.channel=="string"?e.channel:void 0}:{sendResultType:typeof t}}function ti(t){return typeof t=="string"||typeof t=="number"?t:void 0}function xa(t,e){let n={};for(let[r,o]of Object.entries(e))o!==void 0&&(n[`${t}${r.charAt(0).toUpperCase()}${r.slice(1)}`]=o);return n}function D(t,e){if(!ni())return;let n=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));`${JSON.stringify({event:t,callbackNamespace:ge,...n})}`}function Pc(t){let e=t.trim().replace(new RegExp(`^${ge}:`),"");return e||null}async function gr(t,e,n=!1){try{return(await le(t,{text:e,alreadyAcknowledged:n})).textDelivered}catch(r){let o=r instanceof Error?r.message:String(r);return`${o}`,!1}}function hr(t){if(t&&typeof t=="object"&&"content"in t&&Array.isArray(t.content)){let e=t.content[0];return typeof e?.text=="string"?e.text:"(done)"}return"(done)"}function _a(t){if(t&&typeof t=="object"&&"meta"in t){let e=t.meta;if(typeof e?.success=="boolean")return e.success}return ii(hr(t))}function ii(t){return!/^\s*(?:Error\b:?|â|â ī¸)/.test(t)}function bc(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}function Ac(t,e){if(bc(t.kind)){if(!e)return"This plan decision is stale because the session is no longer available.";if(t.planDecisionVersion!=null&&(e.actionablePlanDecisionVersion??e.planDecisionVersion)!=null&&t.planDecisionVersion!==(e.actionablePlanDecisionVersion??e.planDecisionVersion))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(t.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(t.kind==="plan-request-changes"&&e.approvalState==="changes_requested")return"Changes were already requested for this plan. Send your feedback to the agent instead."}}function Rc(t){let e="callback"in t?t.callback?.payload??t.callback?.data:void 0,n="interaction"in t?t.interaction?.payload:void 0;return e??n??""}function Gt(t){let e=t instanceof Error?t.message:String(t);return/message is not modified/i.test(e)}function Ic(t){let e=t instanceof Error?t.message:String(t);return/empty message/i.test(e)}async function le(t,e={}){let n=t.respond,{alreadyAcknowledged:r=!1,forceTelegramMarkupEdit:o=!1,text:i}=e;if(t.channel==="telegram"){if(typeof i=="string"&&typeof n.editMessage=="function")try{return await n.editMessage({text:i,buttons:[]}),typeof n.clearButtons=="function"&&await n.clearButtons(),{textDelivered:!0}}catch(a){if(Gt(a))return typeof n.clearButtons=="function"&&await n.clearButtons(),{textDelivered:!0};let d=a instanceof Error?a.message:String(a);`${d}`}if(o&&typeof n.editButtons=="function")try{return await n.editButtons({buttons:[]}),typeof n.clearButtons=="function"&&await n.clearButtons(),{textDelivered:!1}}catch(a){if(Gt(a))return typeof n.clearButtons=="function"&&await n.clearButtons(),{textDelivered:!1};let d=a instanceof Error?a.message:String(a);`${d}`}let s="callback"in t&&typeof t.callback?.messageText=="string"?t.callback.messageText:void 0;if(o&&typeof s=="string"&&typeof n.editMessage=="function")try{return await n.editMessage({text:s,buttons:[]}),typeof n.clearButtons=="function"&&await n.clearButtons(),{textDelivered:!1}}catch(a){if(Gt(a))return typeof n.clearButtons=="function"&&await n.clearButtons(),{textDelivered:!1};let d=a instanceof Error?a.message:String(a);`${d}`}return typeof n.clearButtons=="function"&&await n.clearButtons(),{textDelivered:!1}}if(typeof n.clearComponents=="function")try{return await n.clearComponents(typeof i=="string"?{text:i}:void 0),{textDelivered:typeof i=="string"}}catch(s){if(Gt(s))return{textDelivered:typeof i=="string"};if(Ic(s)){if(typeof i!="string"&&r)return{textDelivered:!1};if(typeof i!="string"&&typeof n.acknowledge=="function")return await n.acknowledge(),{textDelivered:!1};typeof i!="string"&&n.acknowledge}else{if(typeof i!="string")throw s;{let a=s instanceof Error?s.message:String(s);`${a}`}}}if(typeof i=="string"&&typeof n.editMessage=="function"){try{await n.editMessage({text:i})}catch(s){if(Gt(s))return typeof n.clearButtons=="function"&&await n.clearButtons(),{textDelivered:!0};let a=s instanceof Error?s.message:String(s);return`${a}`,typeof n.clearButtons=="function"&&await n.clearButtons(),{textDelivered:!1}}return typeof n.clearButtons=="function"&&await n.clearButtons(),{textDelivered:!0}}return typeof n.clearButtons=="function"&&await n.clearButtons(),{textDelivered:!1}}async function xc(t){let e=t.respond;if(typeof e.acknowledge!="function")return!1;try{return await e.acknowledge(),!0}catch(n){let r=n instanceof Error?n.message:String(n);return`${r}`,!1}}async function U(t,e){if(t.channel==="telegram"){await t.respond.reply({text:e});return}await t.respond.reply({text:e,ephemeral:!0})}function Ea(t="telegram"){return D("callback_handler_registered",{channel:t,namespace:ge}),{channel:t,namespace:ge,handler:async e=>{let n=await xc(e);if(!e.auth.isAuthorizedSender)return await U(e,"â Unauthorized."),{handled:!0};let r=Rc(e),o=Pc(r);if(D("callback_received",{channel:e.channel,namespace:ge,payloadByteLength:Buffer.byteLength(r,"utf8"),tokenHash:pt(o),isAuthorizedSender:e.auth.isAuthorizedSender}),!o)return await U(e,"â ī¸ Unrecognized callback payload."),{handled:!0};if(!v)return await U(e,"â ī¸ Code agent service not running."),{handled:!0};let i=v.getActionToken(o);if(D("callback_token_lookup_completed",{channel:e.channel,namespace:ge,tokenHash:pt(o),tokenFound:!!i,actionKind:i?.kind,sessionId:i?.sessionId,planDecisionVersion:i?.planDecisionVersion}),!i)return await le(e,{alreadyAcknowledged:n}),e.channel!=="telegram"&&await U(e,"â ī¸ This action is stale or has already been used."),{handled:!0};let s=i.sessionId,a=v.resolve?.(s)??v.getPersistedSession?.(s),d=a?.name??s,l=Ac(i,a);if(D("callback_plan_validation_completed",{channel:e.channel,namespace:ge,tokenHash:pt(o),actionKind:i.kind,sessionId:s,sessionName:d,planDecisionVersion:i.planDecisionVersion,valid:!l}),l)return await le(e,{alreadyAcknowledged:n}),await U(e,`â ī¸ ${l}`),{handled:!0};let u=v.consumeActionToken(o);if(D("callback_token_consume_completed",{channel:e.channel,namespace:ge,tokenHash:pt(o),consumed:!!u,actionKind:u?.kind,sessionId:u?.sessionId,planDecisionVersion:u?.planDecisionVersion}),!u)return await le(e,{alreadyAcknowledged:n,forceTelegramMarkupEdit:i.kind==="plan-offer-start"||i.kind==="plan-offer-dismiss"}),e.channel!=="telegram"&&await U(e,"â ī¸ This action is stale or has already been used."),{handled:!0};switch(u.kind){case"worktree-merge":{let p=await er().execute("callback",{session:s}),c=hr(p);_a(p)&&await gr(e,`â
Merge selected for [${d}]`,n),await U(e,c);break}case"worktree-decide-later":{let p=v.snoozeWorktreeDecision(s,{notifyUser:!1});if(ii(p)){let f=`âī¸ Snoozed 24h for [${d}]`;await gr(e,f,n)||await U(e,f)}else await U(e,p);break}case"worktree-dismiss":{let p=await v.dismissWorktree(s),c=ii(p);c&&await gr(e,`đī¸ Discarded for [${d}]`,n),await U(e,c?"â
Discarded":p);break}case"worktree-create-pr":case"worktree-update-pr":{let p=await Vt().execute("callback",{session:s}),c=hr(p);_a(p)&&await gr(e,i.kind==="worktree-update-pr"?`đŦ PR update selected for [${d}]`:`đŦ PR selected for [${d}]`,n),await U(e,c);break}case"worktree-view-pr":{await le(e,{alreadyAcknowledged:n});let p=v.getPersistedSession?.(s),c=i.targetUrl??p?.worktreePrUrl;await U(e,c?`PR: ${c}`:"â ī¸ PR URL is no longer available.");break}case"plan-approve":{await le(e,{alreadyAcknowledged:n}),v.clearPlanDecisionTokens(s);let p=await he(v,{session:s,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});p.isError&&await U(e,`â ī¸ ${p.text}`);break}case"plan-reject":{await le(e,{alreadyAcknowledged:n});let p=Go(v,s);await U(e,`â ${p.text}`);break}case"plan-request-changes":{await le(e,{alreadyAcknowledged:n});let p=Ho(v,s);await U(e,`âī¸ ${p.text}`);break}case"plan-offer-start":{if(!u.launchPrompt||!u.launchWorkdir){await le(e,{alreadyAcknowledged:n,forceTelegramMarkupEdit:!0}),await U(e,"â ī¸ This action is missing the plan launch context.");break}let p;try{p=v.launchPlanOffer({route:u.route,prompt:u.launchPrompt,workdir:u.launchWorkdir,name:u.launchName,worktreeStrategy:u.launchWorktreeStrategy})}catch(c){let f=c instanceof Error?c.message:String(c);await U(e,`â ī¸ Failed to start planning session: ${f}`);break}await le(e,{alreadyAcknowledged:n,forceTelegramMarkupEdit:!0}),await U(e,`âļī¸ Planning session started: ${p.name} [${p.id}]`);break}case"plan-offer-dismiss":{await le(e,{alreadyAcknowledged:n,forceTelegramMarkupEdit:!0}),await U(e,"â
Dismissed.");break}case"session-restart":case"session-resume":{await le(e,{alreadyAcknowledged:n});let p=await he(v,{session:s,message:"Continue where you left off.",userInitiated:!0});await U(e,p.isError?`â ī¸ ${p.text}`:`âļī¸ ${p.text}`);break}case"view-output":{await le(e,{alreadyAcknowledged:n});let p=await Hn().execute("callback",{session:s,lines:50});await U(e,hr(p));break}case"question-answer":{if(await le(e,{alreadyAcknowledged:n}),i.optionIndex==null){await U(e,"â ī¸ Invalid question-answer action.");break}await v.resolvePendingInputOption(s,i.optionIndex),await U(e,"â
Answer submitted.");break}default:{await le(e,{alreadyAcknowledged:n}),await U(e,"â ī¸ Unknown callback action.");break}}return{handled:!0}}}}O();te();function ct(t){return $a(t).map(e=>e.value)}function $a(t){return Array.from(t.matchAll(/"[^"]*"|'[^']*'|\S+/g),e=>{let n=e[0],r=e.index??0;return{value:Tc(n),raw:n,start:r,end:r+n.length}})}function Ht(t){let[e]=$a(t);if(e)return{value:e.value,rest:t.slice(e.end).trimStart()}}function Tc(t){return t.length>1&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function Cc(t){return t instanceof Error?t.message:String(t)}function Mc(t){let e=ct(t),n,r=e;return e[0]==="--name"&&e[1]&&(n=e[1],r=e.slice(2)),{name:n,prompt:r.join(" ").trim()}}function Da(t){t.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(!n)return{text:"Usage: /agent [--name <name>] <prompt>"};let{name:r,prompt:o}=Mc(n);if(!o)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let i=Sn({prompt:o,name:r},e,v);if(i.kind!=="resolved")return{text:i.text};let s=v.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:An(e)});return{text:v.formatLaunchResult({prompt:o,workdir:i.workdir,harness:i.harness,permissionMode:i.permissionMode??E.permissionMode,planApproval:i.planApproval},s)}}catch(i){let s=Cc(i),a=s.includes("Max sessions")?"":`
|
|
111
|
+
|
|
112
|
+
Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${s}${a}`}}}})}O();function Oa(t){t.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(e.args??"").split(/\s+/).includes("--full");return{text:Vn(v,"all",void 0,{full:n})}}})}O();function Na(t){t.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=e.args?.trim();return n?{text:Gn(v,n,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}O();function Wa(t){t.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(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(!n)return{text:`Usage: /agent_respond <id-or-name> <message>
|
|
113
|
+
/agent_respond --interrupt <id-or-name> <message>`};let r=!1,o=n,i=Ht(o);i?.value==="--interrupt"&&(r=!0,o=i.rest);let s=Ht(o);if(!s)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let a=s.value,d=s.rest;return d.trim()?{text:(await he(v,{session:a,message:d,interrupt:r,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}O();function La(t){t.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let e=v.getMetrics(),n=v.list("running").length;return{text:kn(e,n)}}})}O();var _c=50;function Ba(t){t.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(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(!n)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let r=ct(n),o="",i=!1,s=_c;for(let d=0;d<r.length;d++)if(r[d]==="--full")i=!0;else if(r[d]==="--lines"&&d+1<r.length){let l=parseInt(r[d+1],10);!isNaN(l)&&l>0&&(s=l),d++}else o||(o=r[d]);return o?{text:Un(v,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}O();var Fa="Usage: /goal [--name <name>] [--workdir <dir>] [--model <model>] [--harness <name>] [--mode <ralph|verifier>] [--completion-promise <text>] [--max-iterations N] [--verify <cmd> ...] <goal>";function qa(t){t.registerCommand({name:"goal",description:"Launch an explicit goal task (Ralph-style completion loop or verifier-driven loop)",acceptsArgs:!0,requireAuth:!0,handler:async e=>{if(!B)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(!n)return{text:Fa};let r=ct(n),o,i,s,a,d="bypassPermissions",l,u,p,c=[],f=[];for(let y=0;y<r.length;y++){let k=r[y];if(k==="--name"&&y+1<r.length)o=r[++y];else if(k==="--workdir"&&y+1<r.length)i=r[++y];else if(k==="--model"&&y+1<r.length)s=r[++y];else if(k==="--max-iterations"&&y+1<r.length){let b=parseInt(r[++y],10);!Number.isNaN(b)&&b>0&&(a=b)}else if(k==="--permission-mode"&&y+1<r.length){let b=r[++y];if(b==="default"||b==="plan"||b==="bypassPermissions")d=b;else return{text:`Error: Invalid permission mode "${b}".`}}else if(k==="--harness"&&y+1<r.length)l=r[++y];else if(k==="--mode"&&y+1<r.length){let b=r[++y];if(b==="ralph"||b==="verifier")u=b;else return{text:`Error: Invalid goal mode "${b}". Use ralph or verifier.`}}else if(k==="--completion-promise"&&y+1<r.length)p=r[++y];else if(k==="--verify"&&y+1<r.length){let b=r[++y].trim();if(!b)return{text:"Error: --verify commands must not be empty."};c.push(b)}else f.push(k)}let g=f.join(" ").trim();if(!g)return{text:Fa};let h=lr({goal:g,verifierCommands:c,name:o,workdir:i,model:s,maxIterations:a,permissionMode:d,harness:l,goalMode:u,completionPromise:p},e);if(h.kind!=="resolved")return{text:h.text};try{let y=await B.launchTask({goal:h.goal,name:h.name,workdir:h.workdir,model:h.model,reasoningEffort:h.reasoningEffort,fastMode:h.fastMode,maxIterations:h.maxIterations,permissionMode:h.permissionMode,harness:h.harness,loopMode:h.loopMode,completionPromise:h.completionPromise,originChannel:h.originChannel,originThreadId:h.originThreadId,originAgentId:h.originAgentId,originSessionKey:h.originSessionKey,route:h.route,verifierCommands:h.verifierCommands});return{text:ur(y,h)}}catch(y){return{text:`Error launching goal task: ${y instanceof Error?y.message:String(y)}`}}}})}O();function Ka(t){t.registerCommand({name:"goal_status",description:"Show one goal task or list all explicit goal tasks. Usage: /goal_status [<task-id-or-name>]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!B)return{text:Se};let n=(e.args??"").trim();return{text:cr(B,r=>v?.resolve(r),n)}}})}O();function Ua(t){t.registerCommand({name:"goal_stop",description:"Stop a goal task. Usage: /goal_stop <task-id-or-name>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!B)return{text:Se};let n=(e.args??"").trim();if(!n)return{text:"Usage: /goal_stop <task-id-or-name>"};let r=B.stopTask(n);return{text:mr(r,n)}}})}O();var Va="Usage: /goal_edit <task-id-or-name> <replacement-goal>";function Ga(t){t.registerCommand({name:"goal_edit",description:"Edit a running goal task. Usage: /goal_edit <task-id-or-name> <replacement-goal>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!B)return{text:Se};let n=(e.args??"").trim();if(!n)return{text:Va};let r=Ht(n),o=r?.value.trim(),i=r?.rest.trim();if(!o||!i)return{text:Va};let s=B.editTask(o,i);return{text:fr(s,o)}}})}import{execFile as Vc}from"child_process";import{createHash as td}from"crypto";import{existsSync as Ec,mkdirSync as $c,readFileSync as Dc,renameSync as Oc,writeFileSync as Nc}from"fs";import{homedir as Wc}from"os";import{dirname as Lc,join as Ha}from"path";function Bc(t){let e=t.OPENCLAW_HOME?.trim();return e||Ha(Wc(),".openclaw")}function Fc(t){let e=t.OPENCLAW_CODE_AGENT_GOAL_TASKS_PATH?.trim();return e||Ha(Bc(t),"code-agent-goal-tasks.json")}function qc(t){return t instanceof Error?t.message:String(t)}function Kc(t){if(!t||typeof t!="object")return;let e=t;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 Uc(t){if(!t||typeof t!="object")return;let e=t;if(typeof e.id!="string"||typeof e.name!="string"||typeof e.goal!="string"||typeof e.workdir!="string"||typeof e.status!="string")return;let n=e.status,r=n==="running"||n==="waiting_for_session"?"waiting_for_session":n;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:Kc(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}}var Sr=class{path;tasks=new Map;constructor(e=process.env){this.path=Fc(e),this.load()}load(){try{if(!Ec(this.path))return;let e=Dc(this.path,"utf8"),n=JSON.parse(e);if(!Array.isArray(n))return;for(let r of n){let o=Uc(r);o&&this.tasks.set(o.id,o)}this.save()}catch{}}save(){try{$c(Lc(this.path),{recursive:!0});let e=`${this.path}.tmp`;Nc(e,JSON.stringify([...this.tasks.values()],null,2),"utf8"),Oc(e,this.path)}catch(e){`${this.path}${qc(e)}`}}upsert(e){this.tasks.set(e.id,e),this.save()}get(e){let n=this.tasks.get(e);return n||[...this.tasks.values()].find(r=>r.name===e)}list(){return[...this.tasks.values()].sort((e,n)=>n.createdAt-e.createdAt)}};ke();var Gc=8,nd=600*1e3,Hc=4e3,si=1200,jc="DONE",zc=["BASH_ENV","ENV"];function Qc(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"goal-task"}function mt(t,e){return t.length<=e?t:`${t.slice(0,e-3)}...`}function $e(t,e=20){let n=t.split(/\r?\n/).map(r=>r.trimEnd()).filter(r=>r.trim().length>0);return n.length<=e?n.join(`
|
|
114
|
+
`):n.slice(-e).join(`
|
|
115
|
+
`)}function Jc(t){let e=(t??"").split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).filter(n=>!/^Iteration summary:$/i.test(n)).map(n=>n.replace(/^[-*]\s+/,""));return e.length>0?e.join(`
|
|
116
|
+
`):void 0}function ja(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function za(t){let e=t?.trim();return e&&e.length>0?e:jc}function Yc(t){return t.route??kt(t.originChannel,t.originThreadId,t.originSessionKey)}function ai(t){return t.map((e,n)=>({label:e.label.trim()||`check-${n+1}`,command:e.command.trim(),timeoutMs:e.timeoutMs??nd})).filter(e=>e.command.length>0)}function Zc(t){return t.loopMode==="verifier"}function Xc(t){return ai(t.verifierCommands).length>0}function Qa(t){return Zc(t)&&!Xc(t)}function yr(){return"Verifier-mode goal tasks require at least one verifier command."}function Ja(t){let e=t.steps.filter(n=>!n.ok).map(n=>`${n.label}:${n.exitCode}:${$e(n.output,12)}`).join(`
|
|
117
|
+
`);return td("sha1").update(e).digest("hex")}function em(t){return td("sha1").update($e(t,24)).digest("hex")}function Ya(t){let e=t.toLowerCase().replace(/\s+/g," ").trim();if(!e)return;if(/\b(can i|may i|should i|do you want me to|would you like me to)\b/.test(e)&&/\b(read|write|edit|modify|change|inspect|search|run|execute|install|delete|move|rename|open)\b/.test(e))return"Yes, proceed.";if(/\b(should i continue|shall i continue|want me to continue|should i proceed|shall i proceed|can i proceed|go ahead)\b/.test(e))return"Yes, continue."}function tm(t){if(t.loopMode==="ralph")return["You are working inside a Ralph Wiggum-style autonomous loop.","","Goal:",t.goal,"","Loop rules:","- Keep making concrete progress toward the goal in this repository.","- An external controller will continue looping until you emit the completion promise or the iteration budget is exhausted.",`- When the goal is truly complete, output this exact marker on its own line: <promise>${t.completionPromise}</promise>`,"- Do not output that completion marker early, approximately, or with altered spelling.","- If you are not done yet, do not emit the completion marker.","- Do not ask to stop or wait for confirmation unless blocked by a real product, architecture, credential, or approval decision.","- Re-run useful local checks before ending each turn.",t.verifierCommands.length>0?"- External verifier commands will also be run after you claim completion.":"- There may not be external verifiers, so your completion promise is the success gate."].join(`
|
|
118
|
+
`);let e=t.verifierCommands.map(n=>`- ${n.label}: ${n.command}`).join(`
|
|
117
119
|
`);return["You are working on an autonomous goal-driven task.","","Goal:",t.goal,"","Working rules:","- Make concrete progress toward the goal in this repository.","- An external controller will run these verifier commands after your turn:",e,"- If any verifier fails, you will receive the exact failures and must continue fixing the remaining gaps.","- Do not stop early just because you think the task is probably done.","- Do not ask for confirmation unless you are blocked by a real product, architecture, or credential decision.","- Before ending a turn, run any local checks you think are useful."].join(`
|
|
118
|
-
`)}function
|
|
120
|
+
`)}function Za(t){return t.loopMode==="ralph"?["The OpenClaw gateway restarted while this Ralph-style goal task was running.","Resume from the prior session context and continue immediately.","","Goal:",t.goal,"","Instructions:","- Continue from the current repo state and prior session context without restarting from scratch.",`- Only emit <promise>${t.completionPromise}</promise> when the goal is actually complete.`,"- The external controller will keep looping until that marker appears or the iteration budget is exhausted.","- Do not ask for confirmation just because the gateway restarted."].join(`
|
|
119
121
|
`):["The OpenClaw gateway restarted while this autonomous goal task was running.","Resume from the prior session context and continue toward the same goal immediately.","","Goal:",t.goal,"","Instructions:","- Re-orient yourself from the existing repo state and prior session context.","- Continue the task without restarting from scratch unless the prior approach is clearly invalid.","- The external controller will continue running verifier commands after your turns.","- Do not ask for confirmation just because the gateway restarted."].join(`
|
|
120
|
-
`)}function
|
|
122
|
+
`)}function nm(t,e){let n=e.steps.filter(o=>!o.ok).map(o=>[`- ${o.label} failed (exit ${o.exitCode})`,$e(o.output,18)].join(`
|
|
121
123
|
`)).join(`
|
|
122
124
|
|
|
123
|
-
`);return["The external verifier did not pass.",t.repeatedFailureCount>=2?"The same verifier fingerprint has repeated. Use a different debugging strategy than your previous attempt.":"Fix only the remaining issues from the verifier output below.","","Goal:",t.goal,"","Verifier failures:",
|
|
124
|
-
`)}function
|
|
125
|
-
`)}function
|
|
125
|
+
`);return["The external verifier did not pass.",t.repeatedFailureCount>=2?"The same verifier fingerprint has repeated. Use a different debugging strategy than your previous attempt.":"Fix only the remaining issues from the verifier output below.","","Goal:",t.goal,"","Verifier failures:",n,"","Instructions:","- Continue from the current code state and prior session context.","- Make the minimum necessary changes to satisfy the remaining verifier failures.","- Re-run relevant checks yourself before ending the turn.","- Do not ask for confirmation unless you are truly blocked on a human decision."].join(`
|
|
126
|
+
`)}function rm(t,e){let n=$e(e,18)||"(no meaningful output)",r=t.repeatedFailureCount>=2?"The loop has repeated without converging. Use a different strategy than the previous attempt.":"Continue from the current repo state and prior session context.";return["Continue the same Ralph-style goal task.","","Goal:",t.goal,"","Status:",`- The last turn ended without the completion promise <promise>${t.completionPromise}</promise>.`,`- Current iteration: ${t.iteration}/${t.maxIterations}.`,`- ${r}`,"","Latest output / blockers:",n,"","Instructions:","- Keep working until the goal is actually complete.",`- Only emit <promise>${t.completionPromise}</promise> when all requested work is done.`,"- If you are not done, do not emit the completion promise.",t.verifierCommands.length>0?"- If you believe you are done, make sure the expected verifiers are likely to pass before emitting the completion promise.":"- There may not be external verifiers, so your completion promise is the success signal."].join(`
|
|
127
|
+
`)}function om(t,e){let n=e.steps.filter(r=>!r.ok).map(r=>[`- ${r.label} failed (exit ${r.exitCode})`,$e(r.output,18)].join(`
|
|
126
128
|
`)).join(`
|
|
127
129
|
|
|
128
|
-
`);return["You emitted the completion promise, but the external verifiers did not pass.","","Goal:",t.goal,"","Verifier failures:",
|
|
129
|
-
`)}function
|
|
130
|
-
`)}function
|
|
131
|
-
${
|
|
130
|
+
`);return["You emitted the completion promise, but the external verifiers did not pass.","","Goal:",t.goal,"","Verifier failures:",n,"","Instructions:","- Continue from the current repo state and fix only the remaining gaps.",`- Do not emit <promise>${t.completionPromise}</promise> again until the goal is fully complete and the failing checks are addressed.`,"- Re-run relevant checks yourself before ending the turn."].join(`
|
|
131
|
+
`)}function im(t,e){let n=e.trim();if(!n)return!1;let r=new RegExp(`(^|\\n)\\s*${ja(n)}\\s*(\\n|$)`,"i"),o=new RegExp(`<promise>\\s*${ja(n)}\\s*<\\/promise>`,"i");return r.test(t)||o.test(t)}function Xa(t){return t.steps.map(e=>`${e.ok?"PASS":"FAIL"} ${e.label} (exit ${e.exitCode}, ${Math.round(e.durationMs)}ms)`).join(`
|
|
132
|
+
`)}function Ge(t){return t instanceof Error?t.message:String(t)}function ed(t){return t==="succeeded"||t==="failed"||t==="stopped"}function sm(t){return mt(t.error?.trim()||"Underlying session failed.",si)}function am(t=process.env){let e={...t};for(let n of zc)delete e[n];return e}function dm(t,e){return new Promise(n=>{let r=Date.now();Vc("bash",["-lc",e.command],{cwd:t,timeout:e.timeoutMs??nd,maxBuffer:1024*1024,env:am()},(o,i,s)=>{let a=Date.now()-r,d=typeof o?.code=="number"?o.code:o?1:0,l=`${i??""}${s?`
|
|
133
|
+
${s}`:""}`.trim();n({label:e.label,command:e.command,ok:!o,exitCode:d,durationMs:a,output:mt(l||"(no output)",Hc)})})})}var kr=class{store;sessionManager;restorePromise=null;inFlight=new Set;observerDisposers=new Map;scheduledEvaluations=new Map;dirtyEvaluations=new Set;dirtyEvaluationSessionIds=new Map;started=!1;constructor(e){this.sessionManager=e,this.store=new Sr}start(){this.started||(this.started=!0,!this.restorePromise&&(this.restorePromise=this.restoreRecoverableTasks().catch(e=>{`${Ge(e)}`}).finally(()=>{this.restorePromise=null})))}stop(){this.started=!1,this.clearScheduledEvaluations(),this.detachSessionObservers(),this.captureRecoverableTasks(),this.store.save()}listTasks(){return this.store.list()}getTask(e){return this.store.get(e)}async launchTask(e){let n=e.loopMode??"verifier",r=ai(e.verifierCommands);if(n==="verifier"&&r.length===0)throw new Error(yr());let i={id:Rn(8),name:Qc(e.name??e.goal),goal:e.goal.trim(),workdir:e.workdir,status:"waiting_for_session",createdAt:Date.now(),updatedAt:Date.now(),iteration:0,maxIterations:e.maxIterations??Gc,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,systemPrompt:e.systemPrompt,allowedTools:e.allowedTools,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:e.route,harness:e.harness,permissionMode:e.permissionMode??"bypassPermissions",loopMode:n,completionPromise:za(e.completionPromise),verifierCommands:r,repeatedFailureCount:0},s=await this.spawnTaskSession(i,tm(i));return this.attachSessionObservers(i,s),i.sessionId=s.id,i.sessionName=s.name,i.harnessSessionId=s.harnessSessionId,i.status="running",i.updatedAt=Date.now(),this.store.upsert(i),this.scheduleTaskEvaluation(i.id,"launch",s.id),this.notify(i,`đ¯ [${i.name}] Goal task started
|
|
132
134
|
|
|
133
135
|
Goal:
|
|
134
|
-
${
|
|
136
|
+
${mt(i.goal,500)}`,"goal-task-started"),i}stopTask(e){let n=this.store.get(e);if(n)return ed(n.status)?{task:n,action:"already_terminal"}:(n.sessionId&&this.sessionManager.kill(n.sessionId,"user"),this.markTaskStopped(n,"Stopped by user."),{task:n,action:"stopped"})}editTask(e,n){let r=n.trim();if(!r)return{action:"invalid_goal"};let o=this.store.get(e);if(!o)return{action:"not_found"};if(ed(o.status)||o.status==="waiting_for_user")return{action:"not_editable",task:o};let i=o.goal;return o.goal=r,o.updatedAt=Date.now(),this.store.upsert(o),this.notify(o,`âī¸ [${o.name}] Goal task edited
|
|
135
137
|
|
|
136
138
|
Goal:
|
|
137
|
-
${
|
|
138
|
-
`));return this.attachSessionObservers(e,i),i}let o=await this.spawnManagedTaskSession(e,r
|
|
139
|
+
${mt(o.goal,500)}`,"goal-task-edited"),{action:"updated",task:o,previousGoal:i}}async spawnTaskSession(e,n){return this.spawnManagedTaskSession(e,n)}async spawnManagedTaskSession(e,n,r){let o=r?this.sessionManager.resolveHarnessSessionId(r)??r:void 0,i=r?this.sessionManager.resolve(r):void 0,s=o?this.sessionManager.getPersistedSession(o)??this.sessionManager.getPersistedSession(r??o):void 0,{resumeSessionId:a}=Ze({requestedResumeSessionId:o,activeSession:i?{harnessSessionId:i.harnessSessionId}:void 0,persistedSession:s?{harness:s.harness,backendRef:s.backendRef}:void 0}),d={prompt:n,name:e.name,workdir:e.workdir,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,systemPrompt:e.systemPrompt,allowedTools:e.allowedTools,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:Yc(e),permissionMode:e.permissionMode,multiTurn:!0,goalTaskId:e.id,harness:e.harness,resumeSessionId:a,resumeWorktreeFrom:o,worktreeStrategy:"off"};return this.sessionManager.spawnAndAwaitRunning(d,{notifyLaunch:!1})}async resumeTaskSession(e,n,r){if(!r.harnessSessionId){let i=await this.spawnTaskSession(e,["The previous session ended without a resumable harness session id.","Continue working on the same goal.","",n].join(`
|
|
140
|
+
`));return this.attachSessionObservers(e,i),i}let o=await this.spawnManagedTaskSession(e,n,r.harnessSessionId);return this.attachSessionObservers(e,o),o}resolveResumeSessionId(e){if(e.harnessSessionId)return e.harnessSessionId;if(e.sessionId){let r=this.sessionManager.resolveHarnessSessionId(e.sessionId);if(r)return r}let n=this.sessionManager.resolveHarnessSessionId(e.name);if(n)return n}captureRecoverableTasks(){for(let e of this.store.list()){if(e.status!=="running"&&e.status!=="waiting_for_session")continue;let n=e.sessionId?this.sessionManager.resolve(e.sessionId):void 0;n&&(e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId??e.harnessSessionId,e.route=n.route??e.route,e.updatedAt=Date.now(),e.status="waiting_for_session",this.store.upsert(e))}}async restoreRecoverableTasks(){for(let e of this.store.list()){if(!this.started)break;if(e.status==="waiting_for_user"){this.markTaskFailed(e,"Goal task was waiting for user input and cannot continue autonomously");continue}if(e.status!=="waiting_for_session"&&e.status!=="running")continue;if(Qa(e)){this.markTaskFailed(e,yr());continue}if(e.sessionId){let r=this.sessionManager.resolve(e.sessionId);if(r&&(r.status==="starting"||r.status==="running"))continue}let n=this.resolveResumeSessionId(e);if(!n){this.markTaskFailed(e,"Goal task could not be resumed after gateway restart because no resumable session id was available.");continue}try{let r=await this.spawnManagedTaskSession(e,Za(e),n);if(!this.started){e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId??n,e.route=r.route??e.route,e.status="waiting_for_session",e.updatedAt=Date.now(),this.store.upsert(e),this.sessionManager.kill(r.id,"shutdown");break}this.attachSessionObservers(e,r),e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId??n,e.route=r.route??e.route,e.status="running",e.updatedAt=Date.now(),this.store.upsert(e),this.notifyIterationStatus(e,`đ [${e.name}] Goal task resumed after gateway restart`,r),this.scheduleTaskEvaluation(e.id,"restore",r.id)}catch(r){this.markTaskFailed(e,`Failed to resume the goal task after gateway restart: ${Ge(r)}`)}}}async runVerifiers(e){let n=ai(e.verifierCommands);if(n.length===0){let s={status:"fail",steps:[{label:"verifier-config",command:"(none configured)",ok:!1,exitCode:1,durationMs:0,output:yr()}],summary:"",fingerprint:""};return s.fingerprint=Ja(s),s.summary=Xa(s),s}let r=[];for(let s of n)r.push(await dm(e.workdir,s));let i={status:r.every(s=>s.ok)?"pass":"fail",steps:r,summary:"",fingerprint:""};return i.fingerprint=Ja(i),i.summary=Xa(i),i}notify(e,n,r){this.sessionManager.emitGoalTaskUpdate(e,n,r)}notifyIterationStatus(e,n,r,o){let i=e.loopMode==="ralph"?"iteration":"repair iteration",s=/\b(?:repair\s+)?iteration\s+\d+\/\d+\b/i.test(n)?n:`${n} ${i} ${e.iteration}/${e.maxIterations}`,a=Jc(o),d=a?`${s}
|
|
139
141
|
|
|
140
|
-
${
|
|
142
|
+
${a}`:s;this.notify(e,d,"goal-task-progress")}setTaskRunningWithSession(e,n){e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId,e.route=n.route??e.route,e.status="running",e.waitingForUserReason=void 0,e.updatedAt=Date.now(),this.store.upsert(e)}attachSessionObservers(e,n){if(this.observerDisposers.has(n.id))return;let r=(i,s)=>{(s==="completed"||s==="failed"||s==="killed")&&(this.removeSessionObserver(n.id),this.scheduleTaskEvaluation(e.id,`status:${s}`,n.id))},o=()=>{let i=this.store.get(e.id);i&&(i.sessionId=n.id,i.sessionName=n.name,i.harnessSessionId=n.harnessSessionId,i.route=n.route??i.route,i.updatedAt=Date.now(),i.status==="waiting_for_session"&&(i.status="running"),this.store.upsert(i),this.notifyIterationStatus(i,`đ [${i.name}] Coding turn complete`,n),this.scheduleTaskEvaluation(e.id,"turnEnd",n.id))};n.on("statusChange",r),n.on("turnEnd",o),this.observerDisposers.set(n.id,()=>{n.off?.("statusChange",r),n.off?.("turnEnd",o),n.removeListener?.("statusChange",r),n.removeListener?.("turnEnd",o)})}scheduleTaskEvaluation(e,n,r){if(!this.started)return;let o=this.scheduledEvaluations.get(e);if(o){!o.sessionId&&r&&(o.sessionId=r);return}let i={timer:setTimeout(()=>{this.scheduledEvaluations.delete(e),this.evaluateTask(e,n,i.sessionId).catch(s=>{`${n}${Ge(s)}`})},0),sessionId:r};i.timer.unref?.(),this.scheduledEvaluations.set(e,i)}clearScheduledEvaluations(){for(let e of this.scheduledEvaluations.values())clearTimeout(e.timer);this.scheduledEvaluations.clear(),this.dirtyEvaluations.clear(),this.dirtyEvaluationSessionIds.clear()}detachSessionObservers(){for(let e of[...this.observerDisposers.keys()])this.removeSessionObserver(e)}removeSessionObserver(e){let n=this.observerDisposers.get(e);n&&(this.observerDisposers.delete(e),n())}markTaskFailed(e,n){e.status="failed",e.failureReason=mt(n,si),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`â [${e.name}] Goal task failed
|
|
141
143
|
|
|
142
|
-
${e.failureReason}`,"goal-task-failed")}markTaskFailedWaitingForUser(e,
|
|
144
|
+
${e.failureReason}`,"goal-task-failed")}markTaskFailedWaitingForUser(e,n){this.markTaskFailed(e,`Goal task was waiting for user input and cannot continue autonomously: ${n}`)}markTaskSucceeded(e,n){e.status="succeeded",e.lastVerifierSummary=n,e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`â
[${e.name}] Goal task succeeded
|
|
143
145
|
|
|
144
|
-
${
|
|
146
|
+
${n}`,"goal-task-succeeded")}markTaskStopped(e,n){e.status="stopped",e.failureReason=mt(n,si),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`â [${e.name}] Goal task stopped
|
|
145
147
|
|
|
146
|
-
${e.failureReason}`,"goal-task-stopped")}async handleRunningSession(e,
|
|
147
|
-
`),o=
|
|
148
|
-
`);if(
|
|
148
|
+
${e.failureReason}`,"goal-task-stopped")}async handleRunningSession(e,n){if(n.pendingPlanApproval){let s=await he(this.sessionManager,{session:n.id,message:"Approved. Implement the plan.",approve:!0,userInitiated:!1});s.isError&&this.markTaskFailed(e,s.text);return}if(!n.pendingInputState){this.setTaskRunningWithSession(e,n);return}let r=n.getOutput(30).join(`
|
|
149
|
+
`),o=Ya(r);if(!o){this.markTaskFailedWaitingForUser(e,$e(r,24)||"The session is waiting for user input.");return}let i=await he(this.sessionManager,{session:n.id,message:o,userInitiated:!1});if(i.isError||i.text.includes("Auto-respond limit reached")){this.markTaskFailedWaitingForUser(e,i.text);return}e.status="running",e.waitingForUserReason=void 0,e.updatedAt=Date.now(),this.store.upsert(e)}async resumeAfterIdleTimeout(e,n,r){try{let o=await this.resumeTaskSession(e,r,n);this.setTaskRunningWithSession(e,o),this.notifyIterationStatus(e,`đ [${e.name}] Goal task resumed after idle timeout`,o),this.scheduleTaskEvaluation(e.id,"idle-timeout-resume",o.id)}catch(o){this.markTaskFailed(e,`Failed to resume the goal task after idle timeout: ${Ge(o)}`)}}async handleTerminalSession(e,n){if(n.status==="failed"){this.markTaskFailed(e,sm(n));return}if(n.status==="killed"&&n.killReason==="user"){this.markTaskStopped(e,"Stopped by user.");return}if(n.status==="killed"&&n.killReason==="idle-timeout"){let s=n.getOutput(60).join(`
|
|
150
|
+
`);if(n.pendingPlanApproval){let a=await he(this.sessionManager,{session:n.id,message:"Approved. Implement the plan.",approve:!0,userInitiated:!1});if(a.isError){this.markTaskFailed(e,a.text);return}let d=this.sessionManager.resolve(n.id);if(!d){this.markTaskFailed(e,"Failed to resolve the resumed goal task session after idle timeout plan approval.");return}this.attachSessionObservers(e,d),this.setTaskRunningWithSession(e,d),this.notifyIterationStatus(e,`đ [${e.name}] Goal task resumed after idle timeout`,d),this.scheduleTaskEvaluation(e.id,"idle-timeout-plan-resume",d.id);return}if(n.pendingInputState){let a=Ya(s);if(!a){this.markTaskFailed(e,`Goal task was waiting for user input and cannot continue autonomously: ${$e(s,24)||"The goal task hit idle timeout while waiting for user input."}`);return}await this.resumeAfterIdleTimeout(e,n,["The previous session hit idle timeout while waiting for a response.",`Use this response and continue the goal: ${a}`].join(`
|
|
149
151
|
|
|
150
|
-
`));return}await this.resumeAfterIdleTimeout(e,
|
|
151
|
-
`),
|
|
152
|
+
`));return}await this.resumeAfterIdleTimeout(e,n,Za(e));return}if(n.status==="killed"&&n.killReason!=="done"){this.markTaskFailed(e,`Underlying session was killed (${n.killReason}).`);return}if(e.loopMode==="ralph"){let s=n.getOutput(200).join(`
|
|
153
|
+
`),a=za(e.completionPromise);if(im(s,a)){if(e.verifierCommands.length===0){this.markTaskSucceeded(e,`Completion promise "${a}" detected in agent output.`);return}let c=await this.runVerifiers(e);if(e.lastVerifierSummary=c.summary,e.updatedAt=Date.now(),c.status==="pass"){this.markTaskSucceeded(e,[`Completion promise "${a}" detected.`,c.summary].join(`
|
|
152
154
|
`));return}if(e.lastVerifierFingerprint===c.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=c.fingerprint,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Goal task emitted completion promise but verifiers still failed before hitting the iteration budget (${e.maxIterations}).`,c.summary].join(`
|
|
153
|
-
`));return}e.iteration+=1;let
|
|
154
|
-
`));return}e.iteration+=1;let
|
|
155
|
-
`));return}e.iteration+=1;let o=
|
|
156
|
-
`);return(t??"")+o}function rT(t,e){let r=t.resumeWorktreeFrom??t.resumeSessionId;if(!r)return{};let n=e(r);if(!n)return{};let o=!!n.harness||!!n.backendRef,i=(()=>{if(n.workdir&&n.workdir!==n.worktreePath)return n.workdir;if(n.worktreePath){let u=gs(n.worktreePath);return n.workdir&&u&&Qs(n.workdir,u)?n.workdir:u??n.workdir}return n.workdir})();if(t.worktreeStrategy||(n.worktreeLifecycle?.state==="pr_open"||n.worktreePrUrl?t.worktreeStrategy="auto-pr":n.worktreeStrategy&&(t.worktreeStrategy=n.worktreeStrategy)),!t.planApproval&&n.planApproval&&(t.planApproval=n.planApproval),!n.worktreePath){let u=o&&Qi(Do({persistedHarness:n.harness,backendRef:n.backendRef}));return{originalWorkdir:i,canCreateManagedWorktreeForResumeWithoutPersistedPath:u}}if(!n.worktreeBranch)throw new Error(`Cannot resume session "${r}": persisted worktree metadata is missing worktreeBranch.`);let a=Qi(Do({persistedHarness:n.harness,backendRef:n.backendRef}))&&!!n.backendRef?.worktreePath;if(XA(n.worktreePath))return console.info(`[SessionManager] Resuming with existing worktree: ${n.worktreePath}`),{actualWorkdir:n.worktreePath,originalWorkdir:i??n.worktreePath,worktreePath:n.worktreePath,worktreeBranchName:n.worktreeBranch};if(!i)return console.warn(`[SessionManager] Worktree ${n.worktreePath} no longer exists and cannot be recreated, using original workdir`),{clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom};if(a)return console.info(`[SessionManager] Native Codex worktree ${n.worktreePath} is missing; resuming from original workdir and letting the backend restore thread state.`),{actualWorkdir:i,originalWorkdir:i,worktreeBranchName:n.worktreeBranch,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom,restoredMissingNativeBackendWorktree:!0};try{ys(i);let u=yp(i,n.worktreeBranch.replace(/^agent\//,""),{allowExistingBranch:!0});return console.info(`[SessionManager] Recreated worktree from branch ${n.worktreeBranch}: ${u}`),{actualWorkdir:u,originalWorkdir:i,worktreePath:u,worktreeBranchName:n.worktreeBranch}}catch(u){return console.warn(`[SessionManager] Failed to recreate worktree for resume: ${tg(u)}, using original workdir`),{actualWorkdir:i,originalWorkdir:i,clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom,failedResumeWorktreeRestore:!0}}}function rg(t,e,r){let{actualWorkdir:n,originalWorkdir:o,worktreePath:i,worktreeBranchName:a,clearedResumeSessionId:u,clearedResumeWorktreeFrom:p,restoredMissingNativeBackendWorktree:d,canCreateManagedWorktreeForResumeWithoutPersistedPath:l,failedResumeWorktreeRestore:m}=rT(t,r);u&&(t.resumeSessionId=void 0),p&&(t.resumeWorktreeFrom=void 0),n??=t.workdir,o??=t.workdir;let c=!!(t.resumeSessionId??t.resumeWorktreeFrom),h=t.worktreeStrategy??K.defaultWorktreeStrategy;h&&(t.worktreeStrategy=h);let y=eT(t),S=(!c||!!l)&&!d&&!i&&h&&h!=="off"&&!y;if(m&&h&&h!=="off")throw new Error(`Cannot launch session "${e}": worktree strategy "${h}" was requested, but no isolated worktree was prepared. Launch with worktree_strategy "off" only when running in the base checkout is intentional.`);if(y&&!gp(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${h}" requires a git worktree, but "${o}" is not a git repository.`);if(S&&gp(o)){if(!Cc(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=yp(o,e),n=i,a=hs(i),!a)throw new Error(`created worktree at ${i} but failed to resolve branch name`);console.log(`[SessionManager] Created worktree at ${i}`)}catch(x){throw new Error(`Cannot launch session "${e}": worktree creation failed: ${tg(x)}`)}}else if(S)throw new Error(`Cannot launch session "${e}": worktree strategy "${h}" requires a git worktree, but "${o}" is not a git repository.`);if(c&&i&&(n=i),h&&h!=="off"&&!i)throw new Error(`Cannot launch session "${e}": worktree strategy "${h}" was requested, but no isolated worktree was prepared. Launch with worktree_strategy "off" only when running in the base checkout is intentional.`);return{actualWorkdir:n,originalWorkdir:o,effectiveSystemPrompt:i&&a?tT(t.systemPrompt,o,i,a):t.systemPrompt,worktreePath:i,worktreeBranchName:a,clearedResumeSessionId:u,clearedResumeWorktreeFrom:p,restoredMissingNativeBackendWorktree:d,failedResumeWorktreeRestore:m}}var Ys=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,r){return rg(e,r,this.getPersistedSession)}hydrateSpawnedSession(e,r,n){n.worktreeStrategy&&n.worktreeStrategy!=="off"&&(e.originalWorkdir=r.originalWorkdir),r.worktreePath&&(e.worktreePath=r.worktreePath,e.worktreeBranch=r.worktreeBranchName,e.worktreeState="provisioned"),n.worktreePrTargetRepo&&(e.worktreePrTargetRepo=n.worktreePrTargetRepo)}};Ee();var Zs=class{constructor(e){this.deps=e}deps;applySessionPatch(e,r){let n=this.normalizeCompletionWakePatch(r),o=this.deps.store.getPersistedSession(e);o&&(Object.assign(o,n),this.deps.store.assertPersistedEntry(o));let i=this.findActiveSessionForRef(e,o);return i&&this.applyPatchToActiveSession(i,n),!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,r){if(!r)return!1;let n=q(e),o=q(r);return!!(r.sessionId&&e.id===r.sessionId||o&&o===n||r?.harnessSessionId&&e.harnessSessionId===r.harnessSessionId||r?.name&&e.name===r.name)}findActiveSessionForRef(e,r){let n=this.deps.resolveSession(e);if(n)return n;for(let o of this.deps.sessions.values())if(ke(o)===e||q(o)===e||o.harnessSessionId===e||this.matchesExistingSession(o,r))return o}applyPatchToActiveSession(e,r){this.applyControlStatePatch(e,r),this.applySessionMetadataPatch(e,r),this.applyWorktreeMetadataPatch(e,r)}applyControlStatePatch(e,r){let n={lifecycle:r.lifecycle,approvalState:r.approvalState,approvalExecutionState:r.approvalExecutionState,worktreeState:r.worktreeState,runtimeState:r.runtimeState,deliveryState:r.deliveryState,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,pendingPlanApproval:r.pendingPlanApproval,planApprovalContext:r.planApprovalContext,planDecisionVersion:r.planDecisionVersion,actionablePlanDecisionVersion:r.actionablePlanDecisionVersion,canonicalPlanPromptVersion:r.canonicalPlanPromptVersion,approvalPromptRequiredVersion:r.approvalPromptRequiredVersion,approvalPromptVersion:r.approvalPromptVersion,approvalPromptStatus:r.approvalPromptStatus,approvalPromptTransport:r.approvalPromptTransport,approvalPromptMessageKind:r.approvalPromptMessageKind,approvalPromptLastAttemptAt:r.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:r.approvalPromptDeliveredAt,approvalPromptFailedAt:r.approvalPromptFailedAt,planModeApproved:r.planModeApproved,pendingWorktreeDecisionSince:r.pendingWorktreeDecisionSince};if(typeof e.applyControlPatch=="function"){e.applyControlPatch(n);return}this.assignIfDefined(e,"lifecycle",r.lifecycle),this.assignIfDefined(e,"approvalState",r.approvalState),this.assignIfDefined(e,"approvalExecutionState",r.approvalExecutionState),this.assignIfDefined(e,"worktreeState",r.worktreeState),this.assignIfDefined(e,"runtimeState",r.runtimeState),this.assignIfDefined(e,"deliveryState",r.deliveryState),this.assignIfDefined(e,"requestedPermissionMode",r.requestedPermissionMode),this.assignIfDefined(e,"currentPermissionMode",r.currentPermissionMode),this.assignIfDefined(e,"pendingPlanApproval",r.pendingPlanApproval),this.assignIfDefined(e,"planApprovalContext",r.planApprovalContext),this.assignIfDefined(e,"planDecisionVersion",r.planDecisionVersion),this.assignIfDefined(e,"actionablePlanDecisionVersion",r.actionablePlanDecisionVersion),this.assignIfDefined(e,"canonicalPlanPromptVersion",r.canonicalPlanPromptVersion),this.assignIfDefined(e,"approvalPromptRequiredVersion",r.approvalPromptRequiredVersion),this.assignIfDefined(e,"approvalPromptVersion",r.approvalPromptVersion),this.assignIfDefined(e,"approvalPromptStatus",r.approvalPromptStatus),this.assignIfDefined(e,"approvalPromptTransport",r.approvalPromptTransport),this.assignIfDefined(e,"approvalPromptMessageKind",r.approvalPromptMessageKind),this.assignIfDefined(e,"approvalPromptLastAttemptAt",r.approvalPromptLastAttemptAt),this.assignIfDefined(e,"approvalPromptDeliveredAt",r.approvalPromptDeliveredAt),this.assignIfDefined(e,"approvalPromptFailedAt",r.approvalPromptFailedAt),this.setControlFieldIfDefined(e,"planModeApproved",r.planModeApproved)}applySessionMetadataPatch(e,r){this.assignIfDefined(e,"approvalRationale",r.approvalRationale)}applyWorktreeMetadataPatch(e,r){this.assignIfDefined(e,"worktreePath",r.worktreePath),this.assignIfDefined(e,"worktreeBranch",r.worktreeBranch),this.assignIfDefined(e,"worktreePrUrl",r.worktreePrUrl),this.assignIfDefined(e,"worktreePrNumber",r.worktreePrNumber),this.assignIfDefined(e,"worktreeMerged",r.worktreeMerged),this.assignIfDefined(e,"worktreeMergedAt",r.worktreeMergedAt),this.assignIfDefined(e,"worktreeDisposition",r.worktreeDisposition),this.assignIfDefined(e,"worktreePrTargetRepo",r.worktreePrTargetRepo),this.assignIfDefined(e,"worktreePushRemote",r.worktreePushRemote),this.assignIfDefined(e,"worktreeLifecycle",r.worktreeLifecycle),"autoMergeParentSessionId"in r&&(e.autoMergeParentSessionId=r.autoMergeParentSessionId),"autoMergeConflictResolutionAttemptCount"in r&&(e.autoMergeConflictResolutionAttemptCount=r.autoMergeConflictResolutionAttemptCount),"autoMergeResolverSessionId"in r&&(e.autoMergeResolverSessionId=r.autoMergeResolverSessionId)}assignIfDefined(e,r,n){n!==void 0&&(e[r]=n)}setControlFieldIfDefined(e,r,n){n!==void 0&&e.setControlField?.(r,n)}};Ee();var nT=new Set(["starting","running"]),Xs=class{constructor(e,r){this.sessions=e;this.store=r}sessions;store;resolveActive(e){let r=this.sessions.get(e);return r||(this.findPreferredMatch(e,n=>n.name===e)??this.findPreferredMatch(e,n=>q(n)===e)??this.findPreferredMatch(e,n=>n.harnessSessionId===e))}getPersistedSession(e){return this.store.getPersistedSession(e)}resolveBackendConversationId(e){let r=this.resolveActive(e);return this.store.resolveBackendConversationId(e,r?q(r)??r.harnessSessionId:void 0)}findPreferredMatch(e,r){let n,o;for(let i of this.sessions.values())r(i,e)&&((!o||i.startedAt>o.startedAt)&&(o=i),nT.has(i.status)&&(!n||i.startedAt>n.startedAt)&&(n=i));return n??o}};Ee();Ee();Pt();var ng=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]),ea=class{constructor(e){this.deps=e}deps;async plan(e){let r=ke(e)??e.harnessSessionId;if(this.deps.isAlreadyMerged(r))return console.info(`[SessionManager] handleWorktreeStrategy: session "${e.name}" already merged \u2014 skipping strategy handling`),{kind:"skip",result:{notificationSent:!0,worktreeRemoved:!1}};let n=ng.has(e.worktreeState)?e.worktreeState:e.worktreeLifecycle?.state&&ng.has(e.worktreeLifecycle.state)?e.worktreeLifecycle.state:void 0;if(n&&!(n==="pr_open"&&e.worktreeStrategy==="auto-pr"))return console.info(`[SessionManager] handleWorktreeStrategy: session "${e.name}" worktree is ${e.worktreeLifecycle?.state??e.worktreeState} \u2014 skipping strategy handling`),{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 console.info(`[SessionManager] handleWorktreeStrategy: skipping \u2014 session "${e.name}" is in phase "${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,a=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,i),u=e.worktreeBranch;if(!a)return{kind:"notify",label:"worktree-missing-repo-dir",message:`\u26A0\uFE0F [${e.name}] Cannot determine the original repo for worktree ${i}. Manual inspection is required.`};if(!u)return{kind:"notify",label:"worktree-no-branch-name",message:`\u26A0\uFE0F [${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 p=e.worktreeBaseBranch??wr(a),d=this.deps.getWorktreeCompletionState(a,i,u,p);if(d==="no-change")return{kind:"no-change",repoDir:a,worktreePath:i,nativeBackendWorktree:mt(e)};if(d==="base-advanced")return{kind:"notify",label:"worktree-no-commits-ahead",message:`\u26A0\uFE0F [${e.name}] Auto-merge: branch '${u}' has no commits ahead of '${p}', but '${p}' has new commits \u2014 commits likely landed outside the worktree branch. Verify that commits were not made directly to '${p}' instead of the worktree branch. Worktree: ${i}`};if(d==="dirty-uncommitted")return{kind:"dirty-uncommitted",worktreePath:i,branchName:u,baseBranch:p};let l=sn(a,u,p);return l?{kind:"decision",strategy:o,repoDir:a,worktreePath:i,branchName:u,baseBranch:p,diffSummary:l,sessionRef:r??void 0}:(console.warn(`[SessionManager] Failed to get diff summary for ${u}, skipping merge-back`),{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}})}};qs();function oT(t){if(t.requestedPermissionMode==="plan"){if(t.approvalExecutionState==="approved_then_implemented"){if(t.planApproval==="ask"&&t.approvalPromptStatus==="delivered"&&t.approvalPromptMessageKind==="canonical_buttons"&&t.approvalPromptDeliveredAt)return"Approval interpretation: canonical Approve/Revise/Reject buttons were delivered, and implementation after approval was expected.";if(t.approvalState==="approved")return"Approval interpretation: explicit plan approval was recorded before implementation, so leaving plan-only mode was expected."}if(t.approvalExecutionState==="implemented_without_required_approval")return"Approval interpretation: implementation left plan-only mode without a recorded approval."}}var qp="COMPLETION_FOLLOWUP_DELIVERED",Bp="COMPLETION_FOLLOWUP_SKIPPED";function ta(t){let e=oT(t);return[`Requested permission mode: ${t.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${t.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${t.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function Yo(t){switch(t){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 iT(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function sT(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToWorktreeTerminalOutcomes:!0}}function aT(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToGoalTaskCompletions:!0}}function Wp(t){let{sessionId:e,canonicalStatusDetail:r,canonicalStatusDelivered:n=!0,hasOriginRouteBlock:o=!1}=t,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."]:[],a=o?8:7,u=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 \u2014 do not wait for user input.",`3. ${r??(n?"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,`${a}. 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.`,...n?[`${u}. Do NOT repeat the plugin's status line, and do NOT rely on the plugin to summarize the completed work for you.`]:[`${u}. 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.`],`${u+1}. After the visible follow-up summary has actually been sent to the user or origin route, finish this wake turn with ${qp}. Use ${Bp}: <brief reason> only for valid skip cases: silently continuing an internal multi-phase pipeline, no meaningful confirmed outcome to report, incomplete or unreliable result data, an explicit NO_REPLY/silent cron/system opt-out, or a duplicate wake where you can confirm a prior orchestrator follow-up summary for this same outcome was already visibly delivered. Do not skip merely because agent_output contains a meaningful summary. Otherwise do not use either marker and do not answer NO_REPLY.`]}function uT(t){let{contract:e,canonicalStatusDelivered:r}=t;return["Completion diagnostics:",`- Canonical completion status delivered to user: ${r?"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 Up(t){let{session:e,originThreadLine:r,preview:n}=t,o=!!r.trim(),i=`$${(e.costUsd??0).toFixed(2)}`,a=Ft(e.duration),u=iT(),p=d=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,...o?[r]:[],...ta(e),"","Output preview:",n,"",...uT({contract:u,canonicalStatusDelivered:d}),"",...Wp({sessionId:e.id,canonicalStatusDelivered:d,hasOriginRouteBlock:o})].join(`
|
|
157
|
-
`);return{userMessage
|
|
158
|
-
`)}function
|
|
159
|
-
`)}function
|
|
160
|
-
`),wakeMessage:["Coding agent session failed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,
|
|
161
|
-
`),buttons:
|
|
162
|
-
`)}}function
|
|
163
|
-
`)}function
|
|
164
|
-
`)}function
|
|
165
|
-
`)}var
|
|
166
|
-
`).map(e=>e.trim()).filter(Boolean).map(
|
|
167
|
-
`).map(e=>e.trim()).filter(Boolean).map(
|
|
168
|
-
- Plan details are available in the full session output.`:["Review summary:",...e.slice(0,6).map(
|
|
169
|
-
`)}function
|
|
170
|
-
`).length>
|
|
171
|
-
`).length>
|
|
172
|
-
`)}function
|
|
173
|
-
`),
|
|
174
|
-
${
|
|
155
|
+
`));return}e.iteration+=1;let f=om(e,c),g=pr({output:s,verifierSummary:c.summary,completionPromise:a,completionDetected:!0});try{let h=await this.resumeTaskSession(e,f,n);this.setTaskRunningWithSession(e,h),this.notifyIterationStatus(e,`đ [${e.name}] Completion claimed but verifiers still failed`,void 0,g),this.scheduleTaskEvaluation(e.id,"ralph-verifier-resume",h.id)}catch(h){this.markTaskFailed(e,`Failed to resume the Ralph goal task after verifier failure: ${Ge(h)}`)}return}let l=em(s);if(e.lastVerifierFingerprint===l?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=l,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Completion promise "${a}" was not emitted before hitting the iteration budget (${e.maxIterations}).`,"Latest output:",$e(s,20)||"(no output)"].join(`
|
|
156
|
+
`));return}e.iteration+=1;let u=rm(e,s),p=pr({output:s,completionPromise:a,completionDetected:!1});try{let c=await this.resumeTaskSession(e,u,n);this.setTaskRunningWithSession(e,c),this.notifyIterationStatus(e,`đ [${e.name}] Continued`,void 0,p),this.scheduleTaskEvaluation(e.id,"ralph-continue",c.id)}catch(c){this.markTaskFailed(e,`Failed to continue the Ralph goal task: ${Ge(c)}`)}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(`
|
|
157
|
+
`));return}e.iteration+=1;let o=nm(e,r),i=pr({verifierSummary:r.summary});try{let s=await this.resumeTaskSession(e,o,n);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: ${Ge(s)}`)}}async evaluateTask(e,n,r){this.restorePromise&&await this.restorePromise;let o=this.store.get(e);o&&await this.reconcileTask(o,n,r)}async reconcileTask(e,n="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(Qa(e)){this.markTaskFailed(e,yr());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,`${n}:dirty`,o)}}}}};te();import{existsSync as lm,realpathSync as um}from"fs";import{resolve as pm}from"path";function rd(t){if(!t)return;let e=pm(t);try{if(lm(e))return um.native(e)}catch{}return e}function vr(t,e){return!t||!e?!1:rd(t)===rd(e)}Q();te();import{existsSync as cm}from"fs";Q();fe();function od(t){return t instanceof Error?t.message:String(t)}function mm(t){let e=t.worktreeStrategy??E.defaultWorktreeStrategy;return!!e&&e!=="off"&&Mo(Mt({harnessName:t.harness??se(),backendRef:t.backendRef}))}function fm(t,e,n,r){let o=["","You are working in a git worktree.",`Worktree path: ${n}`,`Branch: ${r}`,"",`IMPORTANT: ALL file edits must be made within this worktree at ${n}.`,`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(`
|
|
158
|
+
`);return(t??"")+o}function gm(t,e){let n=t.resumeWorktreeFrom??t.resumeSessionId;if(!n)return{};let r=e(n);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=Dn(r.worktreePath);return r.workdir&&a&&vr(r.workdir,a)?r.workdir:a??r.workdir}return r.workdir})();if(t.worktreeStrategy||(r.worktreeLifecycle?.state==="pr_open"||r.worktreePrUrl?t.worktreeStrategy="auto-pr":r.worktreeStrategy&&(t.worktreeStrategy=r.worktreeStrategy)),!t.planApproval&&r.planApproval&&(t.planApproval=r.planApproval),!r.worktreePath){let a=o&&fn(Mt({persistedHarness:r.harness,backendRef:r.backendRef}));return{originalWorkdir:i,canCreateManagedWorktreeForResumeWithoutPersistedPath:a}}if(!r.worktreeBranch)throw new Error(`Cannot resume session "${n}": persisted worktree metadata is missing worktreeBranch.`);let s=fn(Mt({persistedHarness:r.harness,backendRef:r.backendRef}))&&!!r.backendRef?.worktreePath;if(cm(r.worktreePath))return`${r.worktreePath}`,{actualWorkdir:r.worktreePath,originalWorkdir:i??r.worktreePath,worktreePath:r.worktreePath,worktreeBranchName:r.worktreeBranch};if(!i)return`${r.worktreePath}`,{clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom};if(s)return`${r.worktreePath}`,{actualWorkdir:i,originalWorkdir:i,worktreeBranchName:r.worktreeBranch,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom,restoredMissingNativeBackendWorktree:!0};try{Nn(i);let a=Wo(i,r.worktreeBranch.replace(/^agent\//,""),{allowExistingBranch:!0});return`${r.worktreeBranch}${a}`,{actualWorkdir:a,originalWorkdir:i,worktreePath:a,worktreeBranchName:r.worktreeBranch}}catch(a){return`${od(a)}`,{actualWorkdir:i,originalWorkdir:i,clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom,failedResumeWorktreeRestore:!0}}}function id(t,e,n){let{actualWorkdir:r,originalWorkdir:o,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d,restoredMissingNativeBackendWorktree:l,canCreateManagedWorktreeForResumeWithoutPersistedPath:u,failedResumeWorktreeRestore:p}=gm(t,n);a&&(t.resumeSessionId=void 0),d&&(t.resumeWorktreeFrom=void 0),r??=t.workdir,o??=t.workdir;let c=!!(t.resumeSessionId??t.resumeWorktreeFrom),f=t.worktreeStrategy??E.defaultWorktreeStrategy;f&&(t.worktreeStrategy=f);let g=mm(t),y=(!c||!!u)&&!l&&!i&&f&&f!=="off"&&!g;if(p&&f&&f!=="off")throw new Error(`Cannot launch session "${e}": worktree strategy "${f}" was requested, but no isolated worktree was prepared. Launch with worktree_strategy "off" only when running in the base checkout is intentional.`);if(g&&!Oo(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${f}" requires a git worktree, but "${o}" is not a git repository.`);if(y&&Oo(o)){if(!Os(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=Wo(o,e),r=i,s=On(i),!s)throw new Error(`created worktree at ${i} but failed to resolve branch name`);`${i}`}catch(k){throw new Error(`Cannot launch session "${e}": worktree creation failed: ${od(k)}`)}}else if(y)throw new Error(`Cannot launch session "${e}": worktree strategy "${f}" requires a git worktree, but "${o}" is not a git repository.`);if(c&&i&&(r=i),f&&f!=="off"&&!i)throw new Error(`Cannot launch session "${e}": worktree strategy "${f}" 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?fm(t.systemPrompt,o,i,s):t.systemPrompt,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d,restoredMissingNativeBackendWorktree:l,failedResumeWorktreeRestore:p}}var wr=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,n){return id(e,n,this.getPersistedSession)}hydrateSpawnedSession(e,n,r){r.worktreeStrategy&&r.worktreeStrategy!=="off"&&(e.originalWorkdir=n.originalWorkdir),n.worktreePath&&(e.worktreePath=n.worktreePath,e.worktreeBranch=n.worktreeBranchName,e.worktreeState="provisioned"),r.worktreePrTargetRepo&&(e.worktreePrTargetRepo=r.worktreePrTargetRepo)}};Q();var Pr=class{constructor(e){this.deps=e}deps;applySessionPatch(e,n){let r=this.normalizeCompletionWakePatch(n),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,n){if(!n)return!1;let r=T(e),o=T(n);return!!(n.sessionId&&e.id===n.sessionId||o&&o===r||n?.harnessSessionId&&e.harnessSessionId===n.harnessSessionId||n?.name&&e.name===n.name)}findActiveSessionForRef(e,n){let r=this.deps.resolveSession(e);if(r)return r;for(let o of this.deps.sessions.values())if(N(o)===e||T(o)===e||o.harnessSessionId===e||this.matchesExistingSession(o,n))return o}applyPatchToActiveSession(e,n){this.applyControlStatePatch(e,n),this.applySessionMetadataPatch(e,n),this.applyWorktreeMetadataPatch(e,n)}applyControlStatePatch(e,n){let r={};if(this.copyControlPatchField(r,n,"lifecycle"),this.copyControlPatchField(r,n,"approvalState"),this.copyControlPatchField(r,n,"approvalExecutionState"),this.copyControlPatchField(r,n,"worktreeState"),this.copyControlPatchField(r,n,"runtimeState"),this.copyControlPatchField(r,n,"deliveryState"),this.copyControlPatchField(r,n,"requestedPermissionMode"),this.copyControlPatchField(r,n,"currentPermissionMode"),this.copyControlPatchField(r,n,"pendingPlanApproval"),this.copyControlPatchField(r,n,"planApprovalContext"),this.copyControlPatchField(r,n,"planDecisionVersion"),this.copyControlPatchField(r,n,"actionablePlanDecisionVersion"),this.copyControlPatchField(r,n,"canonicalPlanPromptVersion"),this.copyControlPatchField(r,n,"approvalPromptRequiredVersion"),this.copyControlPatchField(r,n,"approvalPromptVersion"),this.copyControlPatchField(r,n,"approvalPromptStatus"),this.copyControlPatchField(r,n,"approvalPromptTransport"),this.copyControlPatchField(r,n,"approvalPromptMessageKind"),this.copyControlPatchField(r,n,"approvalPromptLastAttemptAt"),this.copyControlPatchField(r,n,"approvalPromptDeliveredAt"),this.copyControlPatchField(r,n,"approvalPromptFailedAt"),this.copyControlPatchField(r,n,"planModeApproved"),this.copyControlPatchField(r,n,"pendingWorktreeDecisionSince"),typeof e.applyControlPatch=="function"){e.applyControlPatch(r);return}this.assignIfPresent(e,"lifecycle",n,"lifecycle"),this.assignIfPresent(e,"approvalState",n,"approvalState"),this.assignIfPresent(e,"approvalExecutionState",n,"approvalExecutionState"),this.assignIfPresent(e,"worktreeState",n,"worktreeState"),this.assignIfPresent(e,"runtimeState",n,"runtimeState"),this.assignIfPresent(e,"deliveryState",n,"deliveryState"),this.assignIfPresent(e,"requestedPermissionMode",n,"requestedPermissionMode"),this.assignIfPresent(e,"currentPermissionMode",n,"currentPermissionMode"),this.assignIfPresent(e,"pendingPlanApproval",n,"pendingPlanApproval"),this.assignIfPresent(e,"planApprovalContext",n,"planApprovalContext"),this.assignIfPresent(e,"planDecisionVersion",n,"planDecisionVersion"),this.assignIfPresent(e,"actionablePlanDecisionVersion",n,"actionablePlanDecisionVersion"),this.assignIfPresent(e,"canonicalPlanPromptVersion",n,"canonicalPlanPromptVersion"),this.assignIfPresent(e,"approvalPromptRequiredVersion",n,"approvalPromptRequiredVersion"),this.assignIfPresent(e,"approvalPromptVersion",n,"approvalPromptVersion"),this.assignIfPresent(e,"approvalPromptStatus",n,"approvalPromptStatus"),this.assignIfPresent(e,"approvalPromptTransport",n,"approvalPromptTransport"),this.assignIfPresent(e,"approvalPromptMessageKind",n,"approvalPromptMessageKind"),this.assignIfPresent(e,"approvalPromptLastAttemptAt",n,"approvalPromptLastAttemptAt"),this.assignIfPresent(e,"approvalPromptDeliveredAt",n,"approvalPromptDeliveredAt"),this.assignIfPresent(e,"approvalPromptFailedAt",n,"approvalPromptFailedAt"),this.setControlFieldIfPresent(e,"planModeApproved",n)}applySessionMetadataPatch(e,n){this.assignIfDefined(e,"approvalRationale",n.approvalRationale)}applyWorktreeMetadataPatch(e,n){this.assignIfDefined(e,"worktreePath",n.worktreePath),this.assignIfDefined(e,"worktreeBranch",n.worktreeBranch),this.assignIfDefined(e,"worktreePrUrl",n.worktreePrUrl),this.assignIfDefined(e,"worktreePrNumber",n.worktreePrNumber),this.assignIfDefined(e,"worktreeMerged",n.worktreeMerged),this.assignIfDefined(e,"worktreeMergedAt",n.worktreeMergedAt),this.assignIfDefined(e,"worktreeDisposition",n.worktreeDisposition),this.assignIfDefined(e,"worktreePrTargetRepo",n.worktreePrTargetRepo),this.assignIfDefined(e,"worktreePushRemote",n.worktreePushRemote),this.assignIfDefined(e,"worktreeLifecycle",n.worktreeLifecycle),"autoMergeParentSessionId"in n&&(e.autoMergeParentSessionId=n.autoMergeParentSessionId),"autoMergeConflictResolutionAttemptCount"in n&&(e.autoMergeConflictResolutionAttemptCount=n.autoMergeConflictResolutionAttemptCount),"autoMergeResolverSessionId"in n&&(e.autoMergeResolverSessionId=n.autoMergeResolverSessionId)}assignIfDefined(e,n,r){r!==void 0&&(e[n]=r)}assignIfPresent(e,n,r,o){Object.hasOwn(r,o)&&(e[n]=r[o])}copyControlPatchField(e,n,r){Object.hasOwn(n,r)&&(e[r]=n[r])}setControlFieldIfPresent(e,n,r){Object.hasOwn(r,n)&&e.setControlField?.(n,r[n])}};Q();var hm=new Set(["starting","running"]),br=class{constructor(e,n){this.sessions=e;this.store=n}sessions;store;resolveActive(e){let n=this.sessions.get(e);return n||(this.findPreferredMatch(e,r=>r.name===e)??this.findPreferredMatch(e,r=>T(r)===e)??this.findPreferredMatch(e,r=>r.harnessSessionId===e))}getPersistedSession(e){return this.store.getPersistedSession(e)}resolveBackendConversationId(e){let n=this.resolveActive(e);return this.store.resolveBackendConversationId(e,n?T(n)??n.harnessSessionId:void 0)}findPreferredMatch(e,n){let r,o;for(let i of this.sessions.values())n(i,e)&&((!o||i.startedAt>o.startedAt)&&(o=i),hm.has(i.status)&&(!r||i.startedAt>r.startedAt)&&(r=i));return r??o}};Q();Q();fe();var sd=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]),Ar=class{constructor(e){this.deps=e}deps;async plan(e){let n=N(e)??e.harnessSessionId;if(this.deps.isAlreadyMerged(n))return`${e.name}`,{kind:"skip",result:{notificationSent:!0,worktreeRemoved:!1}};let r=sd.has(e.worktreeState)?e.worktreeState:e.worktreeLifecycle?.state&&sd.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 d=e.worktreeBaseBranch??Pe(s),l=this.deps.getWorktreeCompletionState(s,i,a,d);if(l==="no-change")return{kind:"no-change",repoDir:s,worktreePath:i,nativeBackendWorktree:de(e)};if(l==="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(l==="dirty-uncommitted")return{kind:"dirty-uncommitted",worktreePath:i,branchName:a,baseBranch:d};let u=Ie(s,a,d);return u?{kind:"decision",strategy:o,repoDir:s,worktreePath:i,branchName:a,baseBranch:d,diffSummary:u,sessionRef:n??void 0}:(`${a}`,{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}})}};ar();function Sm(t){if(t.requestedPermissionMode==="plan"){if(t.approvalExecutionState==="approved_then_implemented"){if(t.planApproval==="ask"&&t.approvalPromptStatus==="delivered"&&t.approvalPromptMessageKind==="canonical_buttons"&&t.approvalPromptDeliveredAt)return"Approval interpretation: canonical Approve/Revise/Reject buttons were delivered, and implementation after approval was expected.";if(t.approvalState==="approved")return"Approval interpretation: explicit plan approval was recorded before implementation, so leaving plan-only mode was expected."}if(t.approvalExecutionState==="implemented_without_required_approval")return"Approval interpretation: implementation left plan-only mode without a recorded approval."}}function ym(){return/https?:\/\/github\.com\/[^\s)]+\/[^\s)]+\/pull\/(\d+)(?=[\s).,;:]|$)/gi}function km(){return/https?:\/\/\S+/gi}function Rr(t){let e=Sm(t);return[`Requested permission mode: ${t.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${t.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${t.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function di(t){switch(t){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 vm(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function wm(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToWorktreeTerminalOutcomes:!0}}function Pm(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToGoalTaskCompletions:!0}}function li(t){let{sessionId:e,canonicalStatusDetail:n,canonicalStatusDelivered:r=!0,hasOriginRouteBlock:o=!1}=t,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. ${n??(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 bm(t){let{contract:e,canonicalStatusDelivered:n}=t;return["Completion diagnostics:",`- Canonical completion status delivered to user: ${n?"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 ui(t){let{session:e,originThreadLine:n,preview:r}=t,o=!!n.trim(),i=`$${(e.costUsd??0).toFixed(2)}`,s=ve(e.duration),a=vm(),d=l=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,...o?[n]:[],...Rr(e),"","Output preview:",r,"",...bm({contract:a,canonicalStatusDelivered:l}),"",...li({sessionId:e.id,canonicalStatusDelivered:l,hasOriginRouteBlock:o})].join(`
|
|
159
|
+
`);return{userMessage:`â
[${e.name}] Completed | ${i} | ${s}${yn({harness:e.harnessName,model:e.model})}`,wakeMessageOnNotifySuccess:d(!0),wakeMessageOnNotifyFailed:d(!1),followupContract:a}}function ft(t){let e=wm(),n=!!t.originThreadLine.trim(),r=(t.detailLines??[]).map(i=>ad(i).trim()).filter(i=>i.length>0),o=ad(t.outcomeLine);return["Worktree follow-through outcome recorded.",`Name: ${t.sessionName??"unknown"} | ID: ${t.sessionId}`,...n?[t.originThreadLine]:[],"","Canonical outcome status:",o,...r.length>0?["","Outcome details:",...r.map(i=>`- ${i}`)]:[],"","Completion diagnostics:",`- Canonical worktree status delivered to user: ${t.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='${t.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.",...n?["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."]:[],`${n?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.`,`${n?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(`
|
|
160
|
+
`)}function pi(t){let e=Pm(),n=!!t.originThreadLine.trim();return["Goal task succeeded.",`Task: ${t.taskName}`,`Name: ${t.sessionName??t.taskName} | ID: ${t.sessionId}`,...n?[t.originThreadLine]:[],"","Canonical goal status:",t.summary,"","Completion diagnostics:",`- Canonical goal success status delivered to user: ${t.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='${t.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.",...n?["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."]:[],`${n?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.`,`${n?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(`
|
|
161
|
+
`)}function ad(t){return t.replace(ym(),"PR #$1").replace(km(),"[link omitted]")}function ci(t){let{session:e,originThreadLine:n,errorSummary:r,preview:o,worktreeAutoCleaned:i,failedButtons:s}=t,a=o.trim()?["","Output preview:",o]:[],d=i?["","Note: Worktree and branch were auto-removed (zero cost, startup failure)."]:[],l=`$${(e.costUsd??0).toFixed(2)}`,u=ve(e.duration);return{userMessage:[`â [${e.name}] Failed | ${l} | ${u}${yn({harness:e.harnessName,model:e.model})}`,` â ī¸ ${r}`].join(`
|
|
162
|
+
`),wakeMessage:["Coding agent session failed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,n,...Rr(e),...e.harnessSessionId?[`Backend conversation ID: ${e.harnessSessionId}`]:[],"","Failure summary:",r,...a,...d,"","[ACTION REQUIRED] Follow your autonomy rules for session failure:",`1. Use agent_output(session='${e.id}', full=true) to inspect the full failure context.`,`2. Continue the same session with agent_respond(session='${e.id}', message='<next instruction>').`,` If you intentionally want to fork or switch harnesses, launch a new session with agent_launch(resume_session_id='${e.id}', fork_session=true, ...)`," If the failure is a launch/config issue, relaunch fresh with agent_launch(prompt=...).","3. Notify the user with the failure cause and the next action you are taking."].join(`
|
|
163
|
+
`),buttons:s}}function mi(t){let{session:e,originThreadLine:n,preview:r}=t,o=`$${(e.costUsd??0).toFixed(2)}`;return{userMessage:`â¸ī¸ [${e.name}] Turn completed | ${o}${yn({harness:e.harnessName,model:e.model})}`,wakeMessage:["Coding agent session turn ended.",`Name: ${e.name}`,`ID: ${e.id}`,`Status: ${e.status}`,`Lifecycle: ${e.lifecycle}`,"","Last output (~20 lines):",r,...n?["",n]:[]].join(`
|
|
164
|
+
`)}}function fi(t){let{sessionName:e,sessionId:n,branchName:r,baseBranch:o,promptSnippet:i,commitLines:s,moreNote:a,originThreadLine:d,diffSummary:l}=t,u=!!d?.trim();return[`[DELEGATED WORKTREE DECISION] Session "${e}" completed with changes.`,"",`Session ID: ${n}`,`Branch: ${r} â ${o}`,`Commits: ${l.commits} | Files: ${l.filesChanged} | +${l.insertions} / -${l.deletions}`,...u?[d]:[],"",...s,...a?[a]:[],"","Original task prompt (first 500 chars):",i,"","You own the next step for this worktree.",`- Merge immediately with agent_merge(session="${e}", base_branch="${o}") if the changes are clearly in-scope and low-risk.`,`- If a PR is safer or human choice is needed, call agent_request_worktree_decision(session="${e}", summary="...") so the user gets the canonical Merge/Open PR/Later/Discard buttons.`,`- If scope or risk is unclear, call agent_request_worktree_decision(session="${e}", summary="...") with a concise risk summary instead of sending a plain-text-only question.`,"- Never call agent_pr() autonomously in delegate mode.","- After deciding, notify the user briefly with what you did and why.",...u?["- Send any human follow-up to the Session origin route above; if it differs from the current chat, do not use a plain final assistant reply."]:[]].join(`
|
|
165
|
+
`)}function gi(t,e){return[`[DELEGATED WORKTREE DECISION REMINDER] Session "${t.name}" still has an unresolved worktree decision.`,"",`Session ID: ${t.sessionId??t.harnessSessionId}`,`Branch: ${t.worktreeBranch??"unknown"}`,`Pending: ${e}h`,"","Resolve it now:",`- agent_merge(session="${t.name}") if the diff is clearly safe and in scope`,"- If a PR is safer, ask the user before agent_pr()","- If scope or risk is unclear, ask the user for guidance","- Never call agent_pr() autonomously in delegate mode"].join(`
|
|
166
|
+
`)}function hi(t){let{sessionName:e,sessionId:n,cleanupSummary:r,preview:o,originThreadLine:i,requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:u,approvalPromptStatus:p,approvalPromptMessageKind:c,approvalPromptDeliveredAt:f}=t,g=o.trim()?["","Output preview:",o]:[],h=!!i?.trim();return["Coding agent session completed with no repository changes.",`Name: ${e} | ID: ${n}`,`Worktree outcome: ${r}`,...h?[i]:[],...Rr({requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:u,approvalPromptStatus:p,approvalPromptMessageKind:c,approvalPromptDeliveredAt:f}),...g,"",...li({sessionId:n,canonicalStatusDetail:"The plugin already sent the canonical completion status to the user, including that no repo changes were kept.",hasOriginRouteBlock:h})].join(`
|
|
167
|
+
`)}var ud=3200,Si=3e3,Am=2400,Rm=120,Im=5,xm=280,dd=1400,ld="- Additional plan details omitted for brevity.";function pd(t){return t.replace(/^#{1,6}\s+/,"").replace(/^[-*+]\s+/,"").replace(/^\d+[.)]\s+/,"").replace(/^`([^`]+)`$/,"$1").trim()}function Tm(t){return t.split(`
|
|
168
|
+
`).map(e=>e.trim()).filter(Boolean).map(pd).map(e=>ne(e,220)).filter(e=>e.length>0).filter(e=>!/^(plan|proposed plan|implementation plan|review summary|full plan)[:]?$/i.test(e)).filter(e=>!/^(should|can|could|would|will)\b.*\?$/i.test(e)).filter(e=>!/^(thinking|checking|considering|analyzing)\b/i.test(e))}function Cm(t){return t.split(`
|
|
169
|
+
`).map(e=>e.trim()).filter(Boolean).map(pd).filter(e=>e.length>0).filter(e=>!/^(plan|proposed plan|implementation plan|review summary|summary|why this was escalated|full plan)[:]?$/i.test(e)).filter(e=>!/^(should|can|could|would|will)\b.*\?$/i.test(e)).filter(e=>!/^(thinking|checking|considering|analyzing)\b/i.test(e))}function yi(t){let e=Tm(t);return e.length===0?`Review summary:
|
|
170
|
+
- Plan details are available in the full session output.`:["Review summary:",...e.slice(0,6).map(n=>`- ${n}`)].join(`
|
|
171
|
+
`)}function Mm(t){let e=[],n=!1;for(let o of t){let i=o.replace(/\s+/g," ").trim();if(!i)continue;let s=ne(i,xm);s.length<i.length&&(n=!0);let a=`- ${s}`;if(e.length>=Im||[...e,a].join(`
|
|
172
|
+
`).length>dd){n=!0;break}e.push(a)}if(e.length===0)return["- Plan details are available in the full session output."];if(!n)return e;let r=[...e];for(;r.length>0&&[...r,ld].join(`
|
|
173
|
+
`).length>dd;)r.pop();return[...r,ld]}function ki(t){return Mm(Cm(t)).join(`
|
|
174
|
+
`)}function _m(t,e){let n=[],r=t.trim();for(;r.length>e;){let o=r.lastIndexOf(" ",e);o<Math.floor(e*.6)&&(o=e),n.push(r.slice(0,o).trimEnd()),r=r.slice(o).trimStart()}return r.length>0&&n.push(r),n}function Em(t,e){let n=t.split(`
|
|
175
|
+
`),r=[],o="",i=()=>{o.trim().length>0&&(r.push(o.trimEnd()),o="")};for(let s of n){if(s.length>e){i();for(let d of _m(s,e))r.push(d);continue}let a=o.length>0?`${o}
|
|
176
|
+
${s}`:s;if(a.length>e){i(),o=s;continue}o=a}return i(),r}function cd(t){return ne(t.trim(),Rm)}function md(t,e){return e?t?`
|
|
175
177
|
|
|
176
178
|
Choose Approve, Revise, or Reject below.`:`
|
|
177
179
|
|
|
178
180
|
Approval is still pending for this plan version.`:`
|
|
179
181
|
|
|
180
|
-
Continued in next message.`}function
|
|
182
|
+
Continued in next message.`}function $m(t){let{sessionName:e,actionableVersion:n,fullPlanText:r,hasButtons:o}=t,i=`đ [${e}] Plan v${n??"?"} ready for approval:`,s=`
|
|
181
183
|
|
|
182
184
|
Full plan (truncated):
|
|
183
|
-
`,
|
|
184
|
-
`),
|
|
185
|
-
${
|
|
186
|
-
${
|
|
185
|
+
`,a=md(o,!0),d=Math.max(0,Si-i.length-s.length-a.length);return`${i}${s}${ne(r,d)}${a}`}function Dm(t){let{sessionName:e,actionableVersion:n,fullPlanText:r,hasButtons:o}=t,i=cd(e),s=Am;for(;s>0;){let a=Em(r,s),d=a.map((p,c)=>{let f=a.length,g=[`đ [${i}] Plan v${n??"?"} ready for approval (${c+1}/${f}):`,"",c===0?"Full plan:":""].filter(Boolean).join(`
|
|
186
|
+
`),h=md(o,c===f-1);return`${g}
|
|
187
|
+
${p}${h}`}),l=d.reduce((p,c)=>Math.max(p,c.length),0);if(l<=Si)return d;let u=l-Si;s-=Math.max(u,50)}return[$m({sessionName:i,actionableVersion:n,fullPlanText:r,hasButtons:o})]}function vi(t){let{preview:e,artifact:n}=t,r=n?.markdown?.trim();return r&&r.length<=ud?`Full plan:
|
|
188
|
+
${r}`:yi(r||e)}function fd(t){let{sessionName:e,actionableVersion:n,preview:r,artifact:o,hasButtons:i}=t,s=o?.markdown?.trim(),a=cd(e);if(s){let l=`đ [${a}] Plan v${n??"?"} ready for approval:
|
|
187
189
|
|
|
188
190
|
Full plan:
|
|
189
|
-
${
|
|
190
|
-
|
|
191
|
-
${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`;return
|
|
192
|
-
${
|
|
193
|
-
|
|
194
|
-
${
|
|
195
|
-
|
|
196
|
-
${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`],reviewSummary:
|
|
197
|
-
`).map(
|
|
198
|
-
`).trim();if(!(!
|
|
199
|
-
`)
|
|
200
|
-
|
|
201
|
-
${e}`}function
|
|
202
|
-
`)}function
|
|
203
|
-
`)}
|
|
204
|
-
`),buttons:
|
|
205
|
-
`)}}let
|
|
206
|
-
`),buttons:
|
|
207
|
-
`).map(
|
|
208
|
-
`)}function
|
|
191
|
+
${s}
|
|
192
|
+
|
|
193
|
+
${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`;return l.length<=ud?{displayMode:"single-full-plan",userMessages:[l],reviewSummary:`Full plan:
|
|
194
|
+
${s}`}:{displayMode:"chunked-full-plan",userMessages:Dm({sessionName:e,actionableVersion:n,fullPlanText:s,hasButtons:i}),reviewSummary:yi(s)}}let d=yi(r);return{displayMode:"summary",userMessages:[`đ [${a}] Plan v${n??"?"} ready for approval:
|
|
195
|
+
|
|
196
|
+
${d}
|
|
197
|
+
|
|
198
|
+
${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`],reviewSummary:d}}var gd=700;function Om(t){let e=t?.trim();return e||void 0}function Nm(t,e){let n=e?.trim();if(!n)return;if(!t)return n;let r=t.trim(),o=n.split(`
|
|
199
|
+
`).map(a=>a.trimEnd());for(;o.length>0&&!o[o.length-1]?.trim();)o.pop();for(;o.length>0&&o[o.length-1]?.trim()===r;)o.pop();let s=o.filter((a,d,l)=>{let u=a.trim();return!u||u!==r?!0:!l.some((c,f)=>f!==d&&c.trim().length>0&&c.trim()!==r)}).join(`
|
|
200
|
+
`).trim();if(!(!s||s===r))return s.length>gd?vn(s,gd):s}function Wm(t){let e=Om(t.questionText)??"The session is waiting for your reply.",n=Nm(e,t.contextPreview);return n?[`â [${t.sessionName}] Question waiting for reply:`,"","Question:",e,"","Recent context:",n].join(`
|
|
201
|
+
`):`â [${t.sessionName}] Question waiting for reply:
|
|
202
|
+
|
|
203
|
+
${e}`}function Lm(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function jt(t){let{session:e,summary:n}=t,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","","Why this was escalated:","",n].join(`
|
|
204
|
+
`)}function wi(t){let{session:e,preview:n,questionText:r,questionContextPreview:o,planArtifact:i,originThreadLine:s,planApprovalMode:a,planApprovalButtons:d,questionButtons:l}=t,u=e.pendingPlanApproval,p=e.actionablePlanDecisionVersion??e.planDecisionVersion,c=Lm(e,p),f=a??"delegate",g=u&&f==="ask"&&!c?fd({sessionName:e.name,actionableVersion:p,preview:n,artifact:i,hasButtons:!!d}):void 0,h=u?g?.reviewSummary??vi({preview:n,artifact:i}):void 0,y=u?g&&g.userMessages.length===1?g.userMessages[0]:void 0:Wm({sessionName:e.name,questionText:r??n,contextPreview:o}),k=u&&g&&g.userMessages.length>1?g.userMessages.map((A,I,W)=>({text:A,buttons:I===W.length-1?d:void 0})):void 0;if(u){let A=f,I="Permission mode: plan â will switch to bypassPermissions on approval";return A==="delegate"?{label:"plan-approval",userMessage:y,userMessages:k,planReviewSummary:h,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${p??"?"}`,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):",n,"","âââ 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(`
|
|
205
|
+
`)}:A==="ask"?{label:"plan-approval",userMessage:y,userMessages:k,planReviewSummary:h,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${p??"?"}`,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):",n].join(`
|
|
206
|
+
`),buttons:k?void 0:d}:{label:"plan-approval",userMessage:y,planReviewSummary:h,wakeMessage:["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true)`].join(`
|
|
207
|
+
`)}}let b=e.multiTurn?"Multi-turn session":"Session";return{label:"waiting",userMessage:y,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:",n,"",`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(`
|
|
208
|
+
`),buttons:l}}var hd=3,Bm=180,Fm=4e3,Sd=32;function yd(){let t=wn(),e=Gm(t);if(e)return{async generateWorktreeDecisionSummary(n){if(typeof e.generateWorktreeDecisionSummary=="function")return await e.generateWorktreeDecisionSummary(n);if(typeof e.summarizeWorktreeDecision=="function")return await e.summarizeWorktreeDecision(n);let r=Hm(n);if(typeof e.generateObject=="function")return await e.generateObject({task:"openclaw-code-agent.worktree-decision-summary",prompt:r,input:n});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 qm(t){let e=[],n=t.changedFiles.slice(0,3).map(o=>`\`${o}\``);if(n.length>0){let o=t.changedFiles.length-n.length;e.push(o>0?`Touches ${n.join(", ")} and ${o} more file${o===1?"":"s"}`:`Touches ${n.join(", ")}`)}let r=[...new Set(t.commitMessages.map(o=>o.message.trim()).filter(Boolean))].slice(0,2);return r.length>0&&e.push(`Recent work: ${r.join("; ")}`),e}async function kd(t){let e=Km(t),n=qm(t.diffSummary??{changedFiles:e.changedFiles,commitMessages:e.commitSubjects.map(r=>({message:r}))});if(!t.provider)return{source:"fallback",lines:n,evidence:e,error:"LLM summary provider unavailable."};try{let r=await t.provider.generateWorktreeDecisionSummary(e),o=Um(r);return o.length>0?{source:"llm",lines:o,evidence:e}:{source:"fallback",lines:n,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:n,evidence:e,error:"LLM summary provider failed."}}}function Km(t){let e=t.diffSummary;return{sessionName:t.sessionName,objective:jm(t.prompt),stats:e?{commits:e.commits,filesChanged:e.filesChanged,insertions:e.insertions,deletions:e.deletions}:void 0,changedFiles:e?.changedFiles??[],commitSubjects:e?.commitMessages.map(n=>vd(n.message)).filter(Boolean).slice(0,8)??[],outputPreview:wd(Pd(t.outputPreview??""),Fm)}}function Um(t){let e=Vm(t),n=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.summary)?e.summary:void 0;if(!n||n.length===0||n.length>hd)return[];let r=n.map(o=>typeof o=="string"?vd(o):"").filter(Boolean);return r.length!==n.length?[]:r.some(o=>o.length>Bm)?[]:r.some(zm)?[]:r}function Vm(t){if(typeof t!="string")return t;let e=t.trim();if(e)try{return JSON.parse(e)}catch{return{summary:e.split(`
|
|
209
|
+
`).map(n=>n.replace(/^[-*âĸ]\s+/,"").trim()).filter(Boolean).slice(0,hd)}}}function Gm(t){return[t?.worktreeDecisionSummary,t?.llm,t?.ai,t?.model,t?.models].find(n=>!!(n&&typeof n=="object"&&(typeof n.generateWorktreeDecisionSummary=="function"||typeof n.summarizeWorktreeDecision=="function"||typeof n.generateObject=="function"||typeof n.generateText=="function"||typeof n.complete=="function")))}function Hm(t){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(t,null,2)].join(`
|
|
210
|
+
`)}function jm(t){let e=t?.replace(/\r\n/g,`
|
|
209
211
|
`).split(`
|
|
210
|
-
`).map(o=>o.trim()).filter(Boolean).join(" ");if(!e)return;let
|
|
211
|
-
`)}notifyAutoMergeConflictEscalation(e,r
|
|
212
|
-
`),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}updatePersistedSessionFor(e,
|
|
213
|
-
`)}),{notificationSent:!0,worktreeRemoved:!1}}handleAutoMergeSuccess(e,r,
|
|
214
|
-
|
|
215
|
-
(Pre-existing changes on ${o} were auto-stashed and restored.)`);let
|
|
216
|
-
`),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}async handleAutoMergeStrategy(e,r,n,o,i,a,u=ke(e)??e.harnessSessionId){this.deps.isAlreadyMerged(u)||e.autoMergeResolverSessionId||await this.deps.enqueueMerge(r,async()=>{if(this.deps.isAlreadyMerged(u))return;let p=this.deps.mergeBranch(r,o,i,"merge",n);if(p.success){this.handleAutoMergeSuccess(e,r,o,i,a,p);return}if(p.rebaseConflict){await this.handleInitialAutoMergeConflict(e,r,n,o,i,p.error);return}let d=p.dirtyError?`\u274C [${e.name}] Merge blocked: ${p.error}`:`\u274C [${e.name}] Merge failed: ${p.error??"unknown error"}`;if(e.worktreeState==="merge_conflict_resolving"||e.worktreeLifecycle?.state==="merge_conflict_resolving"){this.handleAutoMergeRetryFailure(e,o,n,d);return}this.deps.dispatchSessionNotification(e,{label:"worktree-merge-error",userMessage:d})},()=>{this.deps.dispatchSessionNotification(e,{label:"worktree-merge-queued",userMessage:`\u{1F550} [${e.name}] Merge queued \u2014 another merge for this repo is in progress. Will notify when complete.`})})}async handleAutoPrStrategy(e,r){return this.updatePersistedSessionFor(e,{lifecycle:"terminal",worktreeState:"pr_in_progress"}),(await this.deps.runAutoPr(e,r)).success||(this.markPendingDecision(e),this.deps.dispatchSessionNotification(e,{label:"worktree-auto-pr-failed",userMessage:`\u26A0\uFE0F [${e.name}] Auto-PR did not complete. The worktree is preserved for an explicit merge or PR decision.`,buttons:this.deps.getWorktreeDecisionButtons(e.id)})),{notificationSent:!0,worktreeRemoved:!1}}};import{existsSync as dR,writeFileSync as lR}from"fs";ir();import{randomUUID as _T}from"crypto";function DT(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}var na=class{constructor(e,r){this.onChange=e;this.retentionMs=r}onChange;retentionMs;tokens=new Map;afterChange;replaceAll(e){this.tokens.clear();for(let r of e)this.tokens.set(r.id,r)}clear(){this.tokens.clear(),this.notifyChanged()}listForPersistence(){return[...this.tokens.values()]}createActionToken(e,r,n={}){let o={id:_T(),sessionId:e,kind:r,createdAt:Date.now(),...n};return this.tokens.set(o.id,o),this.notifyChanged(),o}getActionToken(e){let r=this.tokens.get(e);if(r){if(r.expiresAt!=null&&r.expiresAt<=Date.now()){this.tokens.delete(e),this.notifyChanged();return}return r}}consumeActionToken(e){let r=this.getActionToken(e);if(!(!r||r.consumedAt!=null))return r.consumedAt=Date.now(),this.notifyChanged(),r}deleteActionTokensForSession(e){let r=!1;for(let[n,o]of this.tokens)o.sessionId===e&&(this.tokens.delete(n),r=!0);r&&this.notifyChanged()}deletePlanDecisionTokensForSession(e,r){let n=!1;for(let[o,i]of this.tokens)i.sessionId!==e||!DT(i.kind)||r!=null&&i.planDecisionVersion===r||(this.tokens.delete(o),n=!0);n&&this.notifyChanged()}purgeExpiredActionTokens(e=Date.now()){let r=!1;for(let[n,o]of this.tokens){let i=o.expiresAt!=null&&o.expiresAt<=e,a=o.consumedAt!=null&&e-o.consumedAt>this.retentionMs;(i||a)&&(this.tokens.delete(n),r=!0)}r&&this.notifyChanged()}nextExpiryAt(){let e;for(let r of this.tokens.values()){let n=[r.expiresAt,r.consumedAt!=null?r.consumedAt+this.retentionMs:void 0].filter(o=>o!=null&&Number.isFinite(o));for(let o of n)(e==null||o<e)&&(e=o)}return e}setAfterChangeListener(e){this.afterChange=e}notifyChanged(){this.onChange(),this.afterChange?.()}};Ee();Ee();var oa=class{constructor(e){this.indexes=e}indexes;hasRecordedSession(e){return this.indexes.idIndex.has(e)}getLatestPersistedByName(e){let r,n=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,a=0;for(let u of this.indexes.persisted.values()){if(u.name!==e){a++;continue}let p=u.createdAt??Number.NEGATIVE_INFINITY,d=u.completedAt??Number.NEGATIVE_INFINITY;(p>n||p===n&&d>o||p===n&&d===o&&a>i)&&(r=u,n=p,o=d,i=a),a++}return r}resolveBackendConversationId(e,r){if(r)return r;let n=this.indexes.idIndex.get(e);if(n){let a=this.indexes.persisted.get(n);return(a?q(a):void 0)??n}let o=this.getLatestPersistedByName(e);if(o)return q(o)??o.harnessSessionId;let i=this.indexes.backendIdIndex.get(e);if(i){let a=this.indexes.persisted.get(i);return(a?q(a):void 0)??i}if(this.indexes.persisted.has(e)){let a=this.indexes.persisted.get(e);return a?q(a)??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,r){return this.resolveBackendConversationId(e,r)}getPersistedSession(e){let r=this.indexes.idIndex.get(e);if(r)return this.indexes.persisted.get(r);let n=this.getLatestPersistedByName(e);if(n)return n;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,r)=>(r.completedAt??0)-(e.completedAt??0))}};import{existsSync as iR,mkdirSync as sR,readFileSync as aR,readdirSync as td,renameSync as bg,statSync as Ag,unlinkSync as Tg,writeFileSync as Rg}from"fs";import{tmpdir as rd}from"os";import{dirname as uR,join as ua}from"path";import{homedir as LT}from"node:os";import{join as FT}from"node:path";function Sg(t){let e=t.OPENCLAW_HOME?.trim();if(e)return e;let r=t.HOME?.trim()||LT();return FT(r,".openclaw")}ir();var ia=6,NT=new Set(["running","completed","failed","killed"]);function Xo(t){return!!t&&typeof t=="object"}function Qn(t,e=""){return typeof t=="string"&&t.trim().length>0?t:e}function w(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function gt(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function qT(t){return typeof t=="string"&&tf.has(t)?t:void 0}function Ig(t){return t==="default"||t==="plan"||t==="bypassPermissions"?t:void 0}function BT(t){return t==="never"||t==="on-request"?"never":void 0}function WT(t){return t==="approve"||t==="ask"||t==="delegate"?t:void 0}function UT(t){if(t==="plan-mode"||t==="codex-first-turn-plan"||t==="soft-plan")return"plan-mode"}function xg(t){return typeof t=="string"&&Cs.has(t)?t:void 0}function KT(t){return t==="user"||t==="idle-timeout"||t==="startup-timeout"||t==="shutdown"||t==="done"||t==="unknown"?t:void 0}function jT(t){return t==="starting"||t==="active"||t==="awaiting_plan_decision"||t==="awaiting_user_input"||t==="awaiting_worktree_decision"||t==="suspended"||t==="terminal"?t:void 0}function GT(t){return t==="not_required"||t==="pending"||t==="approved"||t==="changes_requested"||t==="rejected"?t:void 0}function VT(t){return t==="none"||t==="provisioned"||t==="pending_decision"||t==="merge_conflict_resolving"||t==="merge_in_progress"||t==="pr_in_progress"||t==="merged"||t==="released"||t==="pr_open"||t==="dismissed"||t==="cleanup_failed"?t:void 0}function HT(t){return t==="none"||t==="provisioned"||t==="pending_decision"||t==="merge_conflict_resolving"||t==="pr_open"||t==="merged"||t==="released"||t==="dismissed"||t==="no_change"||t==="cleanup_failed"?t:void 0}function zT(t){return t==="live"||t==="stopped"?t:void 0}function JT(t){return t==="not_sent"||t==="sending"||t==="delivered"||t==="fallback_delivered"||t==="failed"?t:void 0}function QT(t){return t==="direct-telegram"?"direct-message":t==="none"||t==="direct-message"||t==="wake-only"?t:void 0}function YT(t){return t==="none"||t==="canonical_buttons"||t==="explicit_fallback_text"?t:void 0}function ZT(t){return t==="idle"||t==="notifying"||t==="wake_pending"||t==="failed"?t:void 0}function XT(t){return t==="awaiting_plan_output"||t==="awaiting_approval"||t==="approved_then_implemented"||t==="implemented_without_required_approval"||t==="not_plan_gated"?t:void 0}function eR(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"||t==="plan-offer-start"||t==="plan-offer-dismiss"||t==="worktree-merge"||t==="worktree-create-pr"||t==="worktree-update-pr"||t==="worktree-view-pr"||t==="worktree-decide-later"||t==="worktree-dismiss"||t==="session-resume"||t==="session-restart"||t==="view-output"||t==="question-answer"?t:void 0}function Pg(t){if(!Xo(t))return;let e=w(t.provider),r=w(t.accountId),n=w(t.target),o=w(t.threadId),i=w(t.sessionKey);if(!(!e||!n))return{provider:e,accountId:r,target:n,threadId:o,sessionKey:i}}function tR(t,e,r){if(Xo(t)){let n=w(t.kind),o=w(t.conversationId);if(o&&(n==="claude-code"||n==="codex-app-server"))return{kind:n,conversationId:o,runId:w(t.runId),worktreeId:w(t.worktreeId),worktreePath:w(t.worktreePath)}}if(e==="claude-code")return{kind:"claude-code",conversationId:r}}function rR(t){if(!Xo(t))return;let e=HT(t.state),r=w(t.updatedAt);if(!e||!r)return;let n=w(t.resolutionSource);return{state:e,updatedAt:r,resolvedAt:w(t.resolvedAt),resolutionSource:n==="agent_merge"||n==="agent_pr"||n==="strategy_no_change"||n==="lifecycle_resolver"||n==="dismiss"||n==="maintenance"?n:void 0,baseBranch:w(t.baseBranch),targetRepo:w(t.targetRepo),pushRemote:w(t.pushRemote),notes:Array.isArray(t.notes)?t.notes.filter(o=>typeof o=="string"&&o.length>0):void 0}}function nR(t){let e=new Date(0).toISOString(),r=w(t.worktreeMergedAt)??w(t.worktreeDismissedAt)??w(t.pendingWorktreeDecisionSince)??e;if(t.worktreeMerged===!0)return{state:"merged",updatedAt:r,resolvedAt:w(t.worktreeMergedAt)??r,resolutionSource:"agent_merge",baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(t.worktreeDisposition==="dismissed")return{state:"dismissed",updatedAt:r,resolvedAt:w(t.worktreeDismissedAt)??r,resolutionSource:"dismiss",baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(t.worktreeDisposition==="no-change-cleaned")return{state:"no_change",updatedAt:r,resolvedAt:r,resolutionSource:"strategy_no_change",baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(t.worktreeDisposition==="pr-opened"||t.worktreeState==="pr_open")return{state:"pr_open",updatedAt:r,baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(t.pendingWorktreeDecisionSince||t.worktreeState==="pending_decision")return{state:"pending_decision",updatedAt:r,baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(t.worktreeState==="merge_conflict_resolving")return{state:"merge_conflict_resolving",updatedAt:r,baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(w(t.worktreePath)||w(t.worktreeBranch))return{state:"provisioned",updatedAt:r,baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)}}function oR(t){if(typeof t=="string"&&NT.has(t))return t==="running"?"killed":t}function wg(t){if(!Xo(t))return;let e=Qn(t.harnessSessionId);if(!e)return;let r=oR(t.status);if(!r)return;let n=t.status==="running",o=w(t.worktreePath),i=w(t.worktreeBranch),a=w(t.originChannel),u=typeof t.originThreadId=="string"||typeof t.originThreadId=="number"?t.originThreadId:void 0,p=w(t.originSessionKey),d=Pg(t.route);if(!d)return;let l=en({route:d,originChannel:a,originThreadId:u,originSessionKey:p});if(!l||o&&!i)return;let m=w(t.harness),c=tR(t.backendRef,m,e),h=rR(t.worktreeLifecycle)??nR(t),y=w(t.completionWakeSucceededAt),k=w(t.completionWakeSkippedAt),S=t.completionWakeSummaryRequired===!0&&!k?!0:void 0;return{sessionId:w(t.sessionId),harnessSessionId:e,backendRef:c,name:Qn(t.name,e),prompt:Qn(t.prompt),workdir:Qn(t.workdir,"(unknown)"),model:w(t.model),reasoningEffort:qT(t.reasoningEffort),fastMode:t.fastMode===!0?!0:void 0,createdAt:gt(t.createdAt),completedAt:gt(t.completedAt),status:r,lifecycle:n?"suspended":jT(t.lifecycle),approvalState:GT(t.approvalState),worktreeState:VT(t.worktreeState),runtimeState:n?"stopped":zT(t.runtimeState),deliveryState:ZT(t.deliveryState),completionWakeIssuedAt:w(t.completionWakeIssuedAt),completionWakeSucceededAt:y,completionWakeFailedAt:w(t.completionWakeFailedAt),completionWakeSkippedAt:k,completionWakeSkipReason:w(t.completionWakeSkipReason),completionWakeSummaryRequired:S,killReason:KT(t.killReason),costUsd:typeof t.costUsd=="number"&&Number.isFinite(t.costUsd)?t.costUsd:0,originAgentId:w(t.originAgentId),originChannel:a,originThreadId:u,originSessionKey:p,route:l,outputPath:w(t.outputPath),harness:m,goalTaskId:w(t.goalTaskId),requestedPermissionMode:Ig(t.requestedPermissionMode),currentPermissionMode:Ig(t.currentPermissionMode),approvalExecutionState:XT(t.approvalExecutionState),approvalRationale:w(t.approvalRationale),planModeApproved:t.planModeApproved===!0,pendingPlanApproval:t.pendingPlanApproval===!0,planApprovalContext:UT(t.planApprovalContext),planDecisionVersion:gt(t.planDecisionVersion),actionablePlanDecisionVersion:gt(t.actionablePlanDecisionVersion),canonicalPlanPromptVersion:gt(t.canonicalPlanPromptVersion),approvalPromptRequiredVersion:gt(t.approvalPromptRequiredVersion),approvalPromptVersion:gt(t.approvalPromptVersion),approvalPromptStatus:JT(t.approvalPromptStatus),approvalPromptTransport:QT(t.approvalPromptTransport),approvalPromptMessageKind:YT(t.approvalPromptMessageKind),approvalPromptLastAttemptAt:w(t.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:w(t.approvalPromptDeliveredAt),approvalPromptFailedAt:w(t.approvalPromptFailedAt),planApproval:WT(t.planApproval),codexApprovalPolicy:BT(t.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:xg(t.worktreeStrategy),worktreeMerged:typeof t.worktreeMerged=="boolean"?t.worktreeMerged:void 0,worktreeMergedAt:w(t.worktreeMergedAt),worktreePrUrl:w(t.worktreePrUrl),worktreePrNumber:gt(t.worktreePrNumber),pendingWorktreeDecisionSince:w(t.pendingWorktreeDecisionSince),lastWorktreeReminderAt:w(t.lastWorktreeReminderAt),worktreeBaseBranch:w(t.worktreeBaseBranch),worktreePrTargetRepo:w(t.worktreePrTargetRepo),autoMergeParentSessionId:w(t.autoMergeParentSessionId),autoMergeConflictResolutionAttemptCount:gt(t.autoMergeConflictResolutionAttemptCount),autoMergeResolverSessionId:w(t.autoMergeResolverSessionId),worktreePushRemote:w(t.worktreePushRemote),worktreeDecisionSnoozedUntil:w(t.worktreeDecisionSnoozedUntil),worktreeDisposition:t.worktreeDisposition==="active"||t.worktreeDisposition==="pr-opened"||t.worktreeDisposition==="merged"||t.worktreeDisposition==="dismissed"||t.worktreeDisposition==="no-change-cleaned"?t.worktreeDisposition:void 0,worktreeDismissedAt:w(t.worktreeDismissedAt),worktreeLifecycle:h,resumable:n?!0:t.resumable===!0}}function vg(t){if(!Xo(t))return;let e=eR(t.kind),r=Qn(t.id),n=Qn(t.sessionId),o=gt(t.createdAt);if(!(!r||!n||!e||o==null))return{id:r,sessionId:n,kind:e,createdAt:o,planDecisionVersion:gt(t.planDecisionVersion),expiresAt:gt(t.expiresAt),consumedAt:gt(t.consumedAt),optionIndex:gt(t.optionIndex),label:w(t.label),targetUrl:w(t.targetUrl),route:Pg(t.route),launchName:w(t.launchName),launchPrompt:w(t.launchPrompt),launchWorkdir:w(t.launchWorkdir),launchWorktreeStrategy:xg(t.launchWorktreeStrategy)}}function sa(t){if(!t.backendRef?.kind||!t.backendRef.conversationId)throw new Error(`Persisted session ${t.harnessSessionId} is missing required backend ref metadata.`);if(!t.route?.provider||!t.route.target)throw new Error(`Persisted session ${t.harnessSessionId} is missing required route metadata.`);if(t.worktreePath&&!t.worktreeBranch)throw new Error(`Persisted session ${t.harnessSessionId} is missing required worktreeBranch metadata.`)}function ed(t){return!!t&&typeof t=="object"}function nd(t){return t instanceof Error?t.message:String(t)}function Cg(t){let e=t.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||ua(Sg(t),"code-agent-sessions.json")}function Eg(t,e,r){try{sR(uR(t),{recursive:!0});let n=t+".tmp";Rg(n,JSON.stringify({schemaVersion:ia,sessions:e,actionTokens:r},null,2),"utf-8"),bg(n,t)}catch(n){console.warn(`[SessionStore] Failed to save session index: ${nd(n)}`)}}function aa(t,e){try{if(!iR(t))return;let r=`${t}.legacy-${Date.now()}.json`;bg(t,r),console.warn(`[SessionStore] Breaking upgrade: archived ${e} session store to ${r}. Legacy sessions are not loaded by this release.`)}catch(r){console.warn(`[SessionStore] Failed to archive legacy session store: ${nd(r)}`)}}function pR(t,e){try{if(e.length===0)return;let r=`${t}.codex-sdk-legacy-${Date.now()}.json`;Rg(r,JSON.stringify(e,null,2),"utf-8"),console.warn(`[SessionStore] Breaking Codex transport upgrade: archived ${e.length} legacy Codex SDK session(s) to ${r}. They are not loaded by the App Server backend.`)}catch(r){console.warn(`[SessionStore] Failed to archive legacy Codex SDK sessions: ${nd(r)}`)}}function $g(t,e){try{let r=rd(),n=td(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n)try{let i=ua(r,o),a=Ag(i).mtimeMs;t-a>e&&Tg(i)}catch{}}catch{}}function Mg(t,e){try{let r=rd(),n=td(r).filter(i=>i.startsWith("openclaw-agent-")&&i.endsWith(".txt")),o;for(let i of n)try{let a=ua(r,i),u=Ag(a).mtimeMs+e;if(u<=t)return t;o=o==null?u:Math.min(o,u)}catch{}return o}catch{return}}function Og(t){try{let e=new Set(t),r=rd(),n=td(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n){let i=ua(r,o);if(!e.has(i))try{Tg(i)}catch{}}}catch{}}function _g(t){let{indexPath:e,clearAll:r,indexPersistedEntry:n,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:a}=t;try{let u=aR(e,"utf-8"),p=JSON.parse(u);if(Array.isArray(p)){aa(e,"legacy array store"),a();return}if(!ed(p)||p.schemaVersion!==ia&&p.schemaVersion!==4){aa(e,`schema mismatch (expected v${ia})`),a();return}let d=Array.isArray(p.sessions)?p.sessions:[],l=[];for(let c of d){if(ed(c)&&c.harness==="codex"){let y=ed(c.backendRef)?c.backendRef:void 0;if((typeof y?.kind=="string"?y.kind:void 0)!=="codex-app-server"){l.push(c);continue}}let h=wg(c);if(!h){r(),aa(e,"invalid v4 session entry"),a();return}n(h)}l.length>0&&(pR(e,l),a());let m=Array.isArray(p.actionTokens)?p.actionTokens:[];for(let c of m){let h=vg(c);if(!h){r(),aa(e,"invalid v4 action token"),a();return}o(h)}i()}catch{}}var mR=new Set(["completed","failed","killed"]),od=1440*60*1e3;function cR(t){return t instanceof Error?t.message:String(t)}var pa=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;backendIdIndex=new Map;actionTokens;actionTokenStore;indexPath;queries;constructor(e={}){let r=e.env??process.env;this.indexPath=e.indexPath??Cg(r),this.actionTokenStore=new na(()=>this.saveIndex(),od),this.actionTokens=this.actionTokenStore.tokens,this.queries=new oa({persisted:this.persisted,idIndex:this.idIndex,nameIndex:this.nameIndex,backendIdIndex:this.backendIdIndex}),r.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){_g({indexPath:this.indexPath,clearAll:()=>{this.persisted.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)},purgeExpiredActionTokens:()=>this.actionTokenStore.purgeExpiredActionTokens(),saveIndex:()=>this.saveIndex()})}saveIndex(){Eg(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(e){sa(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){return e.backendRef??{kind:pp(e)==="codex"?"codex-app-server":"claude-code",conversationId:e.harnessSessionId}}indexPersistedEntry(e){let r=this.getEntryStorageKey(e);this.persisted.set(r,e),e.sessionId&&this.idIndex.set(e.sessionId,r),e.name&&this.nameIndex.set(e.name,r);let n=q(e);n&&this.backendIdIndex.set(n,r)}removePersistedIndexes(e){let r=this.getEntryStorageKey(e);this.persisted.delete(r);for(let[n,o]of this.idIndex)o===r&&this.idIndex.delete(n);for(let[n,o]of this.nameIndex)o===r&&this.nameIndex.delete(n);for(let[n,o]of this.backendIdIndex)o===r&&this.backendIdIndex.delete(n)}markRunning(e){if(!e.harnessSessionId)return;let r=typeof e.controlStateSnapshot=="function"?e.controlStateSnapshot():{planModeApproved:!1},n=en({route:e.route,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey});if(!n)return;let o={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,deliveryState:e.deliveryState,costUsd:0,originAgentId:e.originAgentId,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey,route:n,harness:e.harnessName,requestedPermissionMode:e.requestedPermissionMode,currentPermissionMode:e.currentPermissionMode,approvalExecutionState:e.approvalExecutionState,approvalRationale:e.approvalRationale,planModeApproved:r.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,worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeStrategy:e.worktreeStrategy,worktreeBaseBranch:e.worktreeBaseBranch,worktreePrTargetRepo:e.worktreePrTargetRepo,autoMergeParentSessionId:e.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:e.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:e.autoMergeResolverSessionId,worktreeLifecycle:e.worktreeLifecycle,resumable:e.isExplicitlyResumable};sa(o),this.indexPersistedEntry(o),this.saveIndex()}hasRecordedSession(e){return this.queries.hasRecordedSession(e)}persistTerminal(e){if(!e.harnessSessionId)return;let r=typeof e.controlStateSnapshot=="function"?e.controlStateSnapshot():{planModeApproved:!1},n=en({route:e.route,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey});if(!n)return;let o;try{let a=Wn(e.id);if(dR(a))o=a;else{let u=e.getOutput().join(`
|
|
217
|
-
`);u.length>0&&(lR(a,u,"utf-8"),o=a)}}catch(a){console.warn(`[SessionStore] Failed to write output file for session ${e.id}: ${cR(a)}`)}let i={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,deliveryState:e.deliveryState,killReason:e.killReason,costUsd:e.costUsd,originAgentId:e.originAgentId,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey,route:n,outputPath:o,harness:e.harnessName,goalTaskId:e.goalTaskId,requestedPermissionMode:e.requestedPermissionMode,currentPermissionMode:e.currentPermissionMode,approvalExecutionState:e.approvalExecutionState,approvalRationale:e.approvalRationale,planModeApproved:r.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,worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeStrategy:e.worktreeStrategy,worktreeBaseBranch:e.worktreeBaseBranch,worktreePrTargetRepo:e.worktreePrTargetRepo,autoMergeParentSessionId:e.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:e.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:e.autoMergeResolverSessionId,worktreeLifecycle:e.worktreeLifecycle,resumable:e.isExplicitlyResumable};sa(i),this.indexPersistedEntry(i),this.saveIndex()}getLatestPersistedByName(e){return this.queries.getLatestPersistedByName(e)}resolveBackendConversationId(e,r){return this.queries.resolveBackendConversationId(e,r)}resolveHarnessSessionId(e,r){return this.queries.resolveHarnessSessionId(e,r)}getPersistedSession(e){return this.queries.getPersistedSession(e)}listPersistedSessions(){return this.queries.listPersistedSessions()}cleanupTmpOutputFiles(e){this.actionTokenStore.purgeExpiredActionTokens(e),$g(e,od)}getNextTmpOutputCleanupAt(e){return Mg(e,od)}evictOldestPersisted(e){let r=this.listPersistedSessions();if(r.length<=e)return[];let n=r.slice(e);for(let o of n)this.removePersistedIndexes(o);return this.saveIndex(),n}shouldGcActiveSession(e,r,n){return!e.completedAt||!mR.has(e.status)?!1:r-e.completedAt>n}getActionToken(e){return this.actionTokenStore.getActionToken(e)}consumeActionToken(e){return this.actionTokenStore.consumeActionToken(e)}deleteActionTokensForSession(e){this.actionTokenStore.deleteActionTokensForSession(e)}purgeExpiredActionTokens(e=Date.now()){this.actionTokenStore.purgeExpiredActionTokens(e)}getNextActionTokenExpiry(){return this.actionTokenStore.nextExpiryAt()}onActionTokensChanged(e){this.actionTokenStore.setAfterChangeListener(e)}hasOutputPathReference(e){for(let r of this.persisted.values())if(r.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(){Og(this.getReferencedOutputPaths())}};var fR=new Set(["completed","failed","killed"]),da=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 r=e.costUsd??0,n=e.status;this.metrics.totalCostUsd+=r;let o=new Date(e.completedAt??e.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+r),fR.has(n)&&this.metrics.sessionsByStatus[n]++,e.completedAt){let i=e.completedAt-e.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||r>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:e.id,name:e.name,costUsd:r,prompt:Qe(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 Fg from"child_process";var Dg=5e3,gR=64,hR={primary:"primary",success:"success",positive:"success",danger:"danger",destructive:"danger",negative:"danger"},yR={execFile:Fg.execFile},Rr=class extends Error{constructor(e){super(e),this.name="MissingRuntimeDirectNotificationCapabilityError"}},la=class{constructor(e=yR.execFile){this.execFile=e}execFile;async send(e,r,n){ie("direct_send_started",{...$t(e),messageTextLength:r.length,...Pe(n)});try{await this.sendViaRuntime(e,r,n),ie("direct_send_succeeded",{...$t(e),deliveryPath:"runtime",...Pe(n)});return}catch(o){if(!(o instanceof Rr))throw ie("direct_send_failed",{...$t(e),deliveryPath:"runtime",...Pe(n),error:id(o)}),o;ie("direct_send_runtime_capability_missing",{...$t(e),deliveryPath:"runtime",...Pe(n),reason:o.message}),await this.sendViaBoundedCliFallback(e,r,n,o.message),ie("direct_send_succeeded",{...$t(e),deliveryPath:"cli-fallback",...Pe(n)})}}async sendViaRuntime(e,r,n){let o=rs(),i=hc(),a=o?.channel?.outbound?.loadAdapter;if(!o)throw new Rr("OpenClaw plugin runtime is unavailable for direct notification delivery");if(i==null)throw new Rr("OpenClaw runtime config snapshot is unavailable for direct notification delivery");if(!o.channel)throw new Rr(`OpenClaw plugin runtime channel surface is unavailable for direct notification delivery (runtimeVersion=${sd(o)})`);if(!o.channel.outbound)throw new Rr(`OpenClaw plugin runtime channel outbound surface is unavailable for direct notification delivery (runtimeVersion=${sd(o)})`);if(!a)throw new Rr(`OpenClaw plugin runtime channel outbound loadAdapter is unavailable for direct notification delivery (runtimeVersion=${sd(o)})`);let u=await a(e.channel);if(!u)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" is unavailable`);let p=ma(n);if(ie("runtime_adapter_loaded",{...$t(e),adapterHasRenderPresentation:typeof u.renderPresentation=="function",adapterHasSendPayload:typeof u.sendPayload=="function",adapterHasSendText:typeof u.sendText=="function",...Pe(n),...p?_p(p):{}}),p){await this.sendPresentation(u,i,e,r,p);return}if(!u.sendText)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" cannot send text`);await u.sendText({cfg:i,to:e.target,text:r,accountId:e.accountId,threadId:e.threadId})}async sendPresentation(e,r,n,o,i){let a=SR(i),u={text:o,presentation:i,interactive:a};ie("presentation_render_started",{...$t(n),messageTextLength:o.length,adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",..._p(i)});let p={cfg:r,to:n.target,text:o,payload:u,accountId:n.accountId,threadId:n.threadId},d=e.renderPresentation?await e.renderPresentation({payload:u,presentation:i,ctx:p}):u,l=xR(d,a,n.channel);if(ie("presentation_render_completed",{...$t(n),adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...Dp(l)}),!l||typeof l!="object"||!e.sendPayload)throw new Error(`OpenClaw outbound adapter for channel "${n.channel}" cannot preserve interactive presentation`);let m=await e.sendPayload({...p,payload:l});ie("presentation_send_payload_completed",{...$t(n),...Dp(l),...Tf(m)})}sendViaBoundedCliFallback(e,r,n,o){return new Promise((i,a)=>{let u=kR(e,r,n);ie("direct_send_cli_fallback_started",{...$t(e),deliveryPath:"cli-fallback",reason:o,messageTextLength:r.length,...Pe(n)}),this.execFile("openclaw",u,{timeout:Dg,killSignal:"SIGKILL"},(p,d,l)=>{if(!p){ie("direct_send_cli_fallback_completed",{...$t(e),deliveryPath:"cli-fallback",...Pe(n)}),i();return}let m=l?.trim()?` | stderr: ${l.trim()}`:"";ie("direct_send_cli_fallback_failed",{...$t(e),deliveryPath:"cli-fallback",...Pe(n),error:id(p),stderrLength:l?.length}),a(new Error(`${o}; bounded openclaw message send fallback failed within ${Dg}ms timeout: ${id(p)}${m}`))})})}};function $t(t){return{channel:t.channel,target:t.target,accountId:t.accountId,threadId:t.threadId,sessionKey:t.sessionKey}}function kR(t,e,r){let n=ma(r),o=["message","send","--channel",t.channel,"--target",t.target,"--message",e];return t.accountId&&o.push("--account",t.accountId),t.threadId&&o.push("--thread-id",t.threadId),n&&o.push("--presentation",JSON.stringify(n)),o}function id(t){return t instanceof Error?t.message:String(t)}function sd(t){if(!t||typeof t!="object")return"unknown";let e=t.version;return typeof e=="string"&&e.trim()?e:"unknown"}function ma(t){let e=(t??[]).filter(r=>Array.isArray(r)&&r.length>0).map(r=>({type:"buttons",buttons:r.map(n=>({label:n.label,value:AR(n.callbackData),...n.style?{style:n.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function SR(t){let e=t.blocks.filter(r=>r.type==="buttons"&&r.buttons.length>0).map(r=>({type:"buttons",buttons:r.buttons.map(n=>({label:n.label,value:n.value,...n.style?{style:n.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function IR(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t.interactive;if(!e||typeof e!="object"||Array.isArray(e))return!1;let r=e.blocks;return Array.isArray(r)&&r.some(n=>{if(!n||typeof n!="object"||Array.isArray(n))return!1;let o=n;return o.type==="buttons"&&Array.isArray(o.buttons)&&o.buttons.length>0})}function xR(t,e,r){if(!e)return t;let n=IR(t)?t:PR(t,e);return r!=="telegram"?n:wR(n,e)}function PR(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:{...t,interactive:e}}function wR(t,e){if(!t||typeof t!="object"||Array.isArray(t))return t;let r=t,n=Lg(r.channelData),o=Lg(n?.telegram),i=bR(o?.buttons);if(i)return{...r,channelData:{...n??{},telegram:{...o??{},buttons:i}}};let a=vR(e);return a?{...r,channelData:{...n??{},telegram:{...o??{},buttons:a}}}:t}function vR(t){let e=t.blocks.filter(r=>r.type==="buttons"&&r.buttons.length>0).map(r=>r.buttons.filter(n=>typeof n.value=="string"&&n.value.trim().length>0&&Buffer.byteLength(n.value,"utf8")<=gR).map(n=>({text:n.label,callback_data:n.value,...Ng(n.style)}))).filter(r=>r.length>0);return e.length>0?e:void 0}function bR(t){if(!Array.isArray(t))return;let e=t.map(r=>Array.isArray(r)?r.map(n=>{if(!n||typeof n!="object"||Array.isArray(n))return;let{style:o,...i}=n;if(!(typeof i.text!="string"||i.text.trim().length===0))return{...i,...Ng(o)}}).filter(n=>!!n):[]).filter(r=>r.length>0);return e.length>0?e:void 0}function Ng(t){if(typeof t!="string")return{};let e=t.trim().toLowerCase(),r=hR[e];return r?{style:r}:{}}function Lg(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function AR(t){return t.startsWith(`${wt}:`)?t:`${wt}:${t}`}import*as qg from"child_process";var Yn=class{tails=new Map;enqueue(e,r,n){let o=this.tails.get(e);o!==void 0&&n?.();let a=(o?.catch(()=>{})??Promise.resolve()).then(()=>r()),u=a.catch(()=>{});return this.tails.set(e,u),u.finally(()=>{this.tails.get(e)===u&&this.tails.delete(e)}),a}clear(){this.tails.clear()}};var ad=3e4,TR=2e3,RR=2e4,ht=4;function ei(t){return t instanceof Error?t.message:String(t)}function CR(){return new Error(`Dispatch timed out after ${ad}ms`)}function ER(t){if(!(t instanceof Error))return!1;let e=t;return e.killed===!0&&e.signal==="SIGKILL"}var $R={execFile:qg.execFile},ca=class{pendingRetryTimers=new Map;orderedDispatches=new Yn;disposed=!1;clearPendingRetries(){for(let e of this.pendingRetryTimers.values())for(let r of e)clearTimeout(r.timer),r.onCleared?.();this.pendingRetryTimers.clear()}clearRetryTimersForSession(e){let r=this.pendingRetryTimers.get(e);if(r){for(let n of r)clearTimeout(n.timer),n.onCleared?.();this.pendingRetryTimers.delete(e)}}dispose(){this.disposed=!0,this.clearPendingRetries(),this.orderedDispatches.clear()}execute(e,r,n=1){if(!this.disposed){if(n===1&&r.orderingKey){this.enqueueOrderedDispatch(r.orderingKey,o=>this.executeNow(e,r,o,n));return}this.executeNow(e,r,void 0,n)}}executePromise(e,r,n=1){if(!this.disposed){if(n===1&&r.orderingKey){this.enqueueOrderedDispatch(r.orderingKey,o=>this.executePromiseNow(e,r,o,n));return}this.executePromiseNow(e,r,void 0,n)}}executeNow(e,r,n,o=1){if(this.disposed||r.shouldContinue?.()===!1){n?.();return}let i=Date.now();o===1&&r.onStarted?.(),this.log("info","dispatch_started",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:ht}),$R.execFile("openclaw",e,{timeout:ad,killSignal:"SIGKILL"},(a,u,p)=>{if(this.disposed){n?.();return}let d=Date.now()-i;if(!a){let y=r.successValidator?.(u??"");if(y?.outcome==="failure"){this.log("error","dispatch_success_validation_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:d,error:y.reason,terminal:!0}),r.onFinalFailure?.(),n?.();return}if(y?.outcome==="skipped"){this.log("info","dispatch_skipped",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:d,reason:y.reason}),r.shouldContinue?.()!==!1&&r.onSkipped?.(y.reason),n?.();return}this.log("info","dispatch_succeeded",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:d}),r.shouldContinue?.()!==!1&&r.onSuccess?.(),n?.();return}let l=p?.trim()?` | stderr: ${p.trim()}`:"";if(r.target==="message.send"&&ER(a)){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:d,error:`${ei(a)}${l}`,terminal:!0,ambiguousResult:!0}),r.onAmbiguousResult?.(),n?.();return}if(o>=ht||r.terminalOnFailure===!0){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:d,error:`${ei(a)}${l}`,terminal:!0}),r.onFinalFailure?.(),n?.();return}let c=this.retryDelayMs(o);this.log("error","dispatch_retry_scheduled",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:d,retryDelayMs:c,error:`${ei(a)}${l}`});let h={timer:setTimeout(()=>{let y=this.pendingRetryTimers.get(r.sessionId);if(y&&(y.delete(h),y.size===0&&this.pendingRetryTimers.delete(r.sessionId)),r.shouldContinue?.()===!1){n?.();return}this.executeNow(e,r,n,o+1)},c),onCleared:n};h.timer.unref?.(),this.pendingRetryTimers.has(r.sessionId)||this.pendingRetryTimers.set(r.sessionId,new Set),this.pendingRetryTimers.get(r.sessionId).add(h)})}executePromiseNow(e,r,n,o=1){if(this.disposed||r.shouldContinue?.()===!1){n?.();return}let i=Date.now();o===1&&r.onStarted?.(),this.log("info","dispatch_started",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:ht}),this.executePromiseWithTimeout(e).then(()=>{if(this.disposed){n?.();return}let a=Date.now()-i;this.log("info","dispatch_succeeded",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:a}),r.shouldContinue?.()!==!1&&r.onSuccess?.(),n?.()}).catch(a=>{if(this.disposed){n?.();return}let u=Date.now()-i;if(o>=ht||r.terminalOnFailure===!0){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:u,error:ei(a),terminal:!0,...r.terminalOnFailure===!0&&o<ht?{terminalReason:"non_retryable"}:{}}),r.onFinalFailure?.(),n?.();return}let p=this.retryDelayMs(o);this.log("error","dispatch_retry_scheduled",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:u,retryDelayMs:p,error:ei(a)});let d={timer:setTimeout(()=>{let l=this.pendingRetryTimers.get(r.sessionId);if(l&&(l.delete(d),l.size===0&&this.pendingRetryTimers.delete(r.sessionId)),r.shouldContinue?.()===!1){n?.();return}this.executePromiseNow(e,r,n,o+1)},p),onCleared:n};d.timer.unref?.(),this.pendingRetryTimers.has(r.sessionId)||this.pendingRetryTimers.set(r.sessionId,new Set),this.pendingRetryTimers.get(r.sessionId).add(d)})}executePromiseWithTimeout(e){return new Promise((r,n)=>{let o=!1,i=setTimeout(()=>{o||(o=!0,n(CR()))},ad);i.unref?.(),Promise.resolve().then(e).then(()=>{o||(o=!0,clearTimeout(i),r())}).catch(a=>{o||(o=!0,clearTimeout(i),n(a))})})}retryDelayMs(e){let r=Math.max(0,e-1),n=TR*2**r;return Math.min(n,RR)}enqueueOrderedDispatch(e,r){this.orderedDispatches.enqueue(e,async()=>{this.disposed||await new Promise(n=>{let o=!1;r(()=>{o||(o=!0,n())})})})}log(e,r,n){let o=`[WakeDispatcher] ${JSON.stringify({event:r,...n})}`;if(e==="error"){console.error(o);return}console.info(o)}};ir();var fa=class{resolve(e){let r=$n(e);if(!(!r?.provider||!r.target))return{channel:r.provider,target:r.target,accountId:r.accountId,threadId:r.threadId,sessionKey:r.sessionKey}}summary(e){if(!e)return"system";let r=e.accountId?`|${e.accountId}`:"",n=e.threadId?`#${e.threadId}`:"";return`${e.channel}${r}|${e.target}${n}`}};import{randomUUID as MR}from"crypto";var ga=class{constructor(e={}){this.options=e}options;buildChatSendArgs(e,r,n){return["gateway","call","chat.send","--expect-final","--timeout","30000","--params",JSON.stringify({sessionKey:e,message:r,deliver:n,idempotencyKey:MR()})]}buildDirectNotificationArgs(e,r,n){let o=ma(n),i=["message","send","--channel",e.channel,"--target",e.target,"--message",r];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"]}};var Bg="COMPLETION_FOLLOWUP_DELIVERED",Wg="COMPLETION_FOLLOWUP_SKIPPED";function OR(t){let e=_R(t).trim();if(!e)return{outcome:"failure",reason:"completion follow-up wake produced no final response"};if(/^NO_REPLY$/i.test(e))return{outcome:"failure",reason:"completion follow-up wake ended with NO_REPLY"};if(!e.includes(Bg)){let r=DR(e);return r?LR(r)?{outcome:"failure",reason:"completion follow-up wake skipped because the summary was only in agent output, not visibly delivered"}:{outcome:"skipped",reason:r}:{outcome:"failure",reason:`completion follow-up wake did not confirm ${Bg}`}}return{outcome:"success"}}function _R(t){let e=t.trim();if(!e)return"";try{return ud(JSON.parse(e)).trim()}catch{return e}}function ud(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>ud(n)).filter(Boolean).join(`
|
|
218
|
-
`);if(!t||typeof t!="object")return"";let e=t,r=["final","finalResponse","final_response","assistantFinal","assistant_final","response","text","content"];for(let n of r){let o=e[n];if(typeof o=="string"&&o.trim())return o}for(let n of["result","message","data"]){let o=ud(e[n]);if(o.trim())return o}return""}function DR(t){let e=t.indexOf(Wg);return e<0?void 0:t.slice(e+Wg.length).replace(/^[:\s-]+/,"").split(/\r?\n/,1)[0]?.trim()||"explicitly skipped by wake agent"}function LR(t){return/\balready summarized by completed session\b/i.test(t)}var ha=class{routes=new fa;transport;directNotifications;executor=new ca;constructor(e={}){this.transport=e.transport??new ga(e.transportOptions),this.directNotifications=e.directNotifications===void 0?new la:e.directNotifications}clearPendingRetries(){this.executor.clearPendingRetries()}clearRetryTimersForSession(e){this.executor.clearRetryTimersForSession(e)}dispose(){this.executor.dispose()}buildDispatchContext(e){let r=e.buttons??[],n=r.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:n.length>0,buttonRows:r.length||void 0,buttonCount:n.length||void 0,buttonLabels:n.length>0?n.map(o=>o.label):void 0,maxCallbackDataLength:n.length>0?Math.max(...n.map(o=>o.callbackData.length)):void 0}}sendWake(e,r,n,o,i,a,u,p,d){let l=this.routes.resolve(e),m=u;if(m?.()===!1)return;let c=l?.sessionKey?.trim();if(!c){this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-system`,sessionId:e.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:r}),onSuccess:a,onSkipped:d,onFinalFailure:i,successValidator:p,shouldContinue:m});return}this.executor.execute(this.transport.buildChatSendArgs(c,r,!0),{label:n,sessionId:e.id,target:"chat.send",phase:o,routeSummary:`session:${c}`,messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:`session:${c}`,route:l,text:r}),onSuccess:a,onSkipped:d,successValidator:p,shouldContinue:m,onFinalFailure:()=>{m?.()!==!1&&this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-fallback`,sessionId:e.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:r}),onSuccess:a,onSkipped:d,onFinalFailure:i,successValidator:p,shouldContinue:m})}})}sendUserNotification(e,r,n,o,i,a,u=!1,p){if(p?.()===!1)return;let d=!!o?.some(y=>Array.isArray(y)&&y.length>0),l=this.routes.resolve(e);ie("wake_notify_selected",{sessionId:e.id,sessionName:e.name,label:n,messageTextLength:r.length,requireDirectDelivery:u,hasDirectNotificationTransport:!!this.directNotifications,routeSummary:l?this.routes.summary(l):"system",channel:l?.channel,target:l?.target,accountId:l?.accountId,threadId:l?.threadId,sessionKey:l?.sessionKey,...Pe(o)});let m=l?`notify:${l.channel}|${l.accountId??""}|${l.target}|${l.threadId??""}`:`notify:system:${e.id}`;if(!l){if(ie("wake_notify_no_direct_route",{sessionId:e.id,sessionName:e.name,label:n,requireDirectDelivery:u,hasInteractiveButtons:d,...Pe(o)}),u){console.warn(`[WakeDispatcher] Direct notification "${n}" for session ${e.id} has no direct route; reporting delivery failure instead of using system fallback.`),i?.();return}if(d){console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${e.id} has no direct route; refusing text-only fallback because buttons would be lost.`),i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-notify-system`,sessionId:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:r,buttons:o}),orderingKey:m,onSuccess:a,onFinalFailure:i,shouldContinue:p});return}let c=()=>{if(ie("wake_notify_direct_failed",{sessionId:e.id,sessionName:e.name,label:n,requireDirectDelivery:u,hasInteractiveButtons:d,channel:l.channel,target:l.target,accountId:l.accountId,threadId:l.threadId,sessionKey:l.sessionKey,...Pe(o)}),u){console.warn(`[WakeDispatcher] Direct notification "${n}" for session ${e.id} failed direct delivery; reporting delivery failure instead of using system fallback.`),i?.();return}if(d){console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${e.id} failed direct delivery; refusing text-only fallback because buttons would be lost.`),i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-notify-fallback`,sessionId:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:r}),orderingKey:m,onSuccess:a,onFinalFailure:i,shouldContinue:p})},h={label:`${n}-notify`,sessionId:e.id,target:"message.send",phase:"notify",routeSummary:this.routes.summary(l),messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:this.routes.summary(l),route:l,text:r,buttons:o}),orderingKey:m,onSuccess:a,onAmbiguousResult:c,onFinalFailure:c,terminalOnFailure:this.directNotifications?!0:void 0,shouldContinue:p};if(this.directNotifications){ie("wake_notify_dispatching_direct_runtime",{sessionId:e.id,sessionName:e.name,label:n,channel:l.channel,target:l.target,accountId:l.accountId,threadId:l.threadId,sessionKey:l.sessionKey,...Pe(o)}),this.executor.executePromise(()=>this.directNotifications.send(l,r,o),h);return}ie("wake_notify_dispatching_cli_message_send",{sessionId:e.id,sessionName:e.name,label:n,channel:l.channel,target:l.target,accountId:l.accountId,threadId:l.threadId,sessionKey:l.sessionKey,...Pe(o)}),this.executor.execute(this.transport.buildDirectNotificationArgs(l,r,o),h)}sendUserNotificationSequence(e,r,n,o,i,a=!1,u){let p=r.map(l=>({text:l.text.trim(),buttons:l.buttons})).filter(l=>l.text.length>0);if(p.length===0){o?.();return}ie("wake_notify_sequence_started",{sessionId:e.id,sessionName:e.name,label:n,chunkCount:p.length,buttonChunkIndexes:p.map((l,m)=>l.buttons?.some(c=>Array.isArray(c)&&c.length>0)?m+1:void 0).filter(l=>typeof l=="number"),requireDirectDelivery:a});let d=l=>{if(u?.()===!1)return;let m=p[l];if(!m){ie("wake_notify_sequence_succeeded",{sessionId:e.id,sessionName:e.name,label:n,chunkCount:p.length}),i?.();return}let c=l===0?o:i;ie("wake_notify_sequence_chunk_selected",{sessionId:e.id,sessionName:e.name,label:n,chunkIndex:l+1,chunkCount:p.length,messageTextLength:m.text.length,failureHandler:l===0?"all-failed":"sequence-success",...Pe(m.buttons)}),this.sendUserNotification(e,m.text,`${n}-part-${l+1}`,m.buttons,c,()=>d(l+1),a,u)};d(0)}dispatchSessionNotification(e,r){let n=r.hooks,o=r.wakeMessageOnNotifySuccess!=null||r.wakeMessageOnNotifyFailed!=null,i=r.notifyUser??(r.wakeMessage?"on-wake-fallback":"always"),a=(r.userMessages?.length?r.userMessages:r.userMessage?.trim()?[{text:r.userMessage.trim(),buttons:r.buttons}]:[]).map(m=>({text:m.text.trim(),buttons:m.buttons})).filter(m=>m.text.length>0),u=a[0]?.text,p=r.wakeMessage?.trim(),d=r.shouldDispatch,l=r.completionWakeSummaryRequired===!0?OR:void 0;if(o){let m=r.wakeMessageOnNotifySuccess?.trim(),c=r.wakeMessageOnNotifyFailed?.trim(),h=x=>{x&&d?.()!==!1&&(n?.onWakeStarted?.(),this.sendWake(e,x,`${r.label}-wake`,"wake",n?.onWakeFailed,n?.onWakeSucceeded,d,l,n?.onWakeSkipped))},y=x=>{if(x){if(r.deferConditionalWakeUntilNextTick===!0){setTimeout(()=>h(x),0).unref?.();return}h(x)}},k=()=>{d?.()!==!1&&(n?.onNotifySucceeded?.(),m&&y(m))},S=c?()=>{d?.()!==!1&&(n?.onNotifyFailed?.(),r.onUserNotifyFailed?.(),y(c))}:()=>{d?.()!==!1&&(n?.onNotifyFailed?.(),r.onUserNotifyFailed?.())};if(a.length>0){if(d?.()===!1)return;n?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,a,r.label,S,k,r.requireDirectUserNotification===!0,d)}else S();return}if(i==="always"&&a.length>0){if(d?.()===!1)return;n?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,a,r.label,()=>{d?.()!==!1&&(n?.onNotifyFailed?.(),r.onUserNotifyFailed?.())},()=>{d?.()!==!1&&n?.onNotifySucceeded?.()},r.requireDirectUserNotification===!0,d)}if(p&&d?.()!==!1){if(n?.onWakeStarted?.(),i==="on-wake-fallback"&&a.length>0&&!this.routes.resolve(e)?.sessionKey){if(d?.()===!1)return;n?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,a,r.label,()=>{d?.()!==!1&&(n?.onNotifyFailed?.(),r.onUserNotifyFailed?.())},()=>{d?.()!==!1&&n?.onNotifySucceeded?.()},!1,d)}this.sendWake(e,p,`${r.label}-wake`,"wake",n?.onWakeFailed,n?.onWakeSucceeded,d,l,n?.onWakeSkipped)}}};var ya=class{constructor(e,r){this.actionTokens=e;this.isGitHubCliAvailable=r}actionTokens;isGitHubCliAvailable;createActionToken(e,r,n={}){return this.actionTokens.createActionToken(e,r,{expiresAt:Date.now()+10080*60*1e3,...n})}consumeActionToken(e){return this.actionTokens.consumeActionToken(e)}getActionToken(e){return this.actionTokens.getActionToken(e)}clearPlanDecisionTokens(e,r){this.actionTokens.deletePlanDecisionTokensForSession(e,r)}makeActionButton(e,r,n,o={}){let i=this.createActionToken(e,r,{label:n,...o});return{label:n,callbackData:i.id,style:this.resolveButtonStyle(r)}}resolveButtonStyle(e){switch(e){case"plan-approve":case"worktree-create-pr":case"worktree-update-pr":case"plan-offer-start":return"primary";case"worktree-merge":case"session-resume":case"session-restart":return"success";case"plan-reject":case"worktree-dismiss":return"danger";default:return"secondary"}}getWorktreeDecisionButtons(e,r){if(!r)return[];let n=[],o=[this.makeActionButton(e,"worktree-merge","Merge")];if(this.isGitHubCliAvailable())r.worktreePrUrl?(o.push(this.makeActionButton(e,"worktree-view-pr","View PR",{targetUrl:r.worktreePrUrl})),n.push(o),n.push([this.makeActionButton(e,"worktree-update-pr","Sync PR"),this.makeActionButton(e,"worktree-decide-later","Later")])):(o.push(this.makeActionButton(e,"worktree-create-pr","Open PR")),n.push(o),n.push([this.makeActionButton(e,"worktree-decide-later","Later"),this.makeActionButton(e,"worktree-dismiss","Discard")]));else return n.push([...o,this.makeActionButton(e,"worktree-decide-later","Later")]),n.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),n;return r.worktreePrUrl&&n.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),n}getPlanApprovalButtons(e,r){let n=[[this.makeActionButton(e,"plan-approve","Approve",{planDecisionVersion:r?.planDecisionVersion}),this.makeActionButton(e,"plan-request-changes","Revise",{planDecisionVersion:r?.planDecisionVersion}),this.makeActionButton(e,"plan-reject","Reject",{planDecisionVersion:r?.planDecisionVersion})]];return ie("plan_approval_buttons_created",{sessionId:e,planDecisionVersion:r?.planDecisionVersion,...Pe(n)}),n}getResumeButtons(e,r){let n=[];return r.isExplicitlyResumable&&n.push(this.makeActionButton(e,"session-resume","Resume")),n.push(this.makeActionButton(e,"view-output","View output")),[n]}getQuestionButtons(e,r){if(r.length!==0)return[r.map((n,o)=>this.makeActionButton(e,"question-answer",n.label,{optionIndex:o}))]}getPlanOfferButtons(e){let{offerId:r,route:n,planName:o,planPrompt:i,planWorkdir:a,planWorktreeStrategy:u}=e,p=[[this.makeActionButton(r,"plan-offer-start","Start Plan",{route:n,launchName:o,launchPrompt:i,launchWorkdir:a,launchWorktreeStrategy:u}),this.makeActionButton(r,"plan-offer-dismiss","Dismiss",{route:n})]];return ie("plan_offer_buttons_created",{offerId:r,planName:o,channel:n.provider,target:n.target,accountId:n.accountId,threadId:n.threadId,sessionKey:n.sessionKey,planPromptLength:i.length,planWorkdirLength:a.length,planWorktreeStrategy:u,...Pe(p)}),p}};Ee();ir();import{createHash as pd}from"crypto";var FR=1024,ka=class{constructor(e,r,n={}){this.wakeDispatcher=e;this.applyPersistedPatch=r;this.maxCompletedCompletionWakeKeys=Math.max(1,Math.floor(n.maxCompletedCompletionWakeKeys??FR))}wakeDispatcher;applyPersistedPatch;inFlightCompletionWakes=new Set;completedCompletionWakes=new Map;maxCompletedCompletionWakeKeys;dispatch(e,r){let n=this.getDeliveryRef(e),o=this.buildCompletionWakeKey(n,r,e),i=r,a;if(o?.key)if(this.inFlightCompletionWakes.has(o.key)||this.completedCompletionWakes.has(o.key))if(r.hooks?.onWakeSkipped?.("duplicate completion follow-up wake already handled"),o.explicit)i=this.withoutCompletionWake(r);else return;else this.inFlightCompletionWakes.add(o.key),a=o.key;let u=this.buildCompletionWakePatch(i),p=!!(i.wakeMessage?.trim()||i.wakeMessageOnNotifySuccess?.trim()),d=!!(i.wakeMessage?.trim()||i.wakeMessageOnNotifyFailed?.trim()),l={onNotifyStarted:()=>{this.applyDeliveryState(n,"notifying"),i.hooks?.onNotifyStarted?.()},onNotifySucceeded:()=>{this.applyNotifyDeliveryState(n,p?"wake_pending":"idle",p?u:void 0),p||this.markCompletionWakeFinished(a,!1),i.hooks?.onNotifySucceeded?.()},onNotifyFailed:()=>{this.applyNotifyDeliveryState(n,d?"wake_pending":"failed",d?u:void 0),d||this.markCompletionWakeFinished(a,!1),i.hooks?.onNotifyFailed?.()},onWakeStarted:()=>{this.applyPersistedPatchWithCompletionWake(n,"wake_pending",u,{completionWakeIssuedAt:new Date().toISOString(),completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0,completionWakeSkippedAt:void 0,completionWakeSkipReason:void 0}),i.hooks?.onWakeStarted?.()},onWakeSucceeded:()=>{this.applyPersistedPatchWithCompletionWake(n,"idle",this.buildCompletionWakeSucceededPatch(u),{completionWakeSucceededAt:new Date().toISOString(),completionWakeFailedAt:void 0,completionWakeSkippedAt:void 0,completionWakeSkipReason:void 0}),this.markCompletionWakeFinished(a,!0),i.hooks?.onWakeSucceeded?.()},onWakeSkipped:m=>{this.applyPersistedPatchWithCompletionWake(n,"idle",this.buildCompletionWakeSucceededPatch(u),{completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0,completionWakeSkippedAt:new Date().toISOString(),completionWakeSkipReason:m}),this.markCompletionWakeFinished(a,!0),i.hooks?.onWakeSkipped?.(m)},onWakeFailed:()=>{this.applyPersistedPatchWithCompletionWake(n,"failed",u,{completionWakeFailedAt:new Date().toISOString()}),this.markCompletionWakeFinished(a,!1),i.hooks?.onWakeFailed?.()}};this.wakeDispatcher.dispatchSessionNotification(e,{...i,hooks:l})}notifyWorktreeOutcome(e,r,n={}){let o=this.getDeliveryRef(e),i=u=>Jn({sessionId:o,sessionName:e.name,outcomeLine:r,originThreadLine:Ao(e),detailLines:n.detailLines,canonicalStatusDelivered:u}),a=n.summaryWakeRequired??!0;this.dispatch(e,{label:"worktree-outcome",userMessage:r,notifyUser:"always",requireDirectUserNotification:!0,completionWakeSummaryRequired:a,completionWakeOutcomeKey:n.completionWakeOutcomeKey??`terminal:${o}`,deferConditionalWakeUntilNextTick:!0,wakeMessageOnNotifySuccess:a?i(!0):void 0,wakeMessageOnNotifyFailed:a?i(!1):void 0})}dispose(){this.wakeDispatcher.dispose()}getDeliveryRef(e){return ke(e)??q(e)??""}applyDeliveryState(e,r){!e||!r||this.applyPersistedPatch(e,{deliveryState:r})}applyNotifyDeliveryState(e,r,n){!e||!r||this.applyPersistedPatch(e,n?{deliveryState:r,...n}:{deliveryState:r})}applyPersistedPatchWithCompletionWake(e,r,n,o){!e||!r||this.applyPersistedPatch(e,n?{deliveryState:r,...n,...o}:{deliveryState:r})}buildCompletionWakePatch(e){if(e.completionWakeSummaryRequired===!0)return{completionWakeSummaryRequired:!0}}buildCompletionWakeSucceededPatch(e){if(e)return{completionWakeSummaryRequired:void 0}}withoutCompletionWake(e){return{...e,wakeMessage:void 0,wakeMessageOnNotifySuccess:void 0,wakeMessageOnNotifyFailed:void 0,completionWakeSummaryRequired:!1}}buildCompletionWakeKey(e,r,n){if(r.completionWakeSummaryRequired!==!0||!e)return;let o=this.normalizeCompletionWakeOutcomeKey(n,r.completionWakeOutcomeKey?.trim());if(o){let u=pd("sha256").update(o).digest("hex").slice(0,16);return{key:`${this.buildExplicitCompletionWakeScope(e,n)}:outcome:${u}`,explicit:!0}}let i=[r.wakeMessage,r.wakeMessageOnNotifySuccess,r.wakeMessageOnNotifyFailed].map(u=>u?.trim()).filter(u=>!!u);if(i.length===0)return;let a=pd("sha256").update(i.join(`
|
|
212
|
+
`).map(o=>o.trim()).filter(Boolean).join(" ");if(!e)return;let n=e.match(/^[^.!?]+[.!?]/)?.[0]??e,r=Pd(n).replace(/\s+/g," ").trim();return r?wd(r,180):void 0}function vd(t){return t.replace(/^[-*âĸ]\s+/,"").replace(/\s+/g," ").trim()}function wd(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3)).trimEnd()}...`}function Pd(t){return t.replace(/\b[A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd|pwd|credential|credentials|authorization|auth)[A-Za-z0-9_-]*\b\s*[:=]\s*["']?[^"'\s,;)]+/gi,"[redacted credential]").replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{16,}\b/g,"[redacted token]").replace(/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,"[redacted token]").replace(/\bsk-[A-Za-z0-9_-]{20,}\b/g,"[redacted token]").replace(/\bhttps?:\/\/\S+/gi,"[redacted link]").replace(new RegExp(`\\b[A-Za-z0-9_-]{${Sd},}\\b`,"g"),"[redacted token]")}function zm(t){return/\b[A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd|pwd|credential|credentials|authorization|auth)[A-Za-z0-9_-]*\b\s*[:=]\s*["']?[^"'\s,;)]+/i.test(t)||/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{16,}\b/.test(t)||/\bgithub_pat_[A-Za-z0-9_]{20,}\b/.test(t)||/\bsk-[A-Za-z0-9_-]{20,}\b/.test(t)||/\bhttps?:\/\/\S+/i.test(t)||new RegExp(`\\b[A-Za-z0-9_-]{${Sd},}\\b`).test(t)}fe();var Ir=class{constructor(e){this.deps=e;this.actions=new Ar({shouldRunWorktreeStrategy:e.shouldRunWorktreeStrategy,isAlreadyMerged:e.isAlreadyMerged,resolveWorktreeRepoDir:e.resolveWorktreeRepoDir,getWorktreeCompletionState:e.getWorktreeCompletionState})}deps;actions;buildConflictResolverPrompt(e){return["Resolve the git rebase conflict for the auto-merge worktree and finish the rebase cleanly.","",`Original session: ${e.session.name} [${e.session.id}]`,`Repository root: ${e.repoDir}`,`Conflicted worktree: ${e.worktreePath}`,`Branch: ${e.branchName}`,`Base branch: ${e.baseBranch}`,"","Requirements:","- Work only inside the conflicted worktree.","- Inspect the current rebase state and resolve only the necessary conflict hunks.","- Make only minimal follow-up edits needed to keep the rebased branch correct.","- Continue the rebase until it completes successfully.","- Run relevant local verification before you finish.","- Do not broaden scope or start unrelated refactors.",`- Stop only when the branch is cleanly rebased onto ${e.baseBranch}.`,e.mergeError?"":void 0,e.mergeError?"Rebase failure details:":void 0,e.mergeError].filter(n=>typeof n=="string").join(`
|
|
213
|
+
`)}notifyAutoMergeConflictEscalation(e,n,r){this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-escalated",idempotencyKey:`worktree-merge-conflict-escalated:${e.id}:${n}`,userMessage:[`â ī¸ [${e.name}] Auto-merge could not finish after one conflict-resolution attempt.`,`Branch \`${n}\` was preserved for manual follow-up.`,"",r].join(`
|
|
214
|
+
`),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}updatePersistedSessionFor(e,n){for(let r of ae(e))this.deps.updatePersistedSession(r,n)}markPendingDecision(e,n={}){this.updatePersistedSessionFor(e,ir(e,n))}markAutoMergeConflictResolving(e,n,r){this.updatePersistedSessionFor(e,ha(e,n,r,{notes:[`resolver_session:${n}`]}))}markMerged(e){this.updatePersistedSessionFor(e,sr(e,{clearResolverSessionId:!0}))}async handleWorktreeStrategy(e){let n=await this.actions.plan(e);return n.kind==="skip"?n.result:n.kind==="notify"?(this.deps.dispatchSessionNotification(e,{label:n.label,idempotencyKey:["worktree-action",e.id,n.label,e.completedAt??"unknown",e.worktreeBranch??"unknown",e.worktreePath??"unknown"].join(":"),userMessage:n.message}),{notificationSent:!0,worktreeRemoved:!1}):n.kind==="dirty-uncommitted"?this.handleDirtyUncommittedCompletion(e,n.worktreePath,n.branchName,n.baseBranch):n.kind==="no-change"?this.handleNoChange(e,n.repoDir,n.worktreePath,n.nativeBackendWorktree):n.strategy==="ask"?await this.handleAskStrategy(e,n.branchName,n.baseBranch,n.diffSummary):n.strategy==="delegate"?this.handleDelegateStrategy(e,n.branchName,n.baseBranch,n.diffSummary):n.strategy==="auto-merge"?(await this.handleAutoMergeStrategy(e,n.repoDir,n.worktreePath,n.branchName,n.baseBranch,n.diffSummary,n.sessionRef),{notificationSent:!0,worktreeRemoved:!1}):n.strategy==="auto-pr"?this.handleAutoPrStrategy(e,n.baseBranch):{notificationSent:!1,worktreeRemoved:!1}}async handleNoChange(e,n,r,o=de(e)){let i=o?!0:me(n,r);return i?(e.worktreePath=void 0,this.updatePersistedSessionFor(e,{worktreePath:void 0,worktreeDisposition:"no-change-cleaned",worktreeState:"none",worktreeLifecycle:{state:"no_change",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"strategy_no_change",baseBranch:e.worktreeBaseBranch,targetRepo:e.worktreePrTargetRepo,pushRemote:e.worktreePushRemote}}),this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildNoChangeNotification({session:e,nativeBackendWorktree:o,cleanupSucceeded:!0,worktreePath:r,preview:this.deps.getOutputPreview(e),originThreadLine:this.deps.originThreadLine(e)}))):this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildNoChangeNotification({session:e,nativeBackendWorktree:o,cleanupSucceeded:!1,worktreePath:r,preview:this.deps.getOutputPreview(e),originThreadLine:this.deps.originThreadLine(e)})),{notificationSent:!0,worktreeRemoved:i}}async handleAskStrategy(e,n,r,o){let i=await kd({sessionName:e.name,prompt:e.prompt,diffSummary:o,outputPreview:this.deps.getOutputPreview(e,4e3),provider:this.deps.worktreeSummaryProvider});return this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildAskNotification({session:e,branchName:n,baseBranch:r,diffSummary:o,summaryLines:i.lines,buttons:this.deps.getWorktreeDecisionButtons(e.id)})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleDelegateStrategy(e,n,r,o){return this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildDelegateNotification({session:e,branchName:n,baseBranch:r,diffSummary:o,originThreadLine:this.deps.originThreadLine(e)})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleDirtyUncommittedCompletion(e,n,r,o){this.markPendingDecision(e,{notes:["dirty_uncommitted_completion"]});let i=dt(n),s=i.slice(0,20).map(d=>`- ${d}`),a=i.length>20?[`- ...and ${i.length-20} more`]:[];return this.deps.dispatchSessionNotification(e,{label:"worktree-dirty-uncommitted",idempotencyKey:`worktree-dirty-uncommitted:${e.id}:${r}:${o}`,userMessage:[`â ī¸ [${e.name}] Session completed with uncommitted worktree changes.`,"",`Branch \`${r}\` has no commits ahead of \`${o}\`, so merge/PR follow-through is blocked until the worktree is fixed.`,`Worktree: ${n}`,"",...s.length>0?["Dirty entries:",...s,...a,""]:[],"Resume the session or inspect the worktree, then commit real task changes or clean temporary files. Discard only if these local changes should be permanently removed."].join(`
|
|
215
|
+
`)}),{notificationSent:!0,worktreeRemoved:!1}}handleAutoMergeSuccess(e,n,r,o,i,s){be(n,r),this.markMerged(e);let a=qe({kind:"merge",branch:r,base:o,filesChanged:i.filesChanged,insertions:i.insertions,deletions:i.deletions}),d=a;s.stashPopConflict?d+=`
|
|
216
|
+
â ī¸ Pre-merge stash pop conflicted â run \`git stash show ${s.stashRef??"stash@{0}"}\` in ${n} to review stashed changes.`:s.stashed&&(d+=`
|
|
217
|
+
(Pre-existing changes on ${o} were auto-stashed and restored.)`);let l=[s.fastForward?"Merge type: fast-forward.":"Merge type: merge commit.",`Auto-merge landed ${r} into ${o}.`,"Local worktree branch cleanup was requested.",...s.stashPopConflict?[`Pre-merge stash pop conflicted; run git stash show ${s.stashRef??"stash@{0}"} in ${n} to review stashed changes.`]:[],...!s.stashPopConflict&&s.stashed?[`Pre-existing changes on ${o} were auto-stashed and restored.`]:[]];this.deps.dispatchSessionNotification(e,{label:"worktree-merge-success",idempotencyKey:`worktree-merge-success:${e.id}:${r}:${o}`,userMessage:d,notifyUser:"always",completionSummary:{required:!0,producer:"worktree",outcomeKey:`terminal:${e.id}`},completionWakeSummaryRequired:!0,completionWakeOutcomeKey:`terminal:${e.id}`,deferConditionalWakeUntilNextTick:!0,wakeMessageOnNotifySuccess:ft({sessionId:e.id,sessionName:e.name,outcomeLine:a,originThreadLine:this.deps.originThreadLine(e),detailLines:l,canonicalStatusDelivered:!0}),wakeMessageOnNotifyFailed:ft({sessionId:e.id,sessionName:e.name,outcomeLine:a,originThreadLine:this.deps.originThreadLine(e),detailLines:l,canonicalStatusDelivered:!1})})}async handleInitialAutoMergeConflict(e,n,r,o,i,s){let a=e.autoMergeConflictResolutionAttemptCount??0;if(a>=1){this.markPendingDecision(e,{notes:["auto_merge_conflict_retry_exhausted"],clearResolverSessionId:!0}),this.notifyAutoMergeConflictEscalation(e,o,`The rebased branch still conflicts with \`${i}\`. Open a PR or resolve manually in ${r}.`);return}let d=this.buildConflictResolverPrompt({session:e,repoDir:n,worktreePath:r,branchName:o,baseBranch:i,mergeError:s});try{let l=await this.deps.spawnConflictResolver({session:e,repoDir:n,worktreePath:r,branchName:o,baseBranch:i,prompt:d});this.markAutoMergeConflictResolving(e,l.id,a+1),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-resolving",idempotencyKey:`worktree-merge-conflict-resolving:${e.id}:${o}:${l.id}`,userMessage:`â ī¸ [${e.name}] Auto-merge hit a rebase conflict. Started resolver session ${l.name} and will retry automatically if it succeeds.`})}catch(l){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}`,userMessage:`â [${e.name}] Auto-merge hit a rebase conflict and failed to start the resolver: ${l instanceof Error?l.message:String(l)}`,buttons:[[this.deps.makeOpenPrButton(e.id)]]})}}handleAutoMergeRetryFailure(e,n,r,o){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}:${n}`,userMessage:[o,"","Auto-merge retry did not complete after conflict resolution.",`Branch \`${n}\` was preserved for manual follow-up in ${r}.`].join(`
|
|
218
|
+
`),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}async handleAutoMergeStrategy(e,n,r,o,i,s,a=N(e)??e.harnessSessionId){this.deps.isAlreadyMerged(a)||e.autoMergeResolverSessionId||await this.deps.enqueueMerge(n,async()=>{if(this.deps.isAlreadyMerged(a))return;let d=this.deps.mergeBranch(n,o,i,"merge",r);if(d.success){this.handleAutoMergeSuccess(e,n,o,i,s,d);return}if(d.rebaseConflict){await this.handleInitialAutoMergeConflict(e,n,r,o,i,d.error);return}let l=d.dirtyError?`â [${e.name}] Merge blocked: ${d.error}`:`â [${e.name}] Merge failed: ${d.error??"unknown error"}`;if(e.worktreeState==="merge_conflict_resolving"||e.worktreeLifecycle?.state==="merge_conflict_resolving"){this.handleAutoMergeRetryFailure(e,o,r,l);return}this.deps.dispatchSessionNotification(e,{label:"worktree-merge-error",idempotencyKey:`worktree-merge-error:${e.id}:${o}`,userMessage:l})},()=>{this.deps.dispatchSessionNotification(e,{label:"worktree-merge-queued",idempotencyKey:`worktree-merge-queued:${e.id}:${o}`,userMessage:`đ [${e.name}] Merge queued â another merge for this repo is in progress. Will notify when complete.`})})}async handleAutoPrStrategy(e,n){return this.updatePersistedSessionFor(e,{lifecycle:"terminal",worktreeState:"pr_in_progress"}),(await this.deps.runAutoPr(e,n)).success||(this.markPendingDecision(e),this.deps.dispatchSessionNotification(e,{label:"worktree-auto-pr-failed",idempotencyKey:`worktree-auto-pr-failed:${e.id}:${n}`,userMessage:`â ī¸ [${e.name}] Auto-PR did not complete. The worktree is preserved for an explicit merge or PR decision.`,buttons:this.deps.getWorktreeDecisionButtons(e.id)})),{notificationSent:!0,worktreeRemoved:!1}}};import{existsSync as Cf,writeFileSync as Mf}from"fs";ke();import{randomUUID as Qm}from"crypto";function Jm(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}var xr=class{constructor(e,n){this.onChange=e;this.retentionMs=n}onChange;retentionMs;tokens=new Map;afterChange;replaceAll(e){this.tokens.clear();for(let n of e)this.tokens.set(n.id,n)}clear(){this.tokens.clear(),this.notifyChanged()}listForPersistence(){return[...this.tokens.values()]}createActionToken(e,n,r={}){let o={id:Qm(),sessionId:e,kind:n,createdAt:Date.now(),...r};return this.tokens.set(o.id,o),this.notifyChanged(),o}getActionToken(e){let n=this.tokens.get(e);if(n){if(n.expiresAt!=null&&n.expiresAt<=Date.now()){this.tokens.delete(e),this.notifyChanged();return}return n}}consumeActionToken(e){let n=this.getActionToken(e);if(!(!n||n.consumedAt!=null))return n.consumedAt=Date.now(),this.notifyChanged(),n}deleteActionTokensForSession(e){let n=!1;for(let[r,o]of this.tokens)o.sessionId===e&&(this.tokens.delete(r),n=!0);n&&this.notifyChanged()}deletePlanDecisionTokensForSession(e,n){let r=!1;for(let[o,i]of this.tokens)i.sessionId!==e||!Jm(i.kind)||n!=null&&i.planDecisionVersion===n||(this.tokens.delete(o),r=!0);r&&this.notifyChanged()}purgeExpiredActionTokens(e=Date.now()){let n=!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),n=!0)}n&&this.notifyChanged()}nextExpiryAt(){let e;for(let n of this.tokens.values()){let r=[n.expiresAt,n.consumedAt!=null?n.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?.()}};Q();Q();var Tr=class{constructor(e){this.indexes=e}indexes;hasRecordedSession(e){return this.indexes.idIndex.has(e)}getLatestPersistedByName(e){let n,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 d=a.createdAt??Number.NEGATIVE_INFINITY,l=a.completedAt??Number.NEGATIVE_INFINITY;(d>r||d===r&&l>o||d===r&&l===o&&s>i)&&(n=a,r=d,o=l,i=s),s++}return n}resolveBackendConversationId(e,n){if(n)return n;let r=this.indexes.idIndex.get(e);if(r){let s=this.indexes.persisted.get(r);return(s?T(s):void 0)??r}let o=this.getLatestPersistedByName(e);if(o)return T(o)??o.harnessSessionId;let i=this.indexes.backendIdIndex.get(e);if(i){let s=this.indexes.persisted.get(i);return(s?T(s):void 0)??i}if(this.indexes.persisted.has(e)){let s=this.indexes.persisted.get(e);return s?T(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,n){return this.resolveBackendConversationId(e,n)}getPersistedSession(e){let n=this.indexes.idIndex.get(e);if(n)return this.indexes.persisted.get(n);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,n)=>(n.completedAt??0)-(e.completedAt??0))}};import{existsSync as Af,mkdirSync as Rf,readFileSync as If,readdirSync as bi,renameSync as Cd,statSync as Md,unlinkSync as _d,writeFileSync as Ed}from"fs";import{tmpdir as Ai}from"os";import{dirname as xf,join as Er}from"path";import{homedir as Ym}from"node:os";import{join as Zm}from"node:path";function bd(t){let e=t.OPENCLAW_HOME?.trim();if(e)return e;let n=t.HOME?.trim()||Ym();return Zm(n,".openclaw")}ke();var Cr=6,Xm=new Set(["running","completed","failed","killed"]);function He(t){return!!t&&typeof t=="object"}function gt(t,e=""){return typeof t=="string"&&t.trim().length>0?t:e}function w(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function ue(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ef(t){return typeof t=="string"&&da.has(t)?t:void 0}function Ad(t){return t==="default"||t==="plan"||t==="bypassPermissions"?t:void 0}function tf(t){return t==="never"||t==="on-request"?"never":void 0}function nf(t){return t==="approve"||t==="ask"||t==="delegate"?t:void 0}function rf(t){if(t==="plan-mode"||t==="codex-first-turn-plan"||t==="soft-plan")return"plan-mode"}function Rd(t){return typeof t=="string"&&zn.has(t)?t:void 0}function of(t){return t==="user"||t==="idle-timeout"||t==="startup-timeout"||t==="shutdown"||t==="done"||t==="unknown"?t:void 0}function sf(t){return t==="starting"||t==="active"||t==="awaiting_plan_decision"||t==="awaiting_user_input"||t==="awaiting_worktree_decision"||t==="suspended"||t==="terminal"?t:void 0}function af(t){return t==="not_required"||t==="pending"||t==="approved"||t==="changes_requested"||t==="rejected"?t:void 0}function df(t){return t==="none"||t==="provisioned"||t==="pending_decision"||t==="merge_conflict_resolving"||t==="merge_in_progress"||t==="pr_in_progress"||t==="merged"||t==="released"||t==="pr_open"||t==="dismissed"||t==="cleanup_failed"?t:void 0}function lf(t){return t==="none"||t==="provisioned"||t==="pending_decision"||t==="merge_conflict_resolving"||t==="pr_open"||t==="merged"||t==="released"||t==="dismissed"||t==="no_change"||t==="cleanup_failed"?t:void 0}function uf(t){return t==="live"||t==="stopped"?t:void 0}function pf(t){return t==="not_sent"||t==="sending"||t==="delivered"||t==="fallback_delivered"||t==="failed"?t:void 0}function cf(t){return t==="direct-telegram"?"direct-message":t==="none"||t==="direct-message"||t==="wake-only"?t:void 0}function mf(t){return t==="none"||t==="canonical_buttons"||t==="explicit_fallback_text"?t:void 0}function ff(t){return t==="idle"||t==="notifying"||t==="wake_pending"||t==="failed"?t:void 0}function gf(t){return t==="in_flight"||t==="delivered"?t:void 0}function hf(t){if(!Array.isArray(t))return;let e=t.map(n=>{if(!He(n))return;let r=w(n.key),o=gf(n.status),i=w(n.recordedAt);if(!(!r||!o||!i||!Number.isFinite(Date.parse(i))))return{key:r,status:o,recordedAt:i,label:w(n.label)}}).filter(n=>!!n);return e.length>0?e.slice(-64):void 0}function Sf(t){if(!Array.isArray(t))return;let e=t.map(n=>{if(!He(n))return;let r=w(n.key),o=w(n.recordedAt);if(!(!r||!o||!Number.isFinite(Date.parse(o))))return{key:r,recordedAt:o,label:w(n.label),skipReason:w(n.skipReason)}}).filter(n=>!!n);return e.length>0?e.slice(-1024):void 0}function yf(t){return t==="awaiting_plan_output"||t==="awaiting_approval"||t==="approved_then_implemented"||t==="implemented_without_required_approval"||t==="not_plan_gated"?t:void 0}function kf(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"||t==="plan-offer-start"||t==="plan-offer-dismiss"||t==="worktree-merge"||t==="worktree-create-pr"||t==="worktree-update-pr"||t==="worktree-view-pr"||t==="worktree-decide-later"||t==="worktree-dismiss"||t==="session-resume"||t==="session-restart"||t==="view-output"||t==="question-answer"?t:void 0}function Id(t){if(!He(t))return;let e=w(t.provider),n=w(t.accountId),r=w(t.target),o=w(t.threadId),i=w(t.sessionKey);if(!(!e||!r))return{provider:e,accountId:n,target:r,threadId:o,sessionKey:i}}function vf(t,e,n){if(He(t)){let r=w(t.kind),o=w(t.conversationId);if(o&&(r==="claude-code"||r==="codex-app-server"||r==="opencode-server"))return{kind:r,conversationId:o,runId:w(t.runId),worktreeId:w(t.worktreeId),worktreePath:w(t.worktreePath)}}if(e==="claude-code")return{kind:"claude-code",conversationId:n}}function wf(t){if(!He(t))return;let e=lf(t.state),n=w(t.updatedAt);if(!e||!n)return;let r=w(t.resolutionSource);return{state:e,updatedAt:n,resolvedAt:w(t.resolvedAt),resolutionSource:r==="agent_merge"||r==="agent_pr"||r==="strategy_no_change"||r==="lifecycle_resolver"||r==="dismiss"||r==="maintenance"?r:void 0,baseBranch:w(t.baseBranch),targetRepo:w(t.targetRepo),pushRemote:w(t.pushRemote),notes:Array.isArray(t.notes)?t.notes.filter(o=>typeof o=="string"&&o.length>0):void 0}}function Pf(t){let e=new Date(0).toISOString(),n=w(t.worktreeMergedAt)??w(t.worktreeDismissedAt)??w(t.pendingWorktreeDecisionSince)??e;if(t.worktreeMerged===!0)return{state:"merged",updatedAt:n,resolvedAt:w(t.worktreeMergedAt)??n,resolutionSource:"agent_merge",baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(t.worktreeDisposition==="dismissed")return{state:"dismissed",updatedAt:n,resolvedAt:w(t.worktreeDismissedAt)??n,resolutionSource:"dismiss",baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(t.worktreeDisposition==="no-change-cleaned")return{state:"no_change",updatedAt:n,resolvedAt:n,resolutionSource:"strategy_no_change",baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(t.worktreeDisposition==="pr-opened"||t.worktreeState==="pr_open")return{state:"pr_open",updatedAt:n,baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(t.pendingWorktreeDecisionSince||t.worktreeState==="pending_decision")return{state:"pending_decision",updatedAt:n,baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(t.worktreeState==="merge_conflict_resolving")return{state:"merge_conflict_resolving",updatedAt:n,baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)};if(w(t.worktreePath)||w(t.worktreeBranch))return{state:"provisioned",updatedAt:n,baseBranch:w(t.worktreeBaseBranch),targetRepo:w(t.worktreePrTargetRepo),pushRemote:w(t.worktreePushRemote)}}function bf(t){if(typeof t=="string"&&Xm.has(t))return t==="running"?"killed":t}function xd(t){if(!He(t))return;let e=gt(t.harnessSessionId);if(!e)return;let n=bf(t.status);if(!n)return;let r=t.status==="running",o=w(t.worktreePath),i=w(t.worktreeBranch),s=w(t.originChannel),a=typeof t.originThreadId=="string"||typeof t.originThreadId=="number"?t.originThreadId:void 0,d=w(t.originSessionKey),l=Id(t.route);if(!l)return;let u=Oe({route:l,originChannel:s,originThreadId:a,originSessionKey:d});if(!u||o&&!i)return;let p=w(t.harness),c=vf(t.backendRef,p,e),f=wf(t.worktreeLifecycle)??Pf(t),g=w(t.completionWakeSucceededAt),h=w(t.completionWakeSkippedAt),y=t.completionWakeSummaryRequired===!0&&!h?!0:void 0;return{sessionId:w(t.sessionId),harnessSessionId:e,backendRef:c,name:gt(t.name,e),prompt:gt(t.prompt),workdir:gt(t.workdir,"(unknown)"),model:w(t.model),reasoningEffort:ef(t.reasoningEffort),fastMode:t.fastMode===!0?!0:void 0,createdAt:ue(t.createdAt),completedAt:ue(t.completedAt),status:n,lifecycle:r?"suspended":sf(t.lifecycle),approvalState:af(t.approvalState),worktreeState:df(t.worktreeState),runtimeState:r?"stopped":uf(t.runtimeState),deliveryState:ff(t.deliveryState),notificationDedupe:hf(t.notificationDedupe),completionSummaryDedupe:Sf(t.completionSummaryDedupe),completionWakeIssuedAt:w(t.completionWakeIssuedAt),completionWakeSucceededAt:g,completionWakeFailedAt:w(t.completionWakeFailedAt),completionWakeSkippedAt:h,completionWakeSkipReason:w(t.completionWakeSkipReason),completionWakeSummaryRequired:y,killReason:of(t.killReason),costUsd:typeof t.costUsd=="number"&&Number.isFinite(t.costUsd)?t.costUsd:0,originAgentId:w(t.originAgentId),originChannel:s,originThreadId:a,originSessionKey:d,route:u,outputPath:w(t.outputPath),harness:p,goalTaskId:w(t.goalTaskId),requestedPermissionMode:Ad(t.requestedPermissionMode),currentPermissionMode:Ad(t.currentPermissionMode),approvalExecutionState:yf(t.approvalExecutionState),approvalRationale:w(t.approvalRationale),planModeApproved:t.planModeApproved===!0,pendingPlanApproval:t.pendingPlanApproval===!0,planApprovalContext:rf(t.planApprovalContext),planDecisionVersion:ue(t.planDecisionVersion),actionablePlanDecisionVersion:ue(t.actionablePlanDecisionVersion),canonicalPlanPromptVersion:ue(t.canonicalPlanPromptVersion),approvalPromptRequiredVersion:ue(t.approvalPromptRequiredVersion),approvalPromptVersion:ue(t.approvalPromptVersion),approvalPromptStatus:pf(t.approvalPromptStatus),approvalPromptTransport:cf(t.approvalPromptTransport),approvalPromptMessageKind:mf(t.approvalPromptMessageKind),approvalPromptLastAttemptAt:w(t.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:w(t.approvalPromptDeliveredAt),approvalPromptFailedAt:w(t.approvalPromptFailedAt),planApproval:nf(t.planApproval),codexApprovalPolicy:tf(t.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:Rd(t.worktreeStrategy),worktreeMerged:typeof t.worktreeMerged=="boolean"?t.worktreeMerged:void 0,worktreeMergedAt:w(t.worktreeMergedAt),worktreePrUrl:w(t.worktreePrUrl),worktreePrNumber:ue(t.worktreePrNumber),pendingWorktreeDecisionSince:w(t.pendingWorktreeDecisionSince),lastWorktreeReminderAt:w(t.lastWorktreeReminderAt),worktreeBaseBranch:w(t.worktreeBaseBranch),worktreePrTargetRepo:w(t.worktreePrTargetRepo),autoMergeParentSessionId:w(t.autoMergeParentSessionId),autoMergeConflictResolutionAttemptCount:ue(t.autoMergeConflictResolutionAttemptCount),autoMergeResolverSessionId:w(t.autoMergeResolverSessionId),worktreePushRemote:w(t.worktreePushRemote),worktreeDecisionSnoozedUntil:w(t.worktreeDecisionSnoozedUntil),worktreeDisposition:t.worktreeDisposition==="active"||t.worktreeDisposition==="pr-opened"||t.worktreeDisposition==="merged"||t.worktreeDisposition==="dismissed"||t.worktreeDisposition==="no-change-cleaned"?t.worktreeDisposition:void 0,worktreeDismissedAt:w(t.worktreeDismissedAt),worktreeLifecycle:f,resumable:r?!0:t.resumable===!0}}function Td(t){if(!He(t))return;let e=kf(t.kind),n=gt(t.id),r=gt(t.sessionId),o=ue(t.createdAt);if(!(!n||!r||!e||o==null))return{id:n,sessionId:r,kind:e,createdAt:o,planDecisionVersion:ue(t.planDecisionVersion),expiresAt:ue(t.expiresAt),consumedAt:ue(t.consumedAt),optionIndex:ue(t.optionIndex),label:w(t.label),targetUrl:w(t.targetUrl),route:Id(t.route),launchName:w(t.launchName),launchPrompt:w(t.launchPrompt),launchWorkdir:w(t.launchWorkdir),launchWorktreeStrategy:Rd(t.launchWorktreeStrategy)}}function Mr(t){if(!t.backendRef?.kind||!t.backendRef.conversationId)throw new Error(`Persisted session ${t.harnessSessionId} is missing required backend ref metadata.`);if(!t.route?.provider||!t.route.target)throw new Error(`Persisted session ${t.harnessSessionId} is missing required route metadata.`);if(t.worktreePath&&!t.worktreeBranch)throw new Error(`Persisted session ${t.harnessSessionId} is missing required worktreeBranch metadata.`)}function Pi(t){return!!t&&typeof t=="object"}function Ri(t){return t instanceof Error?t.message:String(t)}function $d(t){let e=t.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||Er(bd(t),"code-agent-sessions.json")}function Dd(t,e,n){try{Rf(xf(t),{recursive:!0});let r=t+".tmp";Ed(r,JSON.stringify({schemaVersion:Cr,sessions:e,actionTokens:n},null,2),"utf-8"),Cd(r,t)}catch(r){`${Ri(r)}`}}function _r(t,e){try{if(!Af(t))return;let n=`${t}.legacy-${Date.now()}.json`;Cd(t,n),`${e}${n}`}catch(n){`${Ri(n)}`}}function Tf(t,e){try{if(e.length===0)return;let n=`${t}.codex-sdk-legacy-${Date.now()}.json`;Ed(n,JSON.stringify(e,null,2),"utf-8"),`${e.length}${n}`}catch(n){`${Ri(n)}`}}function Od(t,e){try{let n=Ai(),r=bi(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r)try{let i=Er(n,o),s=Md(i).mtimeMs;t-s>e&&_d(i)}catch{}}catch{}}function Nd(t,e){try{let n=Ai(),r=bi(n).filter(i=>i.startsWith("openclaw-agent-")&&i.endsWith(".txt")),o;for(let i of r)try{let s=Er(n,i),a=Md(s).mtimeMs+e;if(a<=t)return t;o=o==null?a:Math.min(o,a)}catch{}return o}catch{return}}function Wd(t){try{let e=new Set(t),n=Ai(),r=bi(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r){let i=Er(n,o);if(!e.has(i))try{_d(i)}catch{}}}catch{}}function Ld(t){let{indexPath:e,clearAll:n,indexPersistedEntry:r,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:s}=t;try{let a=If(e,"utf-8"),d=JSON.parse(a);if(Array.isArray(d)){_r(e,"legacy array store"),s();return}if(!Pi(d)||d.schemaVersion!==Cr&&d.schemaVersion!==4){_r(e,`schema mismatch (expected v${Cr})`),s();return}let l=Array.isArray(d.sessions)?d.sessions:[],u=[];for(let c of l){if(Pi(c)&&c.harness==="codex"){let g=Pi(c.backendRef)?c.backendRef:void 0;if((typeof g?.kind=="string"?g.kind:void 0)!=="codex-app-server"){u.push(c);continue}}let f=xd(c);if(!f){n(),_r(e,"invalid v4 session entry"),s();return}r(f)}u.length>0&&(Tf(e,u),s());let p=Array.isArray(d.actionTokens)?d.actionTokens:[];for(let c of p){let f=Td(c);if(!f){n(),_r(e,"invalid v4 action token"),s();return}o(f)}i()}catch{}}var _f=new Set(["completed","failed","killed"]),Ii=1440*60*1e3;function Ef(t){return t instanceof Error?t.message:String(t)}var $r=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;backendIdIndex=new Map;actionTokens;actionTokenStore;indexPath;queries;constructor(e={}){let n=e.env??process.env;this.indexPath=e.indexPath??$d(n),this.actionTokenStore=new xr(()=>this.saveIndex(),Ii),this.actionTokens=this.actionTokenStore.tokens,this.queries=new Tr({persisted:this.persisted,idIndex:this.idIndex,nameIndex:this.nameIndex,backendIdIndex:this.backendIdIndex}),n.OPENCLAW_DEBUG_SESSION_STORE==="1"&&`${this.indexPath}`,this.loadIndex()}loadIndex(){Ld({indexPath:this.indexPath,clearAll:()=>{this.persisted.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)},purgeExpiredActionTokens:()=>this.actionTokenStore.purgeExpiredActionTokens(),saveIndex:()=>this.saveIndex()})}saveIndex(){Dd(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(e){Mr(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){let n=Co(e),r=n==="codex"?"codex-app-server":n==="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 n=typeof e.controlStateSnapshot=="function"?e.controlStateSnapshot():{planModeApproved:!1};return{requestedPermissionMode:e.requestedPermissionMode,currentPermissionMode:e.currentPermissionMode,approvalExecutionState:e.approvalExecutionState,approvalRationale:e.approvalRationale,planModeApproved:n.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,worktreeBaseBranch:e.worktreeBaseBranch,worktreePrTargetRepo:e.worktreePrTargetRepo,autoMergeParentSessionId:e.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:e.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:e.autoMergeResolverSessionId,worktreeLifecycle:e.worktreeLifecycle}}indexPersistedEntry(e){let n=this.getEntryStorageKey(e);this.persisted.set(n,e),e.sessionId&&this.idIndex.set(e.sessionId,n),e.name&&this.nameIndex.set(e.name,n);let r=T(e);r&&this.backendIdIndex.set(r,n)}removePersistedIndexes(e){let n=this.getEntryStorageKey(e);this.persisted.delete(n);for(let[r,o]of this.idIndex)o===n&&this.idIndex.delete(r);for(let[r,o]of this.nameIndex)o===n&&this.nameIndex.delete(r);for(let[r,o]of this.backendIdIndex)o===n&&this.backendIdIndex.delete(r)}markRunning(e){if(!e.harnessSessionId)return;let n=this.getSessionApprovalSnapshot(e),r=this.getSessionRoutingSnapshot(e),o=this.getSessionWorktreeSnapshot(e),i=Oe({route:r.route,originChannel:r.originChannel,originThreadId:r.originThreadId,originSessionKey:r.originSessionKey});if(!i)return;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,deliveryState:e.deliveryState,notificationDedupe:this.getExistingNotificationDedupe(e),costUsd:0,originAgentId:r.originAgentId,originChannel:r.originChannel,originThreadId:r.originThreadId,originSessionKey:r.originSessionKey,route:i,harness:e.harnessName,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,approvalRationale:n.approvalRationale,planModeApproved:n.planModeApproved,pendingPlanApproval:n.pendingPlanApproval,planApprovalContext:n.planApprovalContext,planDecisionVersion:n.planDecisionVersion,actionablePlanDecisionVersion:n.actionablePlanDecisionVersion,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,planApproval:n.planApproval,codexApprovalPolicy:n.codexApprovalPolicy,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,worktreeBaseBranch:o.worktreeBaseBranch,worktreePrTargetRepo:o.worktreePrTargetRepo,autoMergeParentSessionId:o.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:o.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:o.autoMergeResolverSessionId,worktreeLifecycle:o.worktreeLifecycle,resumable:e.isExplicitlyResumable};Mr(s),this.indexPersistedEntry(s),this.saveIndex()}hasRecordedSession(e){return this.queries.hasRecordedSession(e)}persistTerminal(e){if(!e.harnessSessionId)return;let n=this.getSessionApprovalSnapshot(e),r=this.getSessionRoutingSnapshot(e),o=this.getSessionWorktreeSnapshot(e),i=Oe({route:r.route,originChannel:r.originChannel,originThreadId:r.originThreadId,originSessionKey:r.originSessionKey});if(!i)return;let s;try{let d=st(e.id);if(Cf(d))s=d;else{let l=e.getOutput().join(`
|
|
219
|
+
`);l.length>0&&(Mf(d,l,"utf-8"),s=d)}}catch(d){`${e.id}${Ef(d)}`}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,deliveryState:e.deliveryState,notificationDedupe:this.getExistingNotificationDedupe(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,goalTaskId:e.goalTaskId,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,approvalRationale:n.approvalRationale,planModeApproved:n.planModeApproved,pendingPlanApproval:n.pendingPlanApproval,planApprovalContext:n.planApprovalContext,planDecisionVersion:n.planDecisionVersion,actionablePlanDecisionVersion:n.actionablePlanDecisionVersion,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,planApproval:n.planApproval,codexApprovalPolicy:n.codexApprovalPolicy,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,worktreeBaseBranch:o.worktreeBaseBranch,worktreePrTargetRepo:o.worktreePrTargetRepo,autoMergeParentSessionId:o.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:o.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:o.autoMergeResolverSessionId,worktreeLifecycle:o.worktreeLifecycle,resumable:e.isExplicitlyResumable};Mr(a),this.indexPersistedEntry(a),this.saveIndex()}getExistingNotificationDedupe(e){return this.getPersistedSession(e.id)?.notificationDedupe??(e.harnessSessionId?this.getPersistedSession(e.harnessSessionId)?.notificationDedupe:void 0)??(T(e)?this.getPersistedSession(T(e))?.notificationDedupe:void 0)}getLatestPersistedByName(e){return this.queries.getLatestPersistedByName(e)}resolveBackendConversationId(e,n){return this.queries.resolveBackendConversationId(e,n)}resolveHarnessSessionId(e,n){return this.queries.resolveHarnessSessionId(e,n)}getPersistedSession(e){return this.queries.getPersistedSession(e)}listPersistedSessions(){return this.queries.listPersistedSessions()}cleanupTmpOutputFiles(e){this.actionTokenStore.purgeExpiredActionTokens(e),Od(e,Ii)}getNextTmpOutputCleanupAt(e){return Nd(e,Ii)}evictOldestPersisted(e){let n=this.listPersistedSessions();if(n.length<=e)return[];let r=n.slice(e);for(let o of r)this.removePersistedIndexes(o);return this.saveIndex(),r}shouldGcActiveSession(e,n,r){return!e.completedAt||!_f.has(e.status)?!1:n-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()){this.actionTokenStore.purgeExpiredActionTokens(e)}getNextActionTokenExpiry(){return this.actionTokenStore.nextExpiryAt()}onActionTokensChanged(e){this.actionTokenStore.setAfterChangeListener(e)}hasOutputPathReference(e){for(let n of this.persisted.values())if(n.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(){Wd(this.getReferencedOutputPaths())}};var $f=new Set(["completed","failed","killed"]),Dr=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 n=e.costUsd??0,r=e.status;this.metrics.totalCostUsd+=n;let o=new Date(e.completedAt??e.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+n),$f.has(r)&&this.metrics.sessionsByStatus[r]++,e.completedAt){let i=e.completedAt-e.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||n>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:e.id,name:e.name,costUsd:n,prompt:ne(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 qd from"child_process";var Bd=5e3,Df=64,Of={primary:"primary",success:"success",positive:"success",danger:"danger",destructive:"danger",negative:"danger"},Nf={execFile:qd.execFile},De=class extends Error{constructor(e){super(e),this.name="MissingRuntimeDirectNotificationCapabilityError"}},Or=class{constructor(e=Nf.execFile){this.execFile=e}execFile;async send(e,n,r){D("direct_send_started",{...ye(e),messageTextLength:n.length,...G(r)});try{await this.sendViaRuntime(e,n,r),D("direct_send_succeeded",{...ye(e),deliveryPath:"runtime",...G(r)});return}catch(o){if(!(o instanceof De))throw D("direct_send_failed",{...ye(e),deliveryPath:"runtime",...G(r),error:xi(o)}),o;D("direct_send_runtime_capability_missing",{...ye(e),deliveryPath:"runtime",...G(r),reason:o.message}),await this.sendViaBoundedCliFallback(e,n,r,o.message),D("direct_send_succeeded",{...ye(e),deliveryPath:"cli-fallback",...G(r)})}}async sendViaRuntime(e,n,r){let o=wn(),i=Ps(),s=o?.channel?.outbound?.loadAdapter;if(!o)throw new De("OpenClaw plugin runtime is unavailable for direct notification delivery");if(i==null)throw new De("OpenClaw runtime config snapshot is unavailable for direct notification delivery");if(!o.channel)throw new De(`OpenClaw plugin runtime channel surface is unavailable for direct notification delivery (runtimeVersion=${Ti(o)})`);if(!o.channel.outbound)throw new De(`OpenClaw plugin runtime channel outbound surface is unavailable for direct notification delivery (runtimeVersion=${Ti(o)})`);if(!s)throw new De(`OpenClaw plugin runtime channel outbound loadAdapter is unavailable for direct notification delivery (runtimeVersion=${Ti(o)})`);let a=await s(e.channel);if(!a)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" is unavailable`);let d=Nr(r);if(D("runtime_adapter_loaded",{...ye(e),adapterHasRenderPresentation:typeof a.renderPresentation=="function",adapterHasSendPayload:typeof a.sendPayload=="function",adapterHasSendText:typeof a.sendText=="function",...G(r),...d?ri(d):{}}),d){await this.sendPresentation(a,i,e,n,d);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:n,accountId:e.accountId,threadId:e.threadId})}async sendPresentation(e,n,r,o,i){let s=Lf(i),a={text:o,presentation:i,interactive:s};D("presentation_render_started",{...ye(r),messageTextLength:o.length,adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...ri(i)});let d={cfg:n,to:r.target,text:o,payload:a,accountId:r.accountId,threadId:r.threadId},l=e.renderPresentation?await e.renderPresentation({payload:a,presentation:i,ctx:d}):a,u=Ff(l,s,r.channel);if(D("presentation_render_completed",{...ye(r),adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...oi(u)}),!u||typeof u!="object"||!e.sendPayload)throw new Error(`OpenClaw outbound adapter for channel "${r.channel}" cannot preserve interactive presentation`);let p=await e.sendPayload({...d,payload:u});D("presentation_send_payload_completed",{...ye(r),...oi(u),...Ma(p)})}sendViaBoundedCliFallback(e,n,r,o){return new Promise((i,s)=>{let a=Wf(e,n,r);D("direct_send_cli_fallback_started",{...ye(e),deliveryPath:"cli-fallback",reason:o,messageTextLength:n.length,...G(r)}),this.execFile("openclaw",a,{timeout:Bd,killSignal:"SIGKILL"},(d,l,u)=>{if(!d){D("direct_send_cli_fallback_completed",{...ye(e),deliveryPath:"cli-fallback",...G(r)}),i();return}let p=u?.trim()?` | stderr: ${u.trim()}`:"";D("direct_send_cli_fallback_failed",{...ye(e),deliveryPath:"cli-fallback",...G(r),error:xi(d),stderrLength:u?.length}),s(new Error(`${o}; bounded openclaw message send fallback failed within ${Bd}ms timeout: ${xi(d)}${p}`))})})}};function ye(t){return{channel:t.channel,target:t.target,accountId:t.accountId,threadId:t.threadId,sessionKey:t.sessionKey}}function Wf(t,e,n){let r=Nr(n),o=["message","send","--channel",t.channel,"--target",t.target,"--message",e];return t.accountId&&o.push("--account",t.accountId),t.threadId&&o.push("--thread-id",t.threadId),r&&o.push("--presentation",JSON.stringify(r)),o}function xi(t){return t instanceof Error?t.message:String(t)}function Ti(t){if(!t||typeof t!="object")return"unknown";let e=t.version;return typeof e=="string"&&e.trim()?e:"unknown"}function Nr(t){let e=(t??[]).filter(n=>Array.isArray(n)&&n.length>0).map(n=>({type:"buttons",buttons:n.map(r=>({label:r.label,value:Gf(r.callbackData),...r.style?{style:r.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function Lf(t){let e=t.blocks.filter(n=>n.type==="buttons"&&n.buttons.length>0).map(n=>({type:"buttons",buttons:n.buttons.map(r=>({label:r.label,value:r.value,...r.style?{style:r.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function Bf(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t.interactive;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e.blocks;return Array.isArray(n)&&n.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 Ff(t,e,n){if(!e)return t;let r=Bf(t)?t:qf(t,e);return n!=="telegram"?r:Kf(r,e)}function qf(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:{...t,interactive:e}}function Kf(t,e){if(!t||typeof t!="object"||Array.isArray(t))return t;let n=t,r=Fd(n.channelData),o=Fd(r?.telegram),i=Vf(o?.buttons);if(i)return{...n,channelData:{...r??{},telegram:{...o??{},buttons:i}}};let s=Uf(e);return s?{...n,channelData:{...r??{},telegram:{...o??{},buttons:s}}}:t}function Uf(t){let e=t.blocks.filter(n=>n.type==="buttons"&&n.buttons.length>0).map(n=>n.buttons.filter(r=>typeof r.value=="string"&&r.value.trim().length>0&&Buffer.byteLength(r.value,"utf8")<=Df).map(r=>({text:r.label,callback_data:r.value,...Kd(r.style)}))).filter(n=>n.length>0);return e.length>0?e:void 0}function Vf(t){if(!Array.isArray(t))return;let e=t.map(n=>Array.isArray(n)?n.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))return{...i,...Kd(o)}}).filter(r=>!!r):[]).filter(n=>n.length>0);return e.length>0?e:void 0}function Kd(t){if(typeof t!="string")return{};let e=t.trim().toLowerCase(),n=Of[e];return n?{style:n}:{}}function Fd(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Gf(t){return t.startsWith(`${ge}:`)?t:`${ge}:${t}`}import*as Ud from"child_process";var ht=class{tails=new Map;enqueue(e,n,r){let o=this.tails.get(e);o!==void 0&&r?.();let s=(o?.catch(()=>{})??Promise.resolve()).then(()=>n()),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 Ci=3e4,Hf=2e3,jf=2e4,pe=4;function zt(t){return t instanceof Error?t.message:String(t)}function zf(){return new Error(`Dispatch timed out after ${Ci}ms`)}function Qf(t){if(!(t instanceof Error))return!1;let e=t;return e.killed===!0&&e.signal==="SIGKILL"}var Jf={execFile:Ud.execFile},Wr=class{pendingRetryTimers=new Map;orderedDispatches=new ht;disposed=!1;clearPendingRetries(){for(let e of this.pendingRetryTimers.values())for(let n of e)clearTimeout(n.timer),n.onCleared?.();this.pendingRetryTimers.clear()}clearRetryTimersForSession(e){let n=this.pendingRetryTimers.get(e);if(n){for(let r of n)clearTimeout(r.timer),r.onCleared?.();this.pendingRetryTimers.delete(e)}}dispose(){this.disposed=!0,this.clearPendingRetries(),this.orderedDispatches.clear()}execute(e,n,r=1){if(!this.disposed){if(r===1&&n.orderingKey){this.enqueueOrderedDispatch(n.orderingKey,o=>this.executeNow(e,n,o,r));return}this.executeNow(e,n,void 0,r)}}executePromise(e,n,r=1){if(!this.disposed){if(r===1&&n.orderingKey){this.enqueueOrderedDispatch(n.orderingKey,o=>this.executePromiseNow(e,n,o,r));return}this.executePromiseNow(e,n,void 0,r)}}executeNow(e,n,r,o=1){if(this.disposed||n.shouldContinue?.()===!1){r?.();return}let i=Date.now();o===1&&n.onStarted?.(),this.log("info","dispatch_started",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:pe}),Jf.execFile("openclaw",e,{timeout:Ci,killSignal:"SIGKILL"},(s,a,d)=>{if(this.disposed){r?.();return}let l=Date.now()-i;if(!s){let g=n.successValidator?.(a??"");if(g?.outcome==="failure"){this.log("error","dispatch_success_validation_failed",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:pe,elapsedMs:l,error:g.reason,terminal:!0}),n.onFinalFailure?.(),r?.();return}if(g?.outcome==="skipped"){this.log("info","dispatch_skipped",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:pe,elapsedMs:l,reason:g.reason}),n.shouldContinue?.()!==!1&&n.onSkipped?.(g.reason),r?.();return}this.log("info","dispatch_succeeded",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:pe,elapsedMs:l}),n.shouldContinue?.()!==!1&&n.onSuccess?.(),r?.();return}let u=d?.trim()?` | stderr: ${d.trim()}`:"";if(n.target==="message.send"&&Qf(s)){this.log("error","dispatch_failed",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:pe,elapsedMs:l,error:`${zt(s)}${u}`,terminal:!0,ambiguousResult:!0}),n.onAmbiguousResult?.(),r?.();return}if(o>=pe||n.terminalOnFailure===!0){this.log("error","dispatch_failed",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:pe,elapsedMs:l,error:`${zt(s)}${u}`,terminal:!0}),n.onFinalFailure?.(),r?.();return}let c=this.retryDelayMs(o);this.log("error","dispatch_retry_scheduled",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:pe,elapsedMs:l,retryDelayMs:c,error:`${zt(s)}${u}`});let f={timer:setTimeout(()=>{let g=this.pendingRetryTimers.get(n.sessionId);if(g&&(g.delete(f),g.size===0&&this.pendingRetryTimers.delete(n.sessionId)),n.shouldContinue?.()===!1){r?.();return}this.executeNow(e,n,r,o+1)},c),onCleared:r};f.timer.unref?.(),this.pendingRetryTimers.has(n.sessionId)||this.pendingRetryTimers.set(n.sessionId,new Set),this.pendingRetryTimers.get(n.sessionId).add(f)})}executePromiseNow(e,n,r,o=1){if(this.disposed||n.shouldContinue?.()===!1){r?.();return}let i=Date.now();o===1&&n.onStarted?.(),this.log("info","dispatch_started",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:pe}),this.executePromiseWithTimeout(e).then(()=>{if(this.disposed){r?.();return}let s=Date.now()-i;this.log("info","dispatch_succeeded",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:pe,elapsedMs:s}),n.shouldContinue?.()!==!1&&n.onSuccess?.(),r?.()}).catch(s=>{if(this.disposed){r?.();return}let a=Date.now()-i;if(o>=pe||n.terminalOnFailure===!0){this.log("error","dispatch_failed",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:pe,elapsedMs:a,error:zt(s),terminal:!0,...n.terminalOnFailure===!0&&o<pe?{terminalReason:"non_retryable"}:{}}),n.onFinalFailure?.(),r?.();return}let d=this.retryDelayMs(o);this.log("error","dispatch_retry_scheduled",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:pe,elapsedMs:a,retryDelayMs:d,error:zt(s)});let l={timer:setTimeout(()=>{let u=this.pendingRetryTimers.get(n.sessionId);if(u&&(u.delete(l),u.size===0&&this.pendingRetryTimers.delete(n.sessionId)),n.shouldContinue?.()===!1){r?.();return}this.executePromiseNow(e,n,r,o+1)},d),onCleared:r};l.timer.unref?.(),this.pendingRetryTimers.has(n.sessionId)||this.pendingRetryTimers.set(n.sessionId,new Set),this.pendingRetryTimers.get(n.sessionId).add(l)})}executePromiseWithTimeout(e){return new Promise((n,r)=>{let o=!1,i=setTimeout(()=>{o||(o=!0,r(zf()))},Ci);i.unref?.(),Promise.resolve().then(e).then(()=>{o||(o=!0,clearTimeout(i),n())}).catch(s=>{o||(o=!0,clearTimeout(i),r(s))})})}retryDelayMs(e){let n=Math.max(0,e-1),r=Hf*2**n;return Math.min(r,jf)}enqueueOrderedDispatch(e,n){this.orderedDispatches.enqueue(e,async()=>{this.disposed||await new Promise(r=>{let o=!1;n(()=>{o||(o=!0,r())})})})}log(e,n,r){let o=`[WakeDispatcher] ${JSON.stringify({event:n,...r})}`;if(e==="error"){console.error(o);return}}};ke();var Lr=class{resolve(e){let n=Ae(e);if(!(!n?.provider||!n.target))return{channel:n.provider,target:n.target,accountId:n.accountId,threadId:n.threadId,sessionKey:n.sessionKey}}summary(e){if(!e)return"system";let n=e.accountId?`|${e.accountId}`:"",r=e.threadId?`#${e.threadId}`:"";return`${e.channel}${n}|${e.target}${r}`}};import{randomUUID as Yf}from"crypto";var Br=class{constructor(e={}){this.options=e}options;buildChatSendArgs(e,n,r,o=Yf()){return["gateway","call","chat.send","--expect-final","--timeout","30000","--params",JSON.stringify({sessionKey:e,message:n,deliver:r,idempotencyKey:o})]}buildDirectNotificationArgs(e,n,r){let o=Nr(r),i=["message","send","--channel",e.channel,"--target",e.target,"--message",n];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 Zf(t){let e=Xf(t).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 Xf(t){let e=t.trim();if(!e)return"";try{return Mi(JSON.parse(e)).trim()}catch{return e}}function Mi(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>Mi(r)).filter(Boolean).join(`
|
|
220
|
+
`);if(!t||typeof t!="object")return"";let e=t,n=["final","finalResponse","final_response","assistantFinal","assistant_final","response","text","content"];for(let r of n){let o=e[r];if(typeof o=="string"&&o.trim())return o}for(let r of["result","message","data"]){let o=Mi(e[r]);if(o.trim())return o}return""}var Fr=class{routes=new Lr;transport;directNotifications;executor=new Wr;constructor(e={}){this.transport=e.transport??new Br(e.transportOptions),this.directNotifications=e.directNotifications===void 0?new Or:e.directNotifications}clearPendingRetries(){this.executor.clearPendingRetries()}clearRetryTimersForSession(e){this.executor.clearRetryTimersForSession(e)}dispose(){this.executor.dispose()}buildDispatchContext(e){let n=e.buttons??[],r=n.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:n.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,n,r,o,i,s,a,d,l,u){let p=this.routes.resolve(e),c=a;if(c?.()===!1)return;let f=p?.sessionKey?.trim();if(!f){this.executor.execute(this.transport.buildSystemEventArgs(n),{label:`${r}-system`,sessionId:e.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:n}),onSuccess:s,onSkipped:l,onFinalFailure:i,successValidator:d,shouldContinue:c});return}this.executor.execute(this.transport.buildChatSendArgs(f,n,!0,u),{label:r,sessionId:e.id,target:"chat.send",phase:o,routeSummary:`session:${f}`,messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:`session:${f}`,route:p,text:n}),onSuccess:s,onSkipped:l,successValidator:d,shouldContinue:c,onFinalFailure:()=>{c?.()!==!1&&this.executor.execute(this.transport.buildSystemEventArgs(n),{label:`${r}-fallback`,sessionId:e.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:n}),onSuccess:s,onSkipped:l,onFinalFailure:i,successValidator:d,shouldContinue:c})}})}sendUserNotification(e,n,r,o,i,s,a=!1,d){if(d?.()===!1)return;let l=!!o?.some(g=>Array.isArray(g)&&g.length>0),u=this.routes.resolve(e);D("wake_notify_selected",{sessionId:e.id,sessionName:e.name,label:r,messageTextLength:n.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,...G(o)});let p=u?`notify:${u.channel}|${u.accountId??""}|${u.target}|${u.threadId??""}`:`notify:system:${e.id}`;if(!u){if(D("wake_notify_no_direct_route",{sessionId:e.id,sessionName:e.name,label:r,requireDirectDelivery:a,hasInteractiveButtons:l,...G(o)}),a){`${r}${e.id}`,i?.();return}if(l){`${r}${e.id}`,i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(n),{label:`${r}-notify-system`,sessionId:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:n,buttons:o}),orderingKey:p,onSuccess:s,onFinalFailure:i,shouldContinue:d});return}let c=()=>{if(D("wake_notify_direct_failed",{sessionId:e.id,sessionName:e.name,label:r,requireDirectDelivery:a,hasInteractiveButtons:l,channel:u.channel,target:u.target,accountId:u.accountId,threadId:u.threadId,sessionKey:u.sessionKey,...G(o)}),a){`${r}${e.id}`,i?.();return}if(l){`${r}${e.id}`,i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(n),{label:`${r}-notify-fallback`,sessionId:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:n}),orderingKey:p,onSuccess:s,onFinalFailure:i,shouldContinue:d})},f={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:n,buttons:o}),orderingKey:p,onSuccess:s,onAmbiguousResult:c,onFinalFailure:c,terminalOnFailure:this.directNotifications?!0:void 0,shouldContinue:d};if(this.directNotifications){D("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,...G(o)}),this.executor.executePromise(()=>this.directNotifications.send(u,n,o),f);return}D("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,...G(o)}),this.executor.execute(this.transport.buildDirectNotificationArgs(u,n,o),f)}sendUserNotificationSequence(e,n,r,o,i,s=!1,a){let d=n.map(u=>({text:u.text.trim(),buttons:u.buttons})).filter(u=>u.text.length>0);if(d.length===0){o?.();return}D("wake_notify_sequence_started",{sessionId:e.id,sessionName:e.name,label:r,chunkCount:d.length,buttonChunkIndexes:d.map((u,p)=>u.buttons?.some(c=>Array.isArray(c)&&c.length>0)?p+1:void 0).filter(u=>typeof u=="number"),requireDirectDelivery:s});let l=u=>{if(a?.()===!1)return;let p=d[u];if(!p){D("wake_notify_sequence_succeeded",{sessionId:e.id,sessionName:e.name,label:r,chunkCount:d.length}),i?.();return}let c=u===0?o:i;D("wake_notify_sequence_chunk_selected",{sessionId:e.id,sessionName:e.name,label:r,chunkIndex:u+1,chunkCount:d.length,messageTextLength:p.text.length,failureHandler:u===0?"all-failed":"sequence-success",...G(p.buttons)}),this.sendUserNotification(e,p.text,`${r}-part-${u+1}`,p.buttons,c,()=>l(u+1),s,a)};l(0)}dispatchSessionNotification(e,n){let r=n.hooks,o=n.wakeMessageOnNotifySuccess!=null||n.wakeMessageOnNotifyFailed!=null,i=n.notifyUser??(n.wakeMessage?"on-wake-fallback":"always"),s=(n.userMessages?.length?n.userMessages:n.userMessage?.trim()?[{text:n.userMessage.trim(),buttons:n.buttons}]:[]).map(p=>({text:p.text.trim(),buttons:p.buttons})).filter(p=>p.text.length>0),a=s[0]?.text,d=n.wakeMessage?.trim(),l=n.shouldDispatch,u=n.completionWakeSummaryRequired===!0?Zf:void 0;if(o){let p=n.wakeMessageOnNotifySuccess?.trim(),c=n.wakeMessageOnNotifyFailed?.trim(),f=k=>{k&&l?.()!==!1&&(r?.onWakeStarted?.(),this.sendWake(e,k,`${n.label}-wake`,"wake",r?.onWakeFailed,r?.onWakeSucceeded,l,u,r?.onWakeSkipped,n.idempotencyKey))},g=k=>{if(k){if(n.deferConditionalWakeUntilNextTick===!0||n.deferConditionalWakeMs!==void 0){let b=Math.max(0,Math.floor(n.deferConditionalWakeMs??0));setTimeout(()=>f(k),b).unref?.();return}f(k)}},h=()=>{l?.()!==!1&&(r?.onNotifySucceeded?.(),p&&g(p))},y=c?()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.(),g(c))}:()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.())};if(s.length>0){if(l?.()===!1)return;r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,n.label,y,h,n.requireDirectUserNotification===!0,l)}else y();return}if(i==="always"&&s.length>0){if(l?.()===!1)return;r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,n.label,()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.())},()=>{l?.()!==!1&&r?.onNotifySucceeded?.()},n.requireDirectUserNotification===!0,l)}if(d&&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,n.label,()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.())},()=>{l?.()!==!1&&r?.onNotifySucceeded?.()},!1,l)}this.sendWake(e,d,`${n.label}-wake`,"wake",r?.onWakeFailed,r?.onWakeSucceeded,l,u,r?.onWakeSkipped,n.idempotencyKey)}}};var qr=class{constructor(e,n){this.actionTokens=e;this.isGitHubCliAvailable=n}actionTokens;isGitHubCliAvailable;createActionToken(e,n,r={}){return this.actionTokens.createActionToken(e,n,{expiresAt:Date.now()+10080*60*1e3,...r})}consumeActionToken(e){return this.actionTokens.consumeActionToken(e)}getActionToken(e){return this.actionTokens.getActionToken(e)}clearPlanDecisionTokens(e,n){this.actionTokens.deletePlanDecisionTokensForSession(e,n)}makeActionButton(e,n,r,o={}){let i=this.createActionToken(e,n,{label:r,...o});return{label:r,callbackData:i.id,style:this.resolveButtonStyle(n)}}resolveButtonStyle(e){switch(e){case"plan-approve":case"worktree-create-pr":case"worktree-update-pr":case"plan-offer-start":return"primary";case"worktree-merge":case"session-resume":case"session-restart":return"success";case"plan-reject":case"worktree-dismiss":return"danger";default:return"secondary"}}getWorktreeDecisionButtons(e,n){if(!n)return[];let r=[],o=[this.makeActionButton(e,"worktree-merge","Merge")];if(this.isGitHubCliAvailable())n.worktreePrUrl?(o.push(this.makeActionButton(e,"worktree-view-pr","View PR",{targetUrl:n.worktreePrUrl})),r.push(o),r.push([this.makeActionButton(e,"worktree-update-pr","Sync PR"),this.makeActionButton(e,"worktree-decide-later","Later")])):(o.push(this.makeActionButton(e,"worktree-create-pr","Open PR")),r.push(o),r.push([this.makeActionButton(e,"worktree-decide-later","Later"),this.makeActionButton(e,"worktree-dismiss","Discard")]));else return r.push([...o,this.makeActionButton(e,"worktree-decide-later","Later")]),r.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),r;return n.worktreePrUrl&&r.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),r}getPlanApprovalButtons(e,n){let r=[[this.makeActionButton(e,"plan-approve","Approve",{planDecisionVersion:n?.planDecisionVersion}),this.makeActionButton(e,"plan-request-changes","Revise",{planDecisionVersion:n?.planDecisionVersion}),this.makeActionButton(e,"plan-reject","Reject",{planDecisionVersion:n?.planDecisionVersion})]];return D("plan_approval_buttons_created",{sessionId:e,planDecisionVersion:n?.planDecisionVersion,...G(r)}),r}getResumeButtons(e,n){let r=[];return n.isExplicitlyResumable&&r.push(this.makeActionButton(e,"session-resume","Resume")),r.push(this.makeActionButton(e,"view-output","View output")),[r]}getQuestionButtons(e,n){if(n.length!==0)return[n.map((r,o)=>this.makeActionButton(e,"question-answer",r.label,{optionIndex:o}))]}getPlanOfferButtons(e){let{offerId:n,route:r,planName:o,planPrompt:i,planWorkdir:s,planWorktreeStrategy:a}=e,d=[[this.makeActionButton(n,"plan-offer-start","Start Plan",{route:r,launchName:o,launchPrompt:i,launchWorkdir:s,launchWorktreeStrategy:a}),this.makeActionButton(n,"plan-offer-dismiss","Dismiss",{route:r})]];return D("plan_offer_buttons_created",{offerId:n,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,...G(d)}),d}};Q();ke();import{createHash as rg}from"crypto";var eg="duplicate notification already delivered or in flight",Kr=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,n,r){if(!e)return{allowed:!0};let o=this.now(),i=this.prune(n??[],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:eg}:(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,n,r){if(!e)return;let o=this.now();return this.inFlight.delete(e),this.delivered.add(e),this.upsert(this.prune(n??[],o),{key:e,status:"delivered",recordedAt:o.toISOString(),label:r})}releasedRecords(e,n){if(!e)return;let r=this.now();return this.inFlight.delete(e),this.prune(n??[],r).filter(o=>!(o.key===e&&o.status==="in_flight"))}prune(e,n){let r=e.filter(o=>o.status==="delivered"?!0:this.isFreshInFlight(o,n));return r.slice(Math.max(0,r.length-this.maxRecords))}isFreshInFlight(e,n){let r=Date.parse(e.recordedAt);return Number.isFinite(r)?n.getTime()-r<this.inFlightTtlMs:!1}upsert(e,n){let o=[...e.filter(i=>i.key!==n.key),n];return o.slice(Math.max(0,o.length-this.maxRecords))}};ke();Q();ke();import{createHash as tg}from"crypto";var ng=1024,Qt="duplicate completion follow-up wake already handled",Ur="prior human-visible summary already delivered",Vr=class{inFlight=new Set;completed=new Map;claimKeysByPrimary=new Map;maxCompletedKeys;constructor(e={}){this.maxCompletedKeys=Math.max(1,Math.floor(e.maxCompletedKeys??ng))}decide(e,n,r){if(n?.required!==!0)return{required:!1,allowed:!1,explicit:!1};let o=this.buildKeySet(e,n);if(!o)return{required:!0,allowed:!0,explicit:!1};let i=this.normalizeRecords(r),s=new Map(i.map(u=>[u.key,u])),a=o.decisionKeys.find(u=>this.inFlight.has(u)||this.completed.has(u)||s.has(u)),d=a?this.completed.get(a):void 0,l=a?s.get(a):void 0;return a?{required:!0,allowed:!1,explicit:o.explicit,dedupeKey:o.primary,skipReason:d?.skipReason??l?.skipReason??Qt}:(this.registerClaim(o.primary,o.claimKeys),{required:!0,allowed:!0,key:o.primary,explicit:o.explicit})}recordVisibleDelivery(e,n,r,o){if(n.required!==!0)return{required:!1,allowed:!1,explicit:!1};let i=this.buildKeySet(e,n);if(!i)return{required:!0,allowed:!0,explicit:!1};let s=this.normalizeRecords(r),a=new Map(s.map(c=>[c.key,c])),d=i.decisionKeys.find(c=>this.completed.has(c)||a.has(c)),l=d?this.completed.get(d):void 0,u=d?a.get(d):void 0;if(l||u)return{required:!0,allowed:!1,explicit:i.explicit,dedupeKey:i.primary,skipReason:l?.skipReason??u?.skipReason};this.finishKeys(i.primary,i.claimKeys,!0,Ur);let p=this.deliveredRecords(i.claimKeys,s,o,Ur);return{required:!0,allowed:!0,key:i.primary,explicit:i.explicit,records:p}}finish(e,n,r=Qt){if(!e)return;let o=this.claimKeysByPrimary.get(e)??[e];this.finishKeys(e,o,n,r)}completionRecordsAfterDelivery(e,n,r,o=Qt){if(!e)return;let i=this.claimKeysByPrimary.get(e)??[e];return this.deliveredRecords(i,n,r,o)}registerClaim(e,n){for(let r of n)this.inFlight.add(r);for(this.claimKeysByPrimary.delete(e),this.claimKeysByPrimary.set(e,n);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,n,r,o=Qt){for(let i of n)this.inFlight.delete(i);if(this.claimKeysByPrimary.delete(e),!!r){for(let i of n)this.completed.get(i)?.skipReason===Ur&&o!==Ur||(this.completed.delete(i),this.completed.set(i,{skipReason:o}));for(;this.completed.size>this.maxCompletedKeys;){let i=this.completed.keys().next().value;if(i===void 0)break;this.completed.delete(i)}}}buildKeySet(e,n){let r=this.getDeliveryRef(e);if(!r)return;let o=this.normalizeOutcomeKey(e,n.outcomeKey?.trim());if(o){let a=`${this.buildVisibleScope(r,e)}:outcome:${this.digest(o)}`,d=this.isGoalLike(e,n,o),l=this.buildSessionAliasKeys(r,e,"visible-summary"),u=this.buildSessionAliasKeys(r,e,"goal-summary"),p=this.isTerminalLike(n,o);return{primary:a,explicit:!0,claimKeys:[a,...l,...d?u:[]],decisionKeys:[a,...d||p?l:[],...u]}}let i=n.fallbackFingerprint?.trim();if(!i)return;let s=`${r}:${n.producer}:${this.digest(i)}`;return{primary:s,explicit:!1,claimKeys:[s],decisionKeys:[s]}}isGoalLike(e,n,r){return!!e.goalTaskId?.trim()||n.producer==="goal"||/^goal:/i.test(r)}isTerminalLike(e,n){return e.producer==="terminal"||/^terminal:/i.test(n)}normalizeOutcomeKey(e,n){let r=e.goalTaskId?.trim();if(r)return`goal:${r}`;let o=this.normalizeWorktreePrOutcomeKey(n);return o||n}normalizeWorktreePrOutcomeKey(e){if(!e)return;let n=e.split(":");if(n[0]!=="worktree-pr"||n.length<5)return;let r=n[1]?.trim().toLowerCase();if(!r||!/^(?:draft-)?(?:opened|updated)$/.test(r))return;let o=n[2]?.trim()||"default-repo",i=n[3]?.trim();if(!i)return;let s=this.normalizePrIdentity(i),a=n[4]?.trim();if(!(!s||!a))return["worktree-pr",o.toLowerCase(),s,a].join(":")}normalizePrIdentity(e){let n=e.match(/#?(\d+)$/);if(n?.[1])return`#${n[1]}`;let r=e.match(/\/pull\/(\d+)(?:\b|\/|$)/);if(r?.[1])return`#${r[1]}`;let o=e.trim();return o||void 0}buildVisibleScope(e,n){let r=Ae(n);return r?`route:${this.digest(JSON.stringify({provider:r.provider,accountId:r.accountId,target:r.target,threadId:r.threadId}))}`:e}buildSessionAliasKeys(e,n,r){let o=this.buildVisibleScope(e,n),i=["id"in n?n.id:void 0,"sessionId"in n?n.sessionId:void 0,n.name,T(n),n.harnessSessionId,e].map(s=>s?.trim()).filter(s=>!!s);return[...new Set(i)].map(s=>`${o}:session:${this.digest(s)}:${r}`)}getDeliveryRef(e){return N(e)??T(e)??""}digest(e){return tg("sha256").update(e).digest("hex").slice(0,16)}normalizeRecords(e){return e?.length?e.filter(n=>n.key.trim()&&Number.isFinite(Date.parse(n.recordedAt))).slice(-this.maxCompletedKeys):[]}deliveredRecords(e,n,r,o=Qt){let i=new Date().toISOString(),d=[...this.normalizeRecords(n).filter(l=>!e.includes(l.key)),...e.map(l=>({key:l,recordedAt:i,label:r,skipReason:o}))];return d.slice(Math.max(0,d.length-this.maxCompletedKeys))}};var og=2e3,ig=new Set(["1","true","yes","on"]);function sg(){let t=process.env.OPENCLAW_CODE_AGENT_NOTIFICATION_DIAGNOSTICS?.trim().toLowerCase();return!!(t&&ig.has(t))||ni()}function ag(t){sg()&&process.stderr.write(`[SessionNotification] ${JSON.stringify(t)}
|
|
221
|
+
`)}var Gr=class{constructor(e,n,r={}){this.wakeDispatcher=e;this.applyPersistedPatch=n;this.completionSummaries=new Vr({maxCompletedKeys:r.maxCompletedCompletionWakeKeys}),this.notificationDedupe=new Kr({maxRecords:r.maxNotificationDedupeRecords}),this.getPersistedSession=r.getPersistedSession}wakeDispatcher;applyPersistedPatch;completionSummaries;notificationDedupe;getPersistedSession;dispatch(e,n){let r=this.getDeliveryRef(e),o=this.getPersistedSession?.(r),i=this.buildNotificationDedupeKey(e,n),s=this.notificationDedupe.claim(i,o?.notificationDedupe,n.label);if(s.records&&this.applyNotificationDedupePatch(r,s.records),!s.allowed){this.logNotificationDecision({session:e,request:n,deliveryRef:r,dedupeKey:i,decision:"skip",reason:s.reason??"duplicate notification skipped",deliveryPath:"notify"}),n.hooks?.onDuplicateSkipped?.(s.reason??"duplicate notification skipped");return}let a=this.buildCompletionSummaryFact(n),d=n.completionSummaryOwner==="foreground"&&a?.required===!0,l=d?this.completionSummaries.recordVisibleDelivery(e,a,o?.completionSummaryDedupe,n.label):this.completionSummaries.decide(e,a,o?.completionSummaryDedupe);l.records&&this.applyCompletionSummaryDedupePatch(r,l.records);let u=d?this.withoutCompletionWake(n):n;if(l.required&&!l.allowed)if(this.logNotificationDecision({session:e,request:n,deliveryRef:r,dedupeKey:l.dedupeKey??l.key,outcomeKey:a?.outcomeKey,decision:d?"skip":l.explicit?"send_without_followup":"skip",reason:l.skipReason??"completion follow-up wake suppressed",deliveryPath:d?"foreground-summary":"wake",followupKind:a?.producer}),n.hooks?.onWakeSkipped?.(l.skipReason??"completion follow-up wake suppressed"),d){this.releaseNotificationDedupe(r,i);return}else if(l.explicit)u=this.withoutCompletionWake(n);else{this.releaseNotificationDedupe(r,i);return}a?.required===!0&&this.logNotificationDecision({session:e,request:u,deliveryRef:r,dedupeKey:l.dedupeKey??l.key,outcomeKey:a.outcomeKey,decision:d?"record_visible":u.completionWakeSummaryRequired===!0?"send_with_followup":"send_without_followup",reason:d?"foreground summary owns completion follow-up":void 0,deliveryPath:d?"foreground-summary":"wake",followupKind:a.producer});let p=this.buildCompletionWakePatch(u),c=!!(u.wakeMessage?.trim()||u.wakeMessageOnNotifySuccess?.trim()),f=!!(u.wakeMessage?.trim()||u.wakeMessageOnNotifyFailed?.trim()),g=!1,h=!1,y=()=>{h||(h=!0,g||(this.releaseNotificationDedupe(r,i),g=!0),this.completionSummaries.finish(l.key,!1))},k=u.shouldDispatch?()=>{let A=u.shouldDispatch?.()!==!1;return A||y(),A}:void 0,b={onNotifyStarted:()=>{this.applyDeliveryState(r,"notifying"),u.hooks?.onNotifyStarted?.()},onNotifySucceeded:()=>{g=!0,this.markNotificationDedupeDelivered(r,i,u.label),this.applyNotifyDeliveryState(r,c?"wake_pending":"idle",c?p:void 0),c||this.completionSummaries.finish(l.key,!1),u.hooks?.onNotifySucceeded?.()},onNotifyFailed:()=>{this.applyNotifyDeliveryState(r,f?"wake_pending":"failed",f?p:void 0),f||(this.completionSummaries.finish(l.key,!1),this.releaseNotificationDedupe(r,i),g=!0),u.hooks?.onNotifyFailed?.()},onWakeStarted:()=>{this.applyPersistedPatchWithCompletionWake(r,"wake_pending",p,{completionWakeIssuedAt:new Date().toISOString(),completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0,completionWakeSkippedAt:void 0,completionWakeSkipReason:void 0}),u.hooks?.onWakeStarted?.()},onWakeSucceeded:()=>{g=!0,this.markNotificationDedupeDelivered(r,i,u.label),this.markCompletionSummaryDelivered(r,l.key,u.label),this.applyPersistedPatchWithCompletionWake(r,"idle",this.buildCompletionWakeSucceededPatch(p),{completionWakeSucceededAt:new Date().toISOString(),completionWakeFailedAt:void 0,completionWakeSkippedAt:void 0,completionWakeSkipReason:void 0}),this.completionSummaries.finish(l.key,!0),u.hooks?.onWakeSucceeded?.()},onWakeSkipped:A=>{if(h){u.hooks?.onWakeSkipped?.(A);return}g=!0,this.markNotificationDedupeDelivered(r,i,u.label),this.markCompletionSummaryDelivered(r,l.key,u.label,A),this.applyPersistedPatchWithCompletionWake(r,"idle",this.buildCompletionWakeSucceededPatch(p),{completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0,completionWakeSkippedAt:new Date().toISOString(),completionWakeSkipReason:A}),this.completionSummaries.finish(l.key,!0),u.hooks?.onWakeSkipped?.(A)},onWakeFailed:()=>{this.applyPersistedPatchWithCompletionWake(r,"failed",p,{completionWakeFailedAt:new Date().toISOString()}),this.completionSummaries.finish(l.key,!1),this.releaseNotificationDedupe(r,i),g=!0,u.hooks?.onWakeFailed?.()}};this.wakeDispatcher.dispatchSessionNotification(e,{...u,idempotencyKey:i??u.idempotencyKey,shouldDispatch:k,hooks:b})}notifyWorktreeOutcome(e,n,r={}){let o=this.getDeliveryRef(e),i=l=>ft({sessionId:o,sessionName:e.name,outcomeLine:n,originThreadLine:vt(e),detailLines:r.detailLines,canonicalStatusDelivered:l}),s=r.summaryWakeRequired??!0,a={required:s,producer:"worktree-pr",outcomeKey:r.completionWakeOutcomeKey??`terminal:${o}`},d=r.completionSummaryOwner!=="foreground";if(s&&!d){let l=this.getDeliveryRef(e),u=this.completionSummaries.recordVisibleDelivery(e,a,l?this.getPersistedSession?.(l)?.completionSummaryDedupe:void 0,"worktree-outcome");u.records&&this.applyCompletionSummaryDedupePatch(l,u.records)}this.dispatch(e,{label:"worktree-outcome",userMessage:n,notifyUser:"always",requireDirectUserNotification:!0,completionSummary:{...a,required:s&&d},completionWakeSummaryRequired:s&&d,completionWakeOutcomeKey:r.completionWakeOutcomeKey??`terminal:${o}`,idempotencyKey:`worktree-outcome:${r.completionWakeOutcomeKey??n}`,deferConditionalWakeUntilNextTick:!0,deferConditionalWakeMs:og,wakeMessageOnNotifySuccess:s&&d?i(!0):void 0,wakeMessageOnNotifyFailed:s&&d?i(!1):void 0})}dispose(){this.wakeDispatcher.dispose()}getDeliveryRef(e){return N(e)??T(e)??""}applyDeliveryState(e,n){!e||!n||this.applyPersistedPatch(e,{deliveryState:n})}applyNotifyDeliveryState(e,n,r){!e||!n||this.applyPersistedPatch(e,r?{deliveryState:n,...r}:{deliveryState:n})}applyPersistedPatchWithCompletionWake(e,n,r,o){!e||!n||this.applyPersistedPatch(e,r?{deliveryState:n,...r,...o}:{deliveryState:n})}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 n=[e.wakeMessage,e.wakeMessageOnNotifySuccess,e.wakeMessageOnNotifyFailed].map(r=>r?.trim()).filter(r=>!!r);return{required:!0,producer:"legacy",outcomeKey:e.completionWakeOutcomeKey,fallbackFingerprint:n.length>0?`${e.label}
|
|
222
|
+
${n.join(`
|
|
219
223
|
---completion-wake---
|
|
220
|
-
`)).
|
|
221
|
-
`);return new Promise((
|
|
222
|
-
`),wakeMessageOnNotifyFailed:
|
|
223
|
-
`);this.dispatchNotification(
|
|
224
|
-
`)}function
|
|
225
|
-
`)}import{existsSync as
|
|
226
|
-
`),notifyUser:"never"}),this.deps.clearRetryTimersForSession(e.id);return}if(
|
|
227
|
-
`)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",userMessage:[
|
|
228
|
-
`),notifyUser:"always",buttons:u==="ask"&&!d?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:p}):void 0}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.dispatchSessionNotification(e,{label:"suspended",userMessage:`\u{1F4A4} [${e.name}] Suspended after idle timeout | ${i} | ${Ft(a)}`,notifyUser:"always",buttons:this.deps.getResumeButtons(e.id,e)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.notifySession(e,`\u26D4 [${e.name}] ${Yo(e.killReason)} | ${i} | ${Ft(a)}`),this.deps.clearRetryTimersForSession(e.id)}emitWaitingForInput(e){if(!this.deps.debounceWaitingEvent(e.id))return;let r=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0,n=e.actionablePlanDecisionVersion??e.planDecisionVersion,o=e.pendingPlanApproval&&r==="ask"&&ti(e,n),i=e.pendingPlanApproval?void 0:this.deps.getOutputPreview(e),a=!e.pendingPlanApproval&&e.pendingInputState?.promptText?e.pendingInputState.promptText:!e.pendingPlanApproval&&i!==void 0?i:this.deps.getOutputPreview(e,e.pendingPlanApproval&&r!=="delegate"?Number.POSITIVE_INFINITY:void 0),u=e.pendingPlanApproval&&r==="ask"&&!o?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:n}):!e.pendingPlanApproval&&e.pendingInputState?.options.length?this.deps.getQuestionButtons(e.id,e.pendingInputState.options.map(m=>({label:m}))):void 0,p=UR(e,n),d=Xp({session:e,preview:a,questionText:e.pendingPlanApproval?void 0:e.pendingInputState?.promptText,questionContextPreview:i,planArtifact:p,originThreadLine:this.deps.originThreadLine(e),planApprovalMode:r,planApprovalButtons:u,questionButtons:e.pendingPlanApproval?void 0:u}),l=d.planReviewSummary??a;if(d.label==="plan-approval"&&r==="ask"&&o){this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,userMessages:d.userMessages,notifyUser:"never",buttons:d.buttons,wakeMessage:d.wakeMessage});return}if(d.label==="plan-approval"&&r==="ask"){this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,userMessages:d.userMessages,notifyUser:"always",buttons:d.buttons,hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{canonicalPlanPromptVersion:n,approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},shouldDispatch:()=>ri(e,n),onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,n,l),wakeMessageOnNotifySuccess:Zn(e,n)});return}if(d.label==="plan-approval"){this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,wakeMessage:d.wakeMessage,notifyUser:"never",buttons:d.buttons});return}this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,notifyUser:"always",buttons:d.buttons,wakeMessageOnNotifyFailed:d.wakeMessage})}emitTurnComplete(e){console.info(`[SessionManager] turn-complete wake dispatching for session ${e.id} (turns=${e.result?.num_turns??0}, strategy=${e.worktreeStrategy??"none"})`);let r=Gp({session:e,originThreadLine:this.deps.originThreadLine(e),preview:this.deps.getOutputPreview(e)});this.deps.dispatchSessionNotification(e,{label:"turn-complete",userMessage:r.userMessage,wakeMessage:r.wakeMessage,notifyUser:"always",onUserNotifyFailed:()=>{console.warn(`[SessionManager] turn-complete delivery failed for session ${e.id} \u2014 firing terminal notification as fallback`),this.deps.shouldEmitTerminalWake(e)&&this.emitCompleted(e)}})}emitCompleted(e){let r=this.deps.getOutputPreview(e),n=this.shouldRequestCompletionFollowup(e),o=Up({session:e,originThreadLine:this.deps.originThreadLine(e),preview:r}),i;this.deps.dispatchSessionNotification(e,{label:"completed",userMessage:o.userMessage,notifyUser:"always",completionWakeSummaryRequired:n,completionWakeOutcomeKey:`terminal:${e.id}`,requireDirectUserNotification:!0,wakeMessageOnNotifySuccess:n?o.wakeMessageOnNotifySuccess:void 0,wakeMessageOnNotifyFailed:n?o.wakeMessageOnNotifyFailed:void 0,hooks:{onNotifySucceeded:()=>{i=!0,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_succeeded",canonicalStatusDelivered:i,followupSummaryRequired:n})},onNotifyFailed:()=>{i=!1,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_failed",canonicalStatusDelivered:i,followupSummaryRequired:n})},onWakeSucceeded:()=>{this.logCompletionWakeDiagnostic({session:e,event:"completion_wake_succeeded",canonicalStatusDelivered:i,followupSummaryRequired:n})}}})}emitFailed(e,r,n){let o=jp({session:e,originThreadLine:this.deps.originThreadLine(e),errorSummary:r,preview:this.deps.getOutputPreview(e),worktreeAutoCleaned:n,failedButtons:this.deps.getResumeButtons(e.id,e)});this.deps.dispatchSessionNotification(e,{label:"failed",userMessage:o.userMessage,wakeMessage:o.wakeMessage,notifyUser:"always",buttons:o.buttons})}};Ee();Pt();import{existsSync as KR}from"fs";var va=class{constructor(e){this.deps=e}deps;async dismissWorktree(e){let r=this.deps.getPersistedSession(e),n=this.deps.resolveActiveSession(e),o=n??r;if(!o)return`Error: Session "${e}" not found.`;let i=n?.worktreePath??r?.worktreePath,a=this.deps.resolveWorktreeRepoDir(n?.originalWorkdir??r?.workdir,i),u=n?.worktreeBranch??r?.worktreeBranch,p=n?.name??r?.name??e;if(!a)return`Error: No workdir found for session "${e}".`;let d=mt(o);!d&&i&&KR(i)&&xt(a,i,{destructive:!0}),u&&Jt(a,u);for(let m of lt(n??r))this.deps.updatePersistedSession(m,{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:r?.worktreeLifecycle?.baseBranch,targetRepo:r?.worktreePrTargetRepo,pushRemote:r?.worktreePushRemote}});let l=d?`\u{1F5D1}\uFE0F [${p}] Branch \`${u??"unknown"}\` dismissed. Native backend worktree released for backend cleanup.`:`\u{1F5D1}\uFE0F [${p}] Branch \`${u??"unknown"}\` dismissed and permanently deleted.`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:ke(n??r??{id:e})??e,sessionId:r?.sessionId,harnessSessionId:n?.harnessSessionId??r?.harnessSessionId,backendRef:n?.backendRef??r?.backendRef,route:n?.route??r?.route}),{label:"worktree-dismissed",userMessage:l,notifyUser:"always"}),l}snoozeWorktreeDecision(e){let r=this.deps.getPersistedSession(e);if(!r)return`Error: Session "${e}" not found.`;let n=new Date(Date.now()+1440*60*1e3).toISOString();for(let a of lt(r))this.deps.updatePersistedSession(a,{worktreeDecisionSnoozedUntil:n,lastWorktreeReminderAt:new Date().toISOString()});let i=`\u23ED\uFE0F Reminder snoozed 24h for \`${r.worktreeBranch??"unknown"}\` (session: ${r.name})`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:ke(r)??q(r)??r.harnessSessionId,sessionId:r.sessionId,harnessSessionId:r.harnessSessionId,backendRef:r.backendRef,route:r.route}),{label:"worktree-snoozed",userMessage:i,notifyUser:"always"}),i}};var Ug=new Set(["starting","running"]),ba=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>Ug.has(e.status)).length}uniqueName(e){let r=new Set([...this.sessions.values()].filter(o=>Ug.has(o.status)).map(o=>o.name));if(!r.has(e))return e;let n=2;for(;r.has(`${e}-${n}`);)n+=1;return`${e}-${n}`}add(e){this.sessions.set(e.id,e)}remove(e){this.sessions.delete(e)}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()]}};var Aa=class{constructor(e){this.deps=e}deps;initializeSession(e,r,n,o={}){if(this.deps.hydrateSpawnedSession(e,r,n),n.taskLifecycle?.create(e),e.on("statusChange",(i,a)=>{a==="running"?(e.harnessSessionId&&this.deps.markRunning(e),n.taskLifecycle?.progress(e)):(a==="completed"||a==="failed"||a==="killed")&&(n.taskLifecycle?.finalize(e),this.deps.handleTerminal(e).catch(u=>{console.error(`[SessionRuntimeBootstrap] handleTerminal threw for session ${e.id}:`,u)}))}),e.on("lifecycleChange",(i,a)=>{n.taskLifecycle?.progress(e)}),e.on("turnEnd",(i,a)=>{this.deps.handleTurnEnd(e,a)}),e.start(),o.notifyLaunch!==!1){let i=this.deps.formatLaunchWorkdirLabel(e),a=`\u{1F680} [${e.name}] Launched | ${i} | ${e.model??"default"}`;this.deps.notifySession(e,a,"launch")}return e}};var Ta=class{buildNoChangeNotification(e){let{session:r,nativeBackendWorktree:n,cleanupSucceeded:o,worktreePath:i,preview:a,originThreadLine:u}=e,p=o?n?"native backend worktree released for backend cleanup":"worktree cleaned up":`cleanup failed; worktree still exists at ${i}`;return{label:o?"worktree-no-changes":"worktree-no-changes-cleanup-failed",userMessage:o?n?`\u2139\uFE0F [${r.name}] Session completed with no changes \u2014 native backend worktree released for backend cleanup`:`\u2139\uFE0F [${r.name}] Session completed with no changes \u2014 worktree cleaned up`:`\u26A0\uFE0F [${r.name}] Session completed with no changes, but worktree cleanup failed. Worktree still exists at ${i}`,wakeMessage:zp({sessionName:r.name,sessionId:r.id,cleanupSummary:p,preview:a,originThreadLine:u,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,approvalExecutionState:r.approvalExecutionState,approvalState:r.approvalState,planApproval:r.planApproval,approvalPromptStatus:r.approvalPromptStatus,approvalPromptMessageKind:r.approvalPromptMessageKind,approvalPromptDeliveredAt:r.approvalPromptDeliveredAt}),notifyUser:"always"}}buildAskNotification(e){let{session:r,branchName:n,baseBranch:o,diffSummary:i,buttons:a,summaryLines:u=[]}=e,p=i.commitMessages.slice(0,5).map(m=>`\u2022 ${m.hash} ${m.message} (${m.author})`),d=i.commits>5?`...and ${i.commits-5} more`:"",l=r.worktreePrTargetRepo?`Branch: \`${n}\` \u2192 \`${o}\` | PR target: ${r.worktreePrTargetRepo}`:`Branch: \`${n}\` \u2192 \`${o}\``;return{label:"worktree-merge-ask",userMessage:[`\u{1F500} Worktree decision required for session \`${r.name}\``,"",l,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`,"",...u.length>0?["Summary:",...u.map(m=>`- ${m}`),""]:[],"Recent commits:",...p,...d?[d]:[],"",`\u26A0\uFE0F Discard will permanently delete branch \`${n}\` and all local changes. This cannot be undone.`].join(`
|
|
229
|
-
`),notifyUser:"always",buttons:
|
|
230
|
-
`),wakeMessageOnNotifyFailed:[
|
|
231
|
-
`)}}buildDelegateNotification(e){let{session:
|
|
232
|
-
`):
|
|
233
|
-
`)
|
|
234
|
-
`)
|
|
235
|
-
`)?r:void 0}ir();Pt();Je();import{unlinkSync as VR}from"fs";var Ra=class t{timers=new Map;disposed=!1;static MAX_DELAY_MS=2147483647;schedule(e,r,n){if(this.disposed)return;this.cancel(e);let o=Math.max(0,r-Date.now()),i=setTimeout(()=>{if(this.timers.delete(e),!this.disposed){if(r-Date.now()>0){this.schedule(e,r,n);return}n()}},Math.min(o,t.MAX_DELAY_MS));i.unref?.(),this.timers.set(e,i)}cancel(e){let r=this.timers.get(e);r&&(clearTimeout(r),this.timers.delete(e))}cancelPrefix(e){for(let r of this.timers.keys())r.startsWith(e)&&this.cancel(r)}dispose(){this.disposed=!0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};Ee();Ko();Pt();var Gg=10080*60*1e3,HR=300*1e3,Vg="tmp-output:cleanup";function zR(t){return t instanceof Error?t.message:String(t)}var Ca=class{constructor(e){this.deps=e}deps;scheduler=new Ra;schedule(e,r,n){this.scheduler.schedule(e,r,n)}cancel(e){this.scheduler.cancel(e)}cancelPrefix(e){this.scheduler.cancelPrefix(e)}bootstrapMaintenanceSchedules(){let e=Date.now();this.deps.store.cleanupTmpOutputFiles(e);for(let r of this.deps.store.listPersistedSessions())this.syncPersistedSessionMaintenance(r);this.syncActionTokenExpiryDeadline(),this.deps.store.cleanupOrphanOutputFiles(),this.syncTmpOutputCleanupDeadline(e)}syncRuntimeGcDeadline(e){if(!e.completedAt)return;let r=this.runtimeGcKey(e.id);this.schedule(r,e.completedAt+this.runtimeGcMaxAgeMs(),()=>{let n=this.deps.sessions.get(e.id);if(!n||!n.completedAt)return;let o=this.runtimeGcMaxAgeMs();if(!this.deps.store.shouldGcActiveSession(n,Date.now(),o)){this.syncRuntimeGcDeadline(n);return}this.deps.removeRuntimeSession(e.id),this.deps.persistSession(n,{scheduleRuntimeGc:!1}),this.deps.clearRuntimeSessionState(e.id)})}cancelRuntimeGc(e){this.cancel(this.runtimeGcKey(e))}cancelPersistedMaintenance(e){let r=this.persistedMaintenanceRef(e);r&&this.cancelPrefix(`persisted:${r}:`)}syncPersistedSessionMaintenance(e){let r=this.persistedMaintenanceRef(e);if(!r)return;this.cancel(this.persistedMaintenanceKey(r,"worktree-reminder"));let n=this.deps.reminders.getNextReminderAt(e);n!=null?this.schedulePersistedWorktreeReminder(r,n):this.deps.reminders.clearResolvedReminderState(e),this.cancel(this.persistedMaintenanceKey(r,"worktree-retention"));let o=un(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),i=this.resolvedAtIso(e),a=this.isLegacyResolvedWorktree(e);if((o.cleanupSafe||a)&&typeof i=="string"){let u=new Date(i).getTime();Number.isFinite(u)&&this.schedule(this.persistedMaintenanceKey(r,"worktree-retention"),u+Gg,()=>{let p=this.deps.store.getPersistedSession(r);p&&this.reconcileResolvedWorktreeRetention(p,Date.now())})}}reconcileResolvedWorktreeRetention(e,r){let n=un(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),o=this.resolvedAtIso(e),i=o?new Date(o).getTime():0,a=this.isLegacyResolvedWorktree(e);if(!(!n.cleanupSafe&&!a||!i||r-i<Gg))try{if(!e.worktreePath&&!mt(e))return;let u=this.deps.resolveWorktreeRepoDir(e.workdir,e.worktreePath);if(!u)return;let p=mt(e)?!1:xt(u,e.worktreePath);if(!mt(e)&&!p)return;for(let d of lt(e))this.deps.updatePersistedSession(d,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",worktreeLifecycle:{...e.worktreeLifecycle??n.lifecycle,state:n.derivedState,updatedAt:new Date(r).toISOString(),resolvedAt:e.worktreeLifecycle?.resolvedAt??new Date(r).toISOString(),resolutionSource:e.worktreeLifecycle?.resolutionSource??"maintenance",notes:n.reasons}})}catch(u){console.warn(`[SessionManager] Failed maintenance cleanup for worktree ${e.worktreePath}: ${zR(u)}`)}}syncActionTokenExpiryDeadline(){let e="tokens:expiry";this.cancel(e);let r=this.deps.store.getNextActionTokenExpiry();r!=null&&this.schedule(e,r,()=>{this.deps.store.purgeExpiredActionTokens(Date.now())})}syncTmpOutputCleanupDeadline(e=Date.now()){this.cancel(Vg);let r=this.deps.store.getNextTmpOutputCleanupAt(e);r!=null&&this.schedule(Vg,r,()=>{let n=Date.now();this.deps.store.cleanupTmpOutputFiles(n),this.syncTmpOutputCleanupDeadline(n)})}enforcePersistedRetention(){let e=this.deps.store.evictOldestPersisted(this.deps.getMaxPersistedSessions());for(let r of e)this.cancelPersistedMaintenance(r),r.sessionId&&this.cancelRuntimeGc(r.sessionId),this.cleanupOutputPathIfUnreferenced(r.outputPath)}dispose(){this.scheduler.dispose()}persistedMaintenanceRef(e){return e.sessionId??q(e)??e.harnessSessionId}runtimeGcKey(e){return`runtime-gc:${e}`}persistedMaintenanceKey(e,r){return`persisted:${e}:${r}`}runtimeGcMaxAgeMs(){return(K.sessionGcAgeMinutes??1440)*6e4}schedulePersistedWorktreeReminder(e,r){let n=this.persistedMaintenanceKey(e,"worktree-reminder");this.schedule(n,r,()=>{let o=this.deps.store.getPersistedSession(e);if(!o||this.deps.reminders.sendReminderIfDue(o,Date.now()))return;let a=this.deps.reminders.getNextReminderAt(o);a!=null&&this.schedulePersistedWorktreeReminder(e,Math.max(a,Date.now()+HR))})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.deps.store.hasOutputPathReference(e)))try{VR(e)}catch{}}resolvedAtIso(e){return e.worktreeLifecycle?.resolvedAt??e.worktreeMergedAt??e.worktreeDismissedAt??(e.completedAt?new Date(e.completedAt).toISOString():void 0)}isLegacyResolvedWorktree(e){return e.worktreeMerged===!0||e.worktreeDisposition==="dismissed"||e.worktreeDisposition==="no-change-cleaned"||e.worktreeState==="merged"||e.worktreeState==="dismissed"}};qs();var Hg=new Set(["completed","failed","killed"]),JR=new Set(["starting","running"]),QR=5e3,Ea=class{registry;sessions;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueue=new Yn;pendingAskUserQuestions=new Map;store;metrics;wakeDispatcher;interactions;notifications;worktrees;questions;reminders;lifecycle;restore;stateSync;references;worktreeStrategy;worktreeDecisions;runtimeBootstrap;worktreeMessages;maintenance;constructor(e=20,r=50,n={}){this.maxSessions=e,this.maxPersistedSessions=r,this.registry=new ba,this.sessions=this.registry.sessions,this.store=new pa(n.store),this.metrics=new da,this.wakeDispatcher=new ha,this.interactions=new ya(this.store.actionTokenStore,Pr),this.references=new Xs(this.sessions,this.store),this.stateSync=new Zs({store:this.store,sessions:this.sessions,resolveSession:o=>this.references.resolveActive(o)}),this.notifications=new ka(this.wakeDispatcher,(o,i)=>this.stateSync.applySessionPatch(o,i)),this.worktrees=new Sa,this.restore=new Ys(o=>this.store.getPersistedSession(o)),this.worktreeMessages=new Ta,this.worktreeStrategy=new ra({shouldRunWorktreeStrategy:o=>this.shouldRunWorktreeStrategy(o),isAlreadyMerged:o=>this.isAlreadyMerged(o),resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),getWorktreeCompletionState:(o,i,a,u)=>this.getWorktreeCompletionState(o,i,a,u),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),dispatchSessionNotification:(o,i)=>this.dispatchSessionNotification(o,i),getOutputPreview:(o,i)=>this.getOutputPreview(o,i),originThreadLine:o=>this.originThreadLine(o),getWorktreeDecisionButtons:o=>this.getWorktreeDecisionButtons(o),makeOpenPrButton:o=>this.makeActionButton(o,"worktree-create-pr","Open PR"),worktreeSummaryProvider:n.worktreeSummaryProvider,worktreeMessages:this.worktreeMessages,enqueueMerge:(o,i,a)=>this.enqueueMerge(o,i,a),mergeBranch:Ss,spawnConflictResolver:async({session:o,worktreePath:i,prompt:a})=>this.spawn({prompt:a,workdir:i,name:`${o.name}-conflict-resolver`,harness:o.harnessName||dt(),model:o.model,reasoningEffort:o.reasoningEffort,fastMode:o.fastMode,permissionMode:"bypassPermissions",multiTurn:!0,worktreeStrategy:"off",autoMergeParentSessionId:o.id,route:o.route,originChannel:o.originChannel,originThreadId:o.originThreadId,originAgentId:o.originAgentId,originSessionKey:o.originSessionKey},{notifyLaunch:!1}),runAutoPr:async(o,i)=>{let{makeAgentPrTool:a}=await Promise.resolve().then(()=>(Ws(),gf));return{success:(await a().execute("auto-pr",{session:o.id,base_branch:i}))?.meta?.success===!0}}}),this.questions=new Ia(this.pendingAskUserQuestions,(o,i)=>this.dispatchSessionNotification(o,i),o=>{this.lastWaitingEventTimestamps.delete(o)},(o,i)=>this.interactions.getQuestionButtons(o,i)),this.reminders=new xa(o=>this.buildRoutingProxy(o),(o,i)=>this.notifications.dispatch(o,i),(o,i)=>this.updatePersistedSession(o,i),o=>this.getWorktreeDecisionButtons(o)),this.maintenance=new Ca({store:this.store,sessions:this.sessions,reminders:this.reminders,removeRuntimeSession:o=>this.registry.remove(o),persistSession:(o,i)=>this.persistSession(o,i),clearRuntimeSessionState:o=>{this.lastWaitingEventTimestamps.delete(o),this.lastTurnCompleteMarkers.delete(o),this.lastTerminalWakeMarkers.delete(o)},resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),getMaxPersistedSessions:()=>this.maxPersistedSessions}),this.store.onActionTokensChanged(()=>this.syncActionTokenExpiryDeadline()),this.lifecycle=new wa({persistSession:o=>this.persistSession(o),clearWaitingTimestamp:o=>{this.lastWaitingEventTimestamps.delete(o)},handleWorktreeStrategy:o=>this.handleWorktreeStrategy(o),resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),dispatchSessionNotification:(o,i)=>this.dispatchSessionNotification(o,i),notifySession:(o,i,a)=>this.notifySession(o,i,a),clearRetryTimersForSession:o=>this.wakeDispatcher.clearRetryTimersForSession(o),hasTurnCompleteWakeMarker:o=>this.lastTurnCompleteMarkers.has(o),shouldEmitTurnCompleteWake:o=>this.shouldEmitTurnCompleteWake(o),shouldEmitTerminalWake:o=>this.shouldEmitTerminalWake(o),resolvePlanApprovalMode:o=>this.resolvePlanApprovalMode(o),getPlanApprovalButtons:(o,i)=>this.interactions.getPlanApprovalButtons(o,i),getResumeButtons:(o,i)=>this.interactions.getResumeButtons(o,i),getQuestionButtons:(o,i)=>this.interactions.getQuestionButtons(o,i),extractLastOutputLine:o=>this.extractLastOutputLine(o),getOutputPreview:(o,i)=>this.getOutputPreview(o,i),originThreadLine:o=>this.originThreadLine(o),debounceWaitingEvent:o=>this.debounceWaitingEvent(o),isAlreadyMerged:o=>this.isAlreadyMerged(o)}),this.worktreeDecisions=new va({getPersistedSession:o=>this.store.getPersistedSession(o),resolveActiveSession:o=>this.references.resolveActive(o),resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),dispatchNotification:(o,i)=>this.notifications.dispatch(o,i),buildRoutingProxy:o=>this.buildRoutingProxy(o)}),this.runtimeBootstrap=new Aa({hydrateSpawnedSession:(o,i,a)=>{this.restore.hydrateSpawnedSession(o,i,a)},markRunning:o=>{this.store.markRunning(o),this.onPersistedSessionChanged(this.store.getPersistedSession(o.id))},handleTerminal:async o=>this.onSessionTerminal(o),handleTurnEnd:(o,i)=>this.onTurnEnd(o,i),formatLaunchWorkdirLabel:o=>this.formatLaunchWorkdirLabel(o),notifySession:(o,i,a)=>this.notifySession(o,i,a)})}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)}cancelPersistedMaintenance(e){this.maintenance.cancelPersistedMaintenance(e)}onPersistedSessionChanged(e){e&&(this.syncPersistedSessionMaintenance(e),this.enforcePersistedRetention())}syncPersistedSessionMaintenance(e){this.maintenance.syncPersistedSessionMaintenance(e)}reconcileResolvedWorktreeRetention(e,r){this.maintenance.reconcileResolvedWorktreeRetention(e,r)}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,r={}){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.`);if(e.sessionIdOverride){let c=this.registry.get(e.sessionIdOverride);if(c?.status==="starting"||c?.status==="running")throw new Error(`Cannot reuse session ID ${e.sessionIdOverride}: that session is still ${c.status}.`);c&&this.registry.remove(c.id),this.lastWaitingEventTimestamps.delete(e.sessionIdOverride),this.lastTurnCompleteMarkers.delete(e.sessionIdOverride),this.lastTerminalWakeMarkers.delete(e.sessionIdOverride),this.maintenance.cancelRuntimeGc(e.sessionIdOverride)}let o=e.name||lc(e.prompt),i=this.uniqueName(o);if(i!==o&&console.warn(`[SessionManager] Name conflict: "${o}" \u2192 "${i}" (active session with same name exists)`),!e.route?.provider||!e.route.target)throw new Error(`Cannot launch session "${i}": missing explicit route metadata.`);let a=this.restore.prepareSpawn(e,i),u=e.harness??"claude-code",p=this,d,l=u==="claude-code"&&!e.canUseTool?async(c,h)=>{if(!d)throw new Error("canUseTool called before session ID was set");return p.handleAskUserQuestion(d,h)}:e.canUseTool,m=new Ps({...e,workdir:a.actualWorkdir,systemPrompt:a.effectiveSystemPrompt,canUseTool:l},i);return d=m.id,this.registry.add(m),this.metrics.incrementLaunched(),this.runtimeBootstrap.initializeSession(m,a,e,r)}async spawnAndAwaitRunning(e,r={}){let n=this.spawn(e,r);return await this.waitForRunningSession(n),n}async waitForRunningSession(e){if(e.status==="running")return;if(Hg.has(e.status))throw new Error(this.describeLaunchFailure(e));let r=e.on?.bind(e),n=e.off?.bind(e)??e.removeListener?.bind(e);if(!r||!n)throw new Error(`Session ${e.name} [${e.id}] did not expose lifecycle events during startup.`);await new Promise((o,i)=>{let a=(p,d)=>{if(d==="running"){u(),o();return}Hg.has(d)&&(u(),i(new Error(this.describeLaunchFailure(e))))},u=()=>{n("statusChange",a)};r("statusChange",a)})}describeLaunchFailure(e){let r=e.killReason?` (reason: ${e.killReason})`:"",n=e.error||e.result?.result||`status=${e.status}${r}`;return`Session ${e.name} [${e.id}] failed to start: ${n}`}formatLaunchResult(e,r){return Di({prompt:e.prompt,workdir:e.workdir,harness:e.harness,permissionMode:e.permissionMode??K.permissionMode,planApproval:e.planApproval,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,forceNewSession:e.forceNewSession,clearedPersistedCodexResume:e.clearedPersistedCodexResume},r)}shouldRunWorktreeStrategy(e){let r=e.lifecycle;return!(r==="starting"||r==="awaiting_plan_decision"||r==="awaiting_user_input"||e.pendingPlanApproval)}makeActionButton(e,r,n,o={}){return this.interactions.makeActionButton(e,r,n,o)}consumeActionToken(e){return this.interactions.consumeActionToken(e)}getActionToken(e){return this.interactions.getActionToken(e)}clearPlanDecisionTokens(e,r){this.interactions.clearPlanDecisionTokens(e,r)}isCurrentPendingPlanDecision(e,r){let n=this.resolve(e)??this.getPersistedSession(e);return ri(n,r)}dispatchPlanApprovalFallback(e,r,n){let o=new Date().toISOString();this.notifications.dispatch(e,{label:"plan-approval-fallback",userMessage:Zo({session:e,summary:n}),notifyUser:"always",shouldDispatch:()=>this.isCurrentPendingPlanDecision(e.id,r),hooks:{onNotifyStarted:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,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:r,approvalPromptVersion:r,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:Zn(e,r,!0),wakeMessageOnNotifyFailed:Pa({session:e,planDecisionVersion:r})})}getWorktreeDecisionButtons(e){let r=this.resolve(e)??this.getPersistedSession(e);if(!(!r||r.worktreeStrategy==="delegate"))return this.interactions.getWorktreeDecisionButtons(e,r)}getWorktreeCompletionState(e,r,n,o){return this.worktrees.getCompletionState(e,r,n,o)}notifyWorktreeOutcome(e,r,n){this.notifications.notifyWorktreeOutcome(e,r,n)}requestPlanApprovalFromUser(e,r){let n=r.trim();if(!n)return"Error: summary must not be empty.";let o=Yp(n),i=this.resolve(e),a=i?void 0:this.getPersistedSession(e),u=i??a;if(!u)return`Error: Session "${e}" not found.`;if(!u.pendingPlanApproval)return`Error: Session "${e}" is not awaiting plan approval.`;let p=ke(i??a??{id:e})??e;if(this.resolvePlanApprovalMode(u)!=="delegate")return`Error: Session "${e}" already uses direct user plan approval. Do not send a duplicate approval prompt.`;let d=u.actionablePlanDecisionVersion??u.planDecisionVersion;if(ti(u,d))return[`An actionable plan review prompt already exists for session ${u.name} [${p}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ");if(u.deliveryState==="notifying")return[`A plan approval prompt is already being delivered for session ${u.name} [${p}].`,"Wait for delivery to finish before retrying."].join(" ");let l=this.interactions.getPlanApprovalButtons(p,{...u,planDecisionVersion:d}),m=[`\u{1F4CB} [${u.name}] Plan v${d??"?"} needs your decision:`,"","Why this was escalated:","",o,"","Choose Approve, Revise, or Reject below."].join(`
|
|
236
|
-
`);return this.notifications.dispatch(this.buildRoutingProxy({id:p,name:u.name,sessionId:a?.sessionId,harnessSessionId:i?.harnessSessionId??a?.harnessSessionId,backendRef:i?.backendRef??a?.backendRef,route:i?.route??a?.route}),{label:"plan-approval",userMessage:m,notifyUser:"always",buttons:l,hooks:{onNotifyStarted:()=>{this.updatePersistedSession(p,{approvalPromptRequiredVersion:d,approvalPromptStatus:"sending",approvalPromptVersion:d,approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.updatePersistedSession(p,{canonicalPlanPromptVersion:d,approvalPromptRequiredVersion:d,approvalPromptVersion:d,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.updatePersistedSession(p,{approvalPromptRequiredVersion:d,approvalPromptVersion:d,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},shouldDispatch:()=>this.isCurrentPendingPlanDecision(p,d),onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(this.buildRoutingProxy({id:p,name:u.name,sessionId:a?.sessionId,harnessSessionId:i?.harnessSessionId??a?.harnessSessionId,backendRef:i?.backendRef??a?.backendRef,route:i?.route??a?.route}),d,o),wakeMessageOnNotifySuccess:Zn({id:p,name:u.name},d)}),[`Canonical plan approval prompt sent for session ${u.name} [${p}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ")}buildRoutingProxy(e){return{id:ke(e)??q(e)??e.harnessSessionId??"unknown-session",name:e.name,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef?{...e.backendRef}:void 0,route:e.route}}resolveWorktreeRepoDir(e,r){return e&&(!r||!Qs(e,r))||!r?e:gs(r)??e}formatLaunchWorkdirLabel(e){if(!e.worktreePath)return e.workdir;let r=this.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath);return!r||r===e.worktreePath?e.worktreePath:`${e.worktreePath} (worktree of ${r})`}async dismissWorktree(e){return this.worktreeDecisions.dismissWorktree(e)}snoozeWorktreeDecision(e){return this.worktreeDecisions.snoozeWorktreeDecision(e)}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.lastWaitingEventTimestamps.delete(e.id),this.wakeDispatcher.clearRetryTimersForSession(e.id);let r=e.autoMergeParentSessionId;if(!r)return;let n=this.resolve(r),o=this.getPersistedSession(r),i=n??(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){console.warn(`[SessionManager] Auto-merge resolver ${e.id} completed, but original session ${r} could not be found.`);return}if(e.status==="completed"&&n){this.updatePersistedSession(r,{autoMergeResolverSessionId:void 0}),await this.handleWorktreeStrategy(n);return}let a=n?.worktreeBranch??o?.worktreeBranch??"unknown",u=n?.worktreePath??o?.worktreePath??"(unknown worktree)",p=n?.worktreeBaseBranch??o?.worktreeBaseBranch,d=n?.worktreePrTargetRepo??o?.worktreePrTargetRepo,l=n?.worktreePushRemote??o?.worktreePushRemote;this.updatePersistedSession(r,Fs({worktreeBaseBranch:p,worktreePrTargetRepo:d,worktreePushRemote:l},{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",userMessage:[`\u26A0\uFE0F [${i.name}] Auto-merge conflict resolution did not complete successfully.`,`Branch \`${a}\` was preserved for manual follow-up in ${u}.`,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(`
|
|
237
|
-
`),buttons:[[this.makeActionButton(r,"worktree-create-pr","Open PR")]]})}getStoppedStatusLabel(e){return Yo(e)}persistSession(e,r={}){let n=r.scheduleRuntimeGc??!0;this.store.hasRecordedSession(e.id)||this.metrics.recordSession(e),this.store.persistTerminal(e),n&&this.syncRuntimeGcDeadline(e),this.onPersistedSessionChanged(this.store.getPersistedSession(e.id)),this.syncTmpOutputCleanupDeadline()}getMetrics(){return this.metrics.getMetrics()}recordSessionMetrics(e){this.metrics.recordSession(e)}notifySession(e,r,n="notification"){this.dispatchSessionNotification(e,{label:n,userMessage:r,notifyUser:"always"})}sendPlanOffer(e){let r=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",userMessage:e.text,notifyUser:"always",buttons:r})}emitGoalTaskUpdate(e,r,n="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 a=n==="goal-task-succeeded",u=p=>Kp({sessionId:o,sessionName:e.sessionName,taskName:e.name,summary:r,originThreadLine:Ao(i),canonicalStatusDelivered:p});this.dispatchSessionNotification(i,{label:n,userMessage:r,notifyUser:"always",completionWakeSummaryRequired:a,completionWakeOutcomeKey:a?`goal:${e.id}`:void 0,requireDirectUserNotification:a,wakeMessageOnNotifySuccess:a?u(!0):void 0,wakeMessageOnNotifyFailed:a?u(!1):void 0})}launchPlanOffer(e){let r=e.route??{provider:"system",target:"system"};return this.spawn({prompt:e.prompt,workdir:e.workdir,name:e.name,harness:dt(),permissionMode:"plan",planApproval:"ask",worktreeStrategy:e.worktreeStrategy??"off",multiTurn:!0,route:r,originChannel:this.originChannelFromRoute(r),originThreadId:r.threadId,originSessionKey:r.sessionKey})}dispatchSessionNotification(e,r){this.notifications.dispatch(e,r)}originChannelFromRoute(e){return e.accountId?`${e.provider}|${e.accountId}|${e.target}`:`${e.provider}|${e.target}`}debounceWaitingEvent(e){let r=Date.now(),n=this.lastWaitingEventTimestamps.get(e);return n&&r-n<QR?!1:(this.lastWaitingEventTimestamps.set(e,r),!0)}originThreadLine(e){return Ao(e)}extractLastOutputLine(e){return e.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(e,r=1e3){return Kg(e,r)}triggerAgentEvent(e){this.lifecycle.emitCompleted(e)}triggerFailedEvent(e,r,n=!1){this.lifecycle.emitFailed(e,r,n)}triggerWaitingForInputEvent(e){this.lifecycle.emitWaitingForInput(e)}resolvePlanApprovalMode(e){return e.planApproval??K.planApproval??"delegate"}onTurnEnd(e,r){this.lifecycle.handleTurnEnd(e,r)}shouldEmitTurnCompleteWake(e){let r=`${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(e.id)===r?(console.info(`[SessionManager] shouldEmitTurnCompleteWake: debounced for session ${e.id} (marker unchanged: ${r})`),!1):(this.lastTurnCompleteMarkers.set(e.id,r),!0)}shouldEmitTerminalWake(e){let r=`${e.status}|${e.completedAt??0}|${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.killReason}`;return this.lastTerminalWakeMarkers.get(e.id)===r?!1:(this.lastTerminalWakeMarkers.set(e.id,r),!0)}triggerTurnCompleteEventWithSignal(e){this.lifecycle.emitTurnComplete(e)}resolve(e){return this.references.resolveActive(e)}get(e){return this.registry.get(e)}list(e){let r=this.registry.list();return e&&e!=="all"&&(r=r.filter(n=>n.status===e)),r.sort((n,o)=>o.startedAt-n.startedAt)}kill(e,r){let n=this.registry.get(e);if(!n)return!1;if(n.pendingPlanApproval){this.clearPlanDecisionTokens(n.id);let o={lifecycle:"terminal",runtimeState:"stopped",pendingPlanApproval:!1,planApprovalContext:void 0,approvalState:n.approvalState==="pending"?"rejected":n.approvalState,planDecisionVersion:(n.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};n.applyControlPatch(o),Object.assign(n,o),this.updatePersistedSession(n.id,o)}return n.kill(r??"user"),!0}killAll(e="user"){for(let r of this.sessions.values())JR.has(r.status)&&this.kill(r.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 r=this.store.getPersistedSession(e);return r?.worktreeMerged===!0||r?.worktreeLifecycle?.state==="merged"||r?.worktreeLifecycle?.state==="released"}async enqueueMerge(e,r,n){return this.mergeQueue.enqueue(e,r,n)}updatePersistedSession(e,r){let n=this.stateSync.applySessionPatch(e,r);return n&&this.onPersistedSessionChanged(this.store.getPersistedSession(e)),n}listPersistedSessions(){return this.store.listPersistedSessions()}async handleAskUserQuestion(e,r){let n=this.sessions.get(e);if(!n)throw new Error(`Session "${e}" not found for AskUserQuestion intercept`);return this.questions.handleAskUserQuestion(n,r)}resolveAskUserQuestion(e,r){this.questions.resolveAskUserQuestion(e,r)}async resolvePendingInputOption(e,r){let n=this.sessions.get(e);return n&&await n.submitPendingInputOption(r)?(this.lastWaitingEventTimestamps.delete(e),!0):(this.questions.resolveAskUserQuestion(e,r),!0)}dispose(){this.disposeMaintenance(),this.questions.dispose(),this.notifications.dispose()}};pe();Je();var Jg=class{#t;#r;#e=new Map;constructor(t){this.#t=zg(t,1),this.#r=this.#t}get maxEntries(){return this.#r}get size(){return this.#e.size}setMaxEntriesForTest(t){this.#r=typeof t=="number"?zg(t,this.#t):this.#t,this.#n()}clear(){this.#e.clear()}get(t){let e=this.getResult(t);return e.hit?e.value:void 0}getResult(t){if(!this.#e.has(t))return{hit:!1};let e=this.#e.get(t);return this.#e.delete(t),this.#e.set(t,e),{hit:!0,value:e}}set(t,e){this.#e.has(t)&&this.#e.delete(t),this.#e.set(t,e),this.#n()}#n(){for(;this.#e.size>this.#r;){let t=this.#e.keys().next();if(t.done)break;this.#e.delete(t.value)}}};function zg(t,e){return!Number.isFinite(t)||t<=0?e:Math.max(1,Math.floor(t))}var YR="\\x1b\\[[\\x20-\\x3f]*[\\x40-\\x7e]",ZR="\\x1b\\][^\\x07\\x1b]*(?:\\x1b\\\\|\\x07)",GU=new RegExp(YR,"g"),VU=new RegExp(ZR,"g"),HU=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;var ee={};Ct(ee,{Match:()=>XR});function XR(t,e){return e[t.length]?.(...t)??(()=>{throw Error("Invalid Arguments")})()}var s={};Ct(s,{Entries:()=>PC,EntriesRegExp:()=>xC,Every:()=>kC,EveryAll:()=>SC,GraphemeCount:()=>gC,HasPropertyKey:()=>IC,IsArray:()=>oi,IsAsyncIterator:()=>iC,IsBigInt:()=>ni,IsBoolean:()=>rh,IsClassInstance:()=>cC,IsConstructor:()=>sC,IsDeepEqual:()=>cd,IsEqual:()=>J,IsFunction:()=>nh,IsGreaterEqualThan:()=>ih,IsGreaterThan:()=>dC,IsInteger:()=>ld,IsIterator:()=>aC,IsLessEqualThan:()=>oh,IsLessThan:()=>lC,IsMaxLength:()=>hC,IsMinLength:()=>yC,IsMultipleOf:()=>mC,IsNull:()=>Oa,IsNumber:()=>_a,IsObject:()=>mn,IsObjectNotArray:()=>uC,IsString:()=>Da,IsSymbol:()=>pC,IsUndefined:()=>md,IsUnsafePropertyKey:()=>sh,IsValueLike:()=>fC,Keys:()=>Ma,Symbols:()=>wC,TakeLeft:()=>La,Values:()=>vC});function Cr(t,e,r){return t>=e&&t<=r}function Qg(t){return Cr(t,127462,127487)}function eC(t){return Cr(t,65024,65039)}function tC(t){return Cr(t,768,879)||Cr(t,6832,6911)||Cr(t,7616,7679)||Cr(t,65056,65071)}function $a(t){return t>65535?2:1}function Yg(t,e){for(;e<t.length;){let r=t.codePointAt(e);if(tC(r)||eC(r))e+=$a(r);else break}return e}function dd(t,e){let r=t.codePointAt(e),n=e+$a(r);for(n=Yg(t,n);n<t.length-1&&t[n]==="\u200D";){let o=t.codePointAt(n+1);n+=1+$a(o),n=Yg(t,n)}return Qg(r)&&n<t.length&&Qg(t.codePointAt(n))&&(n+=$a(t.codePointAt(n))),n}function Zg(t){return Cr(t,55296,56319)||Cr(t,768,879)||t===8205}function Xg(t){let e=0,r=0;for(;r<t.length;)r=dd(t,r),e++;return e}function rC(t,e){if(e===0)return!0;let r=0,n=0;for(;n<t.length;)if(n=dd(t,n),r++,r>=e)return!0;return!1}function nC(t,e){let r=0,n=0;for(;n<t.length;)if(n=dd(t,n),r++,r>e)return!1;return!0}function eh(t,e){if(e===0)return!0;let r=0;for(;r<t.length;){if(Zg(t.charCodeAt(r)))return rC(t,e);if(r++,r>=e)return!0}return!1}function th(t,e){let r=0;for(;r<t.length;){if(Zg(t.charCodeAt(r)))return nC(t,e);if(r++,r>e)return!1}return!0}function oi(t){return Array.isArray(t)}function iC(t){return mn(t)&&Symbol.asyncIterator in t}function ni(t){return J(typeof t,"bigint")}function rh(t){return J(typeof t,"boolean")}function sC(t){if(md(t)||!nh(t))return!1;let e=Function.prototype.toString.call(t);return!!(/^class\s/.test(e)||/\[native code\]/.test(e))}function nh(t){return J(typeof t,"function")}function ld(t){return Number.isInteger(t)}function aC(t){return mn(t)&&Symbol.iterator in t}function Oa(t){return J(t,null)}function _a(t){return Number.isFinite(t)}function uC(t){return mn(t)&&!oi(t)}function mn(t){return J(typeof t,"object")&&!Oa(t)}function Da(t){return J(typeof t,"string")}function pC(t){return J(typeof t,"symbol")}function md(t){return J(t,void 0)}function J(t,e){return t===e}function dC(t,e){return t>e}function lC(t,e){return t<e}function oh(t,e){return t<=e}function ih(t,e){return t>=e}function mC(t,e){if(ni(t)||ni(e))return BigInt(t)%BigInt(e)===0n;let r=1e-10;if(!_a(t)||ld(t)&&1/e%1===0)return!0;let n=t%e;return Math.min(Math.abs(n),Math.abs(n-e))<r}function cC(t){if(!mn(t))return!1;let e=globalThis.Object.getPrototypeOf(t);return Oa(e)?!1:J(typeof e.constructor,"function")&&!(J(e.constructor,globalThis.Object)||J(e.constructor.name,"Object"))}function fC(t){return ni(t)||rh(t)||Oa(t)||_a(t)||Da(t)||md(t)}function gC(t){return Xg(t)}function hC(t,e){return th(t,e)}function yC(t,e){return eh(t,e)}function kC(t,e,r){for(let n=e;n<t.length;n++)if(!r(t[n],n))return!1;return!0}function SC(t,e,r){let n=!0;for(let o=e;o<t.length;o++)r(t[o],o)||(n=!1);return n}function La(t,e,r){return J(t.length,0)?r():e(t[0],t.slice(1))}function sh(t){return J(t,"__proto__")||J(t,"constructor")||J(t,"prototype")}function IC(t,e){return sh(e)?Object.prototype.hasOwnProperty.call(t,e):e in t}function xC(t){return Ma(t).map(e=>[new RegExp(`^${e}$`),t[e]])}function PC(t){return Object.entries(t)}function Ma(t){return Object.getOwnPropertyNames(t)}function wC(t){return Object.getOwnPropertySymbols(t)}function vC(t){return Object.values(t)}function bC(t,e){if(!mn(e))return!1;let r=Ma(t);return J(r.length,Ma(e).length)&&r.every(n=>cd(t[n],e[n]))}function AC(t,e){return oi(e)&&J(t.length,e.length)&&t.every((r,n)=>cd(t[n],e[n]))}function cd(t,e){return oi(t)?AC(t,e):mn(t)?bC(t,e):J(t,e)}var nt={};Ct(nt,{IsBigInt64Array:()=>BC,IsBigUint64Array:()=>WC,IsBoolean:()=>TC,IsDate:()=>KC,IsFloat32Array:()=>NC,IsFloat64Array:()=>qC,IsInt16Array:()=>_C,IsInt32Array:()=>LC,IsInt8Array:()=>$C,IsMap:()=>GC,IsNumber:()=>RC,IsRegExp:()=>UC,IsSet:()=>jC,IsString:()=>CC,IsTypeArray:()=>EC,IsUint16Array:()=>DC,IsUint32Array:()=>FC,IsUint8Array:()=>MC,IsUint8ClampedArray:()=>OC});function TC(t){return t instanceof Boolean}function RC(t){return t instanceof Number}function CC(t){return t instanceof String}function EC(t){return globalThis.ArrayBuffer.isView(t)}function $C(t){return t instanceof globalThis.Int8Array}function MC(t){return t instanceof globalThis.Uint8Array}function OC(t){return t instanceof globalThis.Uint8ClampedArray}function _C(t){return t instanceof globalThis.Int16Array}function DC(t){return t instanceof globalThis.Uint16Array}function LC(t){return t instanceof globalThis.Int32Array}function FC(t){return t instanceof globalThis.Uint32Array}function NC(t){return t instanceof globalThis.Float32Array}function qC(t){return t instanceof globalThis.Float64Array}function BC(t){return t instanceof globalThis.BigInt64Array}function WC(t){return t instanceof globalThis.BigUint64Array}function UC(t){return t instanceof globalThis.RegExp}function KC(t){return t instanceof globalThis.Date}function jC(t){return t instanceof globalThis.Set}function GC(t){return t instanceof globalThis.Map}function HC(t){return s.IsObject(t)&&s.HasPropertyKey(t,"check")&&s.HasPropertyKey(t,"errors")&&s.IsFunction(t.check)&&s.IsFunction(t.errors)}function fd(t){return s.HasPropertyKey(t,"~guard")&&HC(t["~guard"])}function gd(t){return s.HasPropertyKey(t,"~refine")&&s.IsArray(t["~refine"])&&s.Every(t["~refine"],0,e=>s.IsObject(e)&&s.HasPropertyKey(e,"check")&&s.HasPropertyKey(e,"error")&&s.IsFunction(e.check)&&s.IsFunction(e.error))}function Mt(t){return s.IsObject(t)&&!s.IsArray(t)}function Fa(t){return s.IsBoolean(t)}function M(t){return Mt(t)||Fa(t)}function hd(t){return s.HasPropertyKey(t,"additionalItems")&&M(t.additionalItems)}function sr(t){return s.HasPropertyKey(t,"additionalProperties")&&M(t.additionalProperties)}function yd(t){return s.HasPropertyKey(t,"allOf")&&s.IsArray(t.allOf)&&t.allOf.every(e=>M(e))}function ii(t){return s.HasPropertyKey(t,"$anchor")&&s.IsString(t.$anchor)}function kd(t){return s.HasPropertyKey(t,"anyOf")&&s.IsArray(t.anyOf)&&t.anyOf.every(e=>M(e))}function Sd(t){return s.HasPropertyKey(t,"const")}function cn(t){return s.HasPropertyKey(t,"contains")&&M(t.contains)}function ar(t){return s.HasPropertyKey(t,"default")}function Id(t){return s.HasPropertyKey(t,"dependencies")&&s.IsObject(t.dependencies)&&Object.values(t.dependencies).every(e=>M(e)||s.IsArray(e)&&e.every(r=>s.IsString(r)))}function xd(t){return s.HasPropertyKey(t,"dependentRequired")&&s.IsObject(t.dependentRequired)&&Object.values(t.dependentRequired).every(e=>s.IsArray(e)&&e.every(r=>s.IsString(r)))}function Pd(t){return s.HasPropertyKey(t,"dependentSchemas")&&s.IsObject(t.dependentSchemas)&&Object.values(t.dependentSchemas).every(e=>M(e))}function Er(t){return s.HasPropertyKey(t,"$dynamicAnchor")&&s.IsString(t.$dynamicAnchor)}function wd(t){return s.HasPropertyKey(t,"$dynamicRef")&&s.IsString(t.$dynamicRef)}function vd(t){return s.HasPropertyKey(t,"else")&&M(t.else)}function bd(t){return s.HasPropertyKey(t,"enum")&&s.IsArray(t.enum)}function Ad(t){return s.HasPropertyKey(t,"exclusiveMaximum")&&(s.IsNumber(t.exclusiveMaximum)||s.IsBigInt(t.exclusiveMaximum))}function Xn(t){return s.HasPropertyKey(t,"exclusiveMinimum")&&(s.IsNumber(t.exclusiveMinimum)||s.IsBigInt(t.exclusiveMinimum))}function Na(t){return s.HasPropertyKey(t,"format")&&s.IsString(t.format)}function ur(t){return s.HasPropertyKey(t,"$id")&&s.IsString(t.$id)}function Td(t){return s.HasPropertyKey(t,"if")&&M(t.if)}function eo(t){return s.HasPropertyKey(t,"items")&&(M(t.items)||s.IsArray(t.items)&&t.items.every(e=>M(e)))}function Rd(t){return eo(t)&&s.IsArray(t.items)}function Cd(t){return s.HasPropertyKey(t,"maximum")&&(s.IsNumber(t.maximum)||s.IsBigInt(t.maximum))}function Ed(t){return s.HasPropertyKey(t,"maxContains")&&s.IsNumber(t.maxContains)}function qa(t){return s.HasPropertyKey(t,"maxItems")&&s.IsNumber(t.maxItems)}function $d(t){return s.HasPropertyKey(t,"maxLength")&&s.IsNumber(t.maxLength)}function Md(t){return s.HasPropertyKey(t,"maxProperties")&&s.IsNumber(t.maxProperties)}function to(t){return s.HasPropertyKey(t,"minimum")&&(s.IsNumber(t.minimum)||s.IsBigInt(t.minimum))}function fn(t){return s.HasPropertyKey(t,"minContains")&&s.IsNumber(t.minContains)}function si(t){return s.HasPropertyKey(t,"minItems")&&s.IsNumber(t.minItems)}function Ba(t){return s.HasPropertyKey(t,"minLength")&&s.IsNumber(t.minLength)}function Wa(t){return s.HasPropertyKey(t,"minProperties")&&s.IsNumber(t.minProperties)}function Od(t){return s.HasPropertyKey(t,"multipleOf")&&(s.IsNumber(t.multipleOf)||s.IsBigInt(t.multipleOf))}function _d(t){return s.HasPropertyKey(t,"not")&&M(t.not)}function Dd(t){return s.HasPropertyKey(t,"oneOf")&&s.IsArray(t.oneOf)&&t.oneOf.every(e=>M(e))}function Ua(t){return s.HasPropertyKey(t,"pattern")&&(s.IsString(t.pattern)||t.pattern instanceof RegExp)}function ai(t){return s.HasPropertyKey(t,"patternProperties")&&s.IsObject(t.patternProperties)&&Object.values(t.patternProperties).every(e=>M(e))}function ro(t){return s.HasPropertyKey(t,"prefixItems")&&s.IsArray(t.prefixItems)&&t.prefixItems.every(e=>M(e))}function ui(t){return s.HasPropertyKey(t,"properties")&&s.IsObject(t.properties)&&Object.values(t.properties).every(e=>M(e))}function Ld(t){return s.HasPropertyKey(t,"propertyNames")&&(s.IsObject(t.propertyNames)||M(t.propertyNames))}function zC(t){return s.HasPropertyKey(t,"$recursiveAnchor")&&s.IsBoolean(t.$recursiveAnchor)}function Ka(t){return zC(t)&&s.IsEqual(t.$recursiveAnchor,!0)}function Fd(t){return s.HasPropertyKey(t,"$recursiveRef")&&s.IsString(t.$recursiveRef)}function Nd(t){return s.HasPropertyKey(t,"$ref")&&s.IsString(t.$ref)}function gn(t){return s.HasPropertyKey(t,"required")&&s.IsArray(t.required)&&t.required.every(e=>s.IsString(e))}function qd(t){return s.HasPropertyKey(t,"then")&&M(t.then)}function Bd(t){return s.HasPropertyKey(t,"type")&&(s.IsString(t.type)||s.IsArray(t.type)&&t.type.every(e=>s.IsString(e)))}function pi(t){return s.HasPropertyKey(t,"uniqueItems")&&s.IsBoolean(t.uniqueItems)}function ja(t){return s.HasPropertyKey(t,"unevaluatedItems")&&M(t.unevaluatedItems)}function Ga(t){return s.HasPropertyKey(t,"unevaluatedProperties")&&M(t.unevaluatedProperties)}var ot=class{constructor(){let e=new Set,r=new Set;this.stack=[{indices:e,keys:r}]}Push(){let e=new Set,r=new Set;return this.stack.push({indices:e,keys:r}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let r of e)r.GetIndices().forEach(n=>this.GetIndices().add(n)),r.GetKeys().forEach(n=>this.GetKeys().add(n));return!0}},di=class extends ot{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},Le=class extends di{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};function ah(t,e,r,n){return r["~guard"].check(n)}function uh(t,e,r,n,o,i){return o["~guard"].check(i)||e.AddError({keyword:"~guard",schemaPath:r,instancePath:n,params:{errors:o["~guard"].errors(i)}})}var Mr={};Ct(Mr,{Hash:()=>mE,HashCode:()=>fh});function Y(){throw new Error("Unreachable")}function JC(t){let e=new Set,r=t;for(;r&&r!==Object.prototype;){for(let n of Reflect.ownKeys(r))n!=="constructor"&&typeof n!="symbol"&&e.add(n);r=Object.getPrototypeOf(r)}return[...e]}function QC(t){return typeof t=="number"}var it;(function(t){t[t.Array=0]="Array",t[t.BigInt=1]="BigInt",t[t.Boolean=2]="Boolean",t[t.Date=3]="Date",t[t.Constructor=4]="Constructor",t[t.Function=5]="Function",t[t.Null=6]="Null",t[t.Number=7]="Number",t[t.Object=8]="Object",t[t.RegExp=9]="RegExp",t[t.String=10]="String",t[t.Symbol=11]="Symbol",t[t.TypeArray=12]="TypeArray",t[t.Undefined=13]="Undefined"})(it||(it={}));var oo=BigInt("14695981039346656037"),[YC,ZC]=[BigInt("1099511628211"),BigInt("18446744073709551616")],XC=Array.from({length:256}).map((t,e)=>BigInt(e)),lh=new Float64Array(1),mh=new DataView(lh.buffer),ch=new Uint8Array(lh.buffer);function We(t){oo=oo^XC[t],oo=oo*YC%ZC}function eE(t){We(it.Array);for(let e of t)$r(e)}function tE(t){We(it.BigInt),mh.setBigInt64(0,t);for(let e of ch)We(e)}function ph(t){We(it.Boolean),We(t?1:0)}function rE(t){We(it.Constructor),$r(t.toString())}function nE(t){We(it.Date),$r(t.getTime())}function oE(t){We(it.Function),$r(t.toString())}function iE(t){We(it.Null)}function dh(t){We(it.Number),mh.setFloat64(0,t,!0);for(let e of ch)We(e)}function sE(t){We(it.Object);for(let e of JC(t).sort())$r(e),$r(t[e])}function aE(t){We(it.RegExp),Wd(t.toString())}var uE=new TextEncoder;function Wd(t){We(it.String);for(let e of uE.encode(t))We(e)}function pE(t){We(it.Symbol),$r(t.toString())}function dE(t){We(it.TypeArray);let e=new Uint8Array(t.buffer);for(let r=0;r<e.length;r++)We(e[r])}function lE(t){return We(it.Undefined)}function $r(t){return nt.IsTypeArray(t)?dE(t):nt.IsDate(t)?nE(t):nt.IsRegExp(t)?aE(t):nt.IsBoolean(t)?ph(t.valueOf()):nt.IsString(t)?Wd(t.valueOf()):nt.IsNumber(t)?dh(t.valueOf()):QC(t)?dh(t):s.IsArray(t)?eE(t):s.IsBoolean(t)?ph(t):s.IsBigInt(t)?tE(t):s.IsConstructor(t)?rE(t):s.IsNull(t)?iE(t):s.IsObject(t)?sE(t):s.IsString(t)?Wd(t):s.IsSymbol(t)?pE(t):s.IsUndefined(t)?lE(t):s.IsFunction(t)?oE(t):Y()}function fh(t){return oo=BigInt("14695981039346656037"),$r(t),oo}function mE(t){return fh(t).toString(16).padStart(16,"0")}function gh(t,e,r,n){return s.Every(r["~refine"],0,(o,i)=>o.check(n))}function hh(t,e,r,n,o,i){return s.EveryAll(o["~refine"],0,(a,u)=>a.check(i)||e.AddError({keyword:"~refine",schemaPath:r,instancePath:n,params:{index:u,message:a.error(i)}}))}function yh(t){return eo(t)&&s.IsArray(t.items)}function kh(t,e,r,n){return yh(r)?n.every((i,a)=>s.IsLessThan(a,r.items.length)||vt(t,e,r.additionalItems,i)&&e.AddIndex(a)):!0}function Sh(t,e,r,n,o,i){return yh(o)?i.every((u,p)=>{let d=`${r}/additionalItems`,l=`${n}/${p}`;return s.IsLessThan(p,o.items.length)||bt(t,e,d,l,o.additionalItems,u)&&e.AddIndex(p)}):!0}function cE(t){return`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Ih(t){let e=[];return ai(t)&&e.push(...s.Keys(t.patternProperties)),ui(t)&&e.push(...s.Keys(t.properties).map(cE)),s.IsEqual(e.length,0)?"(?!)":`(${e.join("|")})`}function xh(t,e,r,n){let o=new RegExp(Ih(r));return s.Every(s.Keys(n),0,(a,u)=>o.test(a)||vt(t,e,r.additionalProperties,n[a])&&e.AddKey(a))}function Ph(t,e,r,n,o,i){let a=new RegExp(Ih(o)),u=[];return s.EveryAll(s.Keys(i),0,(d,l)=>{let m=`${r}/additionalProperties`,c=`${n}/${d}`,h=new Le,y=a.test(d)||bt(t,h,m,c,o.additionalProperties,i[d])&&e.AddKey(d);return y||u.push(d),y})||e.AddError({keyword:"additionalProperties",schemaPath:r,instancePath:n,params:{additionalProperties:u}})}function wh(t,e,r,n){let o=r.allOf.reduce((i,a)=>{let u=new ot;return z(t,u,a,n)?[...i,u]:i},[]);return s.IsEqual(o.length,r.allOf.length)&&e.Merge(o)}function vh(t,e,r,n,o,i){let a=[],u=o.allOf.reduce((d,l,m)=>{let c=`${r}/allOf/${m}`,h=new Le,y=de(t,h,c,n,l,i);return y||a.push(h),y?[...d,h]:d},[]),p=s.IsEqual(u.length,o.allOf.length)&&e.Merge(u);return p||a.forEach(d=>d.GetErrors().forEach(l=>e.AddError(l))),p}function bh(t,e,r,n){let o=r.anyOf.reduce((i,a)=>{let u=new ot;return z(t,u,a,n)?[...i,u]:i},[]);return s.IsGreaterThan(o.length,0)&&e.Merge(o)}function Ah(t,e,r,n,o,i){let a=[],u=o.anyOf.reduce((d,l,m)=>{let c=new Le,h=`${r}/anyOf/${m}`,y=de(t,c,h,n,l,i);return y||a.push(c),y?[...d,c]:d},[]),p=s.IsGreaterThan(u.length,0)&&e.Merge(u);return p||a.forEach(d=>d.GetErrors().forEach(l=>e.AddError(l))),p||e.AddError({keyword:"anyOf",schemaPath:r,instancePath:n,params:{}})}function Kd(t,e,r,n){return r}function Th(t,e,r,n,o,i){return Kd(t,e,o,i)||e.AddError({keyword:"boolean",schemaPath:r,instancePath:n,params:{}})}function jd(t,e,r,n){return s.IsValueLike(r.const)?s.IsEqual(n,r.const):s.IsDeepEqual(n,r.const)}function Rh(t,e,r,n,o,i){return jd(t,e,o,i)||e.AddError({keyword:"const",schemaPath:r,instancePath:n,params:{allowedValue:o.const}})}function fE(t){return!(fn(t)&&s.IsEqual(t.minContains,0))}function Gd(t,e,r,n){return fE(r)?!s.IsEqual(n.length,0)&&n.some(o=>z(t,e,r.contains,o)):!0}function Ch(t,e,r,n,o,i){return Gd(t,e,o,i)||e.AddError({keyword:"contains",schemaPath:r,instancePath:n,params:{minContains:1}})}function Eh(t,e,r,n){let o=s.IsEqual(s.Keys(n).length,0),i=s.Every(s.Entries(r.dependencies),0,([a,u])=>!s.HasPropertyKey(n,a)||(s.IsArray(u)?u.every(p=>s.HasPropertyKey(n,p)):z(t,e,u,n)));return o||i}function $h(t,e,r,n,o,i){let a=s.IsEqual(s.Keys(i).length,0),u=s.EveryAll(s.Entries(o.dependencies),0,([p,d])=>{let l=`${r}/dependencies/${p}`;return!s.HasPropertyKey(i,p)||(s.IsArray(d)?d.every(m=>s.HasPropertyKey(i,m)||e.AddError({keyword:"dependencies",schemaPath:r,instancePath:n,params:{property:p,dependencies:d}})):de(t,e,l,n,d,i))});return a||u}function Mh(t,e,r,n){let o=s.IsEqual(s.Keys(n).length,0),i=s.Every(s.Entries(r.dependentRequired),0,([a,u])=>!s.HasPropertyKey(n,a)||u.every(p=>s.HasPropertyKey(n,p)));return o||i}function Oh(t,e,r,n,o,i){let a=s.IsEqual(s.Keys(i).length,0),u=s.EveryAll(s.Entries(o.dependentRequired),0,([p,d])=>!s.HasPropertyKey(i,p)||s.EveryAll(d,0,l=>s.HasPropertyKey(i,l)||e.AddError({keyword:"dependentRequired",schemaPath:r,instancePath:n,params:{property:p,dependencies:d}})));return a||u}function _h(t,e,r,n){let o=s.IsEqual(s.Keys(n).length,0),i=s.Every(s.Entries(r.dependentSchemas),0,([a,u])=>!s.HasPropertyKey(n,a)||z(t,e,u,n));return o||i}function Dh(t,e,r,n,o,i){let a=s.IsEqual(s.Keys(i).length,0),u=s.EveryAll(s.Entries(o.dependentSchemas),0,([p,d])=>{let l=`${r}/dependentSchemas/${p}`;return!s.HasPropertyKey(i,p)||de(t,e,l,n,d,i)});return a||u}function Lh(t,e,r,n){let o=t.DynamicRef(r)??!1;return M(o)&&z(t,e,o,n)}function Fh(t,e,r,n,o,i){let a=t.DynamicRef(o)??!1;return M(a)&&de(t,e,"#",n,a,i)}function zd(t,e,r,n){return r.enum.some(o=>s.IsValueLike(o)?s.IsEqual(n,o):s.IsDeepEqual(n,o))}function Nh(t,e,r,n,o,i){return zd(t,e,o,i)||e.AddError({keyword:"enum",schemaPath:r,instancePath:n,params:{allowedValues:o.enum}})}function Jd(t,e,r,n){return s.IsLessThan(n,r.exclusiveMaximum)}function qh(t,e,r,n,o,i){return Jd(t,e,o,i)||e.AddError({keyword:"exclusiveMaximum",schemaPath:r,instancePath:n,params:{comparison:"<",limit:o.exclusiveMaximum}})}function Qd(t,e,r,n){return s.IsGreaterThan(n,r.exclusiveMinimum)}function Bh(t,e,r,n,o,i){return Qd(t,e,o,i)||e.AddError({keyword:"exclusiveMinimum",schemaPath:r,instancePath:n,params:{comparison:">",limit:o.exclusiveMinimum}})}var yn={};Ct(yn,{Clear:()=>Qh,Entries:()=>QE,Get:()=>XE,Has:()=>ZE,IsDate:()=>io,IsDateTime:()=>Va,IsDuration:()=>Ha,IsEmail:()=>za,IsHostname:()=>Ja,IsIPv4:()=>Za,IsIPv6:()=>Xa,IsIdnEmail:()=>Qa,IsIdnHostname:()=>Ya,IsIri:()=>tu,IsIriReference:()=>eu,IsJsonPointer:()=>nu,IsJsonPointerUriFragment:()=>ru,IsRegex:()=>ou,IsRelativeJsonPointer:()=>iu,IsTime:()=>so,IsUri:()=>pu,IsUriReference:()=>su,IsUriTemplate:()=>au,IsUrl:()=>du,IsUuid:()=>lu,Reset:()=>Yh,Set:()=>YE,Test:()=>e$});var gE=[0,31,28,31,30,31,30,31,31,30,31,30,31],hE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function yE(t){return t%4===0&&(t%100!==0||t%400===0)}function io(t){let e=hE.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&yE(r)?29:gE[n])}var kE=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function so(t,e=!0){let r=kE.exec(t);if(!r)return!1;let n=+r[1],o=+r[2],i=+r[3],a=r[4]==="-"?-1:1,u=+(r[5]||0),p=+(r[6]||0);if(u>23||p>59||e&&!r[4]&&t.toLowerCase().indexOf("z")===-1)return!1;if(n<=23&&o<=59&&i<60)return!0;let d=o-p*a,l=n-u*a-(d<0?1:0);return(l===23||l===-1)&&(d===59||d===-1)&&i<61}function Va(t,e=!0){let r=t.split(/T/i);return r.length===2&&io(r[0])&&so(r[1],e)}var SE=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function Ha(t){return SE.test(t)}var IE=/^(?!.*\.\.)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;function za(t){return IE.test(t)}function xE(t,e,r){t=r?Math.floor(t/700):t>>1,t+=Math.floor(t/e);let n=0;for(;t>455;)t=Math.floor(t/35),n+=36;return n+Math.floor(36*t/(t+38))}function Wh(t){let e=[],r=128,n=0,o=72,i=t.lastIndexOf("-");if(i>0)for(let u=0;u<i;u++){let p=t.charCodeAt(u);if(p>=128)throw new Error("Invalid punycode: non-basic before delimiter");e.push(p)}let a=i<0?0:i+1;for(;a<t.length;){let u=n,p=1,d=36;for(;;){if(a>=t.length)throw new Error("Invalid punycode: unexpected end of input");let m=t.charCodeAt(a++),c;if(m>=97&&m<=122)c=m-97;else if(m>=48&&m<=57)c=m-48+26;else if(m>=65&&m<=90)c=m-65;else throw new Error("Invalid punycode: bad digit character");n+=c*p;let h=d<=o?1:d>=o+26?26:d-o;if(c<h)break;p*=36-h,d+=36}let l=e.length+1;o=xE(n-u,l,u===0),r+=Math.floor(n/l),n%=l,e.splice(n,0,r),n++}return globalThis.String.fromCodePoint(...e)}function wE(t){return new RegExp("\\p{Mn}","u").test(String.fromCodePoint(t))}function vE(t){return new RegExp("\\p{Mc}","u").test(String.fromCodePoint(t))}function bE(t){return new RegExp("\\p{Me}","u").test(String.fromCodePoint(t))}function AE(t){return wE(t)||vE(t)||bE(t)}var TE=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),RE=new Set([2381,2509,2637,2765,2893,3021,3149,3277,3387,3388,3405,3530,6980,7082,7083,43456,69702,69759,69817,69939,69940,70080,70197,70477,70722,70850,71103,71231,71350,72767,73028,73029]);function CE(t){return new RegExp("\\p{Script=Greek}","u").test(String.fromCodePoint(t))}function EE(t){return new RegExp("\\p{Script=Hebrew}","u").test(String.fromCodePoint(t))}function $E(t){return new RegExp("\\p{Script=Hiragana}","u").test(String.fromCodePoint(t))}function ME(t){return new RegExp("\\p{Script=Katakana}","u").test(String.fromCodePoint(t))}function OE(t){return new RegExp("\\p{Script=Han}","u").test(String.fromCodePoint(t))}function _E(t){return t>=1632&&t<=1641}function DE(t){return t>=1776&&t<=1785}function LE(t){return RE.has(t)}function Uh(t){if(t.length===0)return!1;let e=[...t].map(a=>a.codePointAt(0)),r=e.length;if(e[0]===45||e[r-1]===45||r>=4&&e[2]===45&&e[3]===45||AE(e[0]))return!1;let n=!1,o=!1,i=!1;for(let a=0;a<r;a++){let u=e[a];if(TE.has(u))return!1;($E(u)||ME(u)||OE(u))&&(n=!0),_E(u)&&(o=!0),DE(u)&&(i=!0);let p=e[a-1],d=e[a+1];switch(u){case 183:if(p!==108||d!==108)return!1;break;case 885:if(d===void 0||!CE(d))return!1;break;case 1523:case 1524:if(p===void 0||!EE(p))return!1;break;case 8205:if(p===void 0||!LE(p))return!1;break;case 12539:break}}return!(t.includes("\u30FB")&&!n||o&&i)}function FE(t){if(t.charCodeAt(0)===45||t.charCodeAt(t.length-1)===45||t.length>=4&&t.charCodeAt(2)===45&&t.charCodeAt(3)===45)return!1;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);if(!(r>=97&&r<=122||r>=65&&r<=90||r>=48&&r<=57||r===45))return!1}return!0}function Kh(t){return t.toLowerCase().startsWith("xn--")}function jh(t){try{return Uh(Wh(t.slice(4)))}catch{return!1}}function Gh(t){return t.length===0||t.length>63?!1:Kh(t)?jh(t):Uh(t)}function Vh(t){return t.length===0||t.length>63?!1:Kh(t)?jh(t):FE(t)}function Ja(t){if(t.length===0||t.length>253||t.charCodeAt(t.length-1)===46)return!1;for(let e of t.split("."))if(!Vh(e))return!1;return!0}var qE=/^(?!.*\.\.)[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+(?:\.[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+)*@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?)*$/iu;function Qa(t){return qE.test(t)}function Ya(t){if(t.length===0||t.includes(" "))return!1;let e=t.normalize("NFC").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".");if(e.length>253)return!1;for(let r of e.split("."))if(!Gh(r))return!1;return!0}function Yd(t,e,r){let n=0,o=0,i=0,a=0;for(let u=e;u<r;u++){let p=t.charCodeAt(u);if(p===46){if(i===0||o>255||a===48&&i>1)return!1;n++,o=0,i=0,a=0}else if(p>=48&&p<=57)i===0&&(a=p),o=o*10+(p-48),i++;else return!1}return n===3&&i>0&&o<=255&&!(a===48&&i>1)}function Za(t){return Yd(t,0,t.length)}function BE(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function Xa(t){let e=t.length;if(e===0)return!1;let r=0,n=!1,o=0;if(t.charCodeAt(0)===58&&t.charCodeAt(1)===58){if(e===2)return!0;n=!0,o=2}for(;o<e;){let i=0,a=o;for(;o<e&&BE(t.charCodeAt(o));)o++,i++;if(i===0)return!1;let u=t.charCodeAt(o);if(u===46){if(!Yd(t,a,e))return!1;r+=2,o=e;break}if(i>4)return!1;if(r++,o===e)break;if(u!==58)return!1;if(o++,t.charCodeAt(o)===58){if(n||t.charCodeAt(o+1)===58)return!1;if(n=!0,o++,o===e)break}}return n?r<=7:r===8}function Hh(t){try{return new URL(t,"http://example.com"),!0}catch{return!1}}function eu(t){if(t.includes(" ")||t.includes("\\")||/[\x00-\x1F\x7F]/.test(t)||/%(?![0-9a-fA-F]{2})/.test(t))return!1;if(t==="")return!0;let e=t.indexOf(":");return e>0&&/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(t.substring(0,e))?Hh(t):t.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&e===-1?!1:Hh(t)}function tu(t){try{return new URL(t),!0}catch{return!1}}var WE=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function ru(t){return WE.test(t)}var UE=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function nu(t){return UE.test(t)}function ou(t){if(t.length===0)return!1;try{return new RegExp(t),!0}catch{return!1}}var KE=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function iu(t){return KE.test(t)}var jE=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function su(t){return jE.test(t)}var GE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;function au(t){return GE.test(t)}function zh(t){return t>=97&&t<=122||t>=65&&t<=90}function Jh(t){return zh(t)||t>=48&&t<=57}function uu(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function VE(t){return Jh(t)||t===43||t===45||t===46}function Zd(t){return Jh(t)||t===45||t===46||t===95||t===126}function Xd(t){return t===33||t===36||t===38||t===39||t===40||t===41||t===42||t===43||t===44||t===59||t===61}function HE(t){return Zd(t)||Xd(t)||t===58||t===64}function pu(t){let e=t.length;if(e===0||!zh(t.charCodeAt(0)))return!1;let r=1;for(;r<e;){let n=t.charCodeAt(r);if(n===58)break;if(!VE(n))return!1;r++}if(t.charCodeAt(r)!==58)return!1;if(r++,t.charCodeAt(r)===47&&t.charCodeAt(r+1)===47){r+=2;let n=r,o=-1;for(let i=r;i<e;i++){let a=t.charCodeAt(i);if(a===64){o=i;break}if(a===47||a===63||a===35)break}if(o!==-1){for(let i=n;i<o;i++){let a=t.charCodeAt(i);if(a===91||a===93)return!1;if(a===37){if(i+2>=o||!uu(t.charCodeAt(i+1))||!uu(t.charCodeAt(i+2)))return!1;i+=2}else if(!Zd(a)&&!Xd(a)&&a!==58)return!1}r=o+1}if(t.charCodeAt(r)===91){for(r++;r<e&&t.charCodeAt(r)!==93;)r++;if(t.charCodeAt(r)!==93)return!1;r++}else for(;r<e;){let i=t.charCodeAt(r);if(i===47||i===63||i===35||i===58)break;if(i<128&&!Zd(i)&&!Xd(i))return!1;r++}if(t.charCodeAt(r)===58)for(r++;r<e;){let i=t.charCodeAt(r);if(i===47||i===63||i===35)break;if(i<48||i>57)return!1;r++}}for(;r<e;){let n=t.charCodeAt(r);if(n===37){if(r+2>=e||!uu(t.charCodeAt(r+1))||!uu(t.charCodeAt(r+2)))return!1;r+=2}else{if(n>127)return!1;if(!(HE(n)||n===47||n===63||n===35))return!1}r++}return!0}var zE=/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;function du(t){return zE.test(t)}var JE=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function lu(t){return JE.test(t)}var fe=new Map;function Qh(){fe.clear()}function QE(){return[...fe.entries()]}function YE(t,e){fe.set(t,e)}function ZE(t){return fe.has(t)}function XE(t){return fe.get(t)}function e$(t,e){return fe.get(t)?.(e)??!0}function Yh(){Qh(),fe.set("date-time",Va),fe.set("date",io),fe.set("duration",Ha),fe.set("email",za),fe.set("hostname",Ja),fe.set("idn-email",Qa),fe.set("idn-hostname",Ya),fe.set("ipv4",Za),fe.set("ipv6",Xa),fe.set("iri-reference",eu),fe.set("iri",tu),fe.set("json-pointer-uri-fragment",ru),fe.set("json-pointer",nu),fe.set("regex",ou),fe.set("relative-json-pointer",iu),fe.set("time",so),fe.set("uri-reference",su),fe.set("uri-template",au),fe.set("uri",pu),fe.set("url",du),fe.set("uuid",lu)}Yh();function el(t,e,r,n){return yn.Test(r.format,n)}function Zh(t,e,r,n,o,i){return el(t,e,o,i)||e.AddError({keyword:"format",schemaPath:r,instancePath:n,params:{format:o.format}})}function Xh(t,e,r,n){let o=qd(r)?r.then:!0,i=vd(r)?r.else:!0;return z(t,e,r.if,n)?z(t,e,o,n):z(t,e,i,n)}function ey(t,e,r,n,o,i){let a=qd(o)?o.then:!0,u=vd(o)?o.else:!0,p=new Le,d=de(t,p,`${r}/if`,n,o.if,i)?de(t,p,`${r}/then`,n,a,i)||e.AddError({keyword:"if",schemaPath:r,instancePath:n,params:{failingKeyword:"then"}}):de(t,e,`${r}/else`,n,u,i)||e.AddError({keyword:"if",schemaPath:r,instancePath:n,params:{failingKeyword:"else"}});return d&&e.Merge([p]),d}function t$(t,e,r,n){return s.Every(r.items,0,(o,i)=>s.IsLessEqualThan(n.length,i)||vt(t,e,o,n[i])&&e.AddIndex(i))}function r$(t,e,r,n,o,i){return s.EveryAll(o.items,0,(a,u)=>{let p=`${r}/items/${u}`,d=`${n}/${u}`;return s.IsLessEqualThan(i.length,u)||bt(t,e,p,d,a,i[u])&&e.AddIndex(u)})}function n$(t,e,r,n){let o=ro(r)?r.prefixItems.length:0;return s.Every(n,o,(i,a)=>vt(t,e,r.items,i)&&e.AddIndex(a))}function o$(t,e,r,n,o,i){let a=ro(o)?o.prefixItems.length:0;return s.EveryAll(i,a,(u,p)=>{let d=`${r}/items`,l=`${n}/${p}`;return bt(t,e,d,l,o.items,u)&&e.AddIndex(p)})}function ty(t,e,r,n){return Rd(r)?t$(t,e,r,n):n$(t,e,r,n)}function ry(t,e,r,n,o,i){return Rd(o)?r$(t,e,r,n,o,i):o$(t,e,r,n,o,i)}function i$(t){return cn(t)}function tl(t,e,r,n){if(!i$(r))return!0;let o=n.reduce((i,a)=>z(t,e,r.contains,a)?++i:i,0);return s.IsLessEqualThan(o,r.maxContains)}function ny(t,e,r,n,o,i){let a=fn(o)?o.minContains:1;return tl(t,e,o,i)||e.AddError({keyword:"contains",schemaPath:r,instancePath:n,params:{minContains:a,maxContains:o.maxContains}})}function rl(t,e,r,n){return s.IsLessEqualThan(n,r.maximum)}function oy(t,e,r,n,o,i){return rl(t,e,o,i)||e.AddError({keyword:"maximum",schemaPath:r,instancePath:n,params:{comparison:"<=",limit:o.maximum}})}function nl(t,e,r,n){return s.IsLessEqualThan(n.length,r.maxItems)}function iy(t,e,r,n,o,i){return nl(t,e,o,i)||e.AddError({keyword:"maxItems",schemaPath:r,instancePath:n,params:{limit:o.maxItems}})}function ol(t,e,r,n){return s.IsMaxLength(n,r.maxLength)}function sy(t,e,r,n,o,i){return ol(t,e,o,i)||e.AddError({keyword:"maxLength",schemaPath:r,instancePath:n,params:{limit:o.maxLength}})}function il(t,e,r,n){return s.IsLessEqualThan(s.Keys(n).length,r.maxProperties)}function ay(t,e,r,n,o,i){return il(t,e,o,i)||e.AddError({keyword:"maxProperties",schemaPath:r,instancePath:n,params:{limit:o.maxProperties}})}function s$(t){return cn(t)}function sl(t,e,r,n){if(!s$(r))return!0;let o=n.reduce((i,a)=>z(t,e,r.contains,a)?++i:i,0);return s.IsGreaterEqualThan(o,r.minContains)}function uy(t,e,r,n,o,i){return sl(t,e,o,i)||e.AddError({keyword:"contains",schemaPath:r,instancePath:n,params:{minContains:o.minContains}})}function al(t,e,r,n){return s.IsGreaterEqualThan(n,r.minimum)}function py(t,e,r,n,o,i){return al(t,e,o,i)||e.AddError({keyword:"minimum",schemaPath:r,instancePath:n,params:{comparison:">=",limit:o.minimum}})}function ul(t,e,r,n){return s.IsGreaterEqualThan(n.length,r.minItems)}function dy(t,e,r,n,o,i){return ul(t,e,o,i)||e.AddError({keyword:"minItems",schemaPath:r,instancePath:n,params:{limit:o.minItems}})}function pl(t,e,r,n){return s.IsMinLength(n,r.minLength)}function ly(t,e,r,n,o,i){return pl(t,e,o,i)||e.AddError({keyword:"minLength",schemaPath:r,instancePath:n,params:{limit:o.minLength}})}function dl(t,e,r,n){return s.IsGreaterEqualThan(s.Keys(n).length,r.minProperties)}function my(t,e,r,n,o,i){return dl(t,e,o,i)||e.AddError({keyword:"minProperties",schemaPath:r,instancePath:n,params:{limit:o.minProperties}})}function ll(t,e,r,n){return s.IsMultipleOf(n,r.multipleOf)}function cy(t,e,r,n,o,i){return ll(t,e,o,i)||e.AddError({keyword:"multipleOf",schemaPath:r,instancePath:n,params:{multipleOf:o.multipleOf}})}function ml(t,e,r,n){let o=new ot;return!z(t,o,r.not,n)&&e.Merge([o])}function fy(t,e,r,n,o,i){return ml(t,e,o,i)||e.AddError({keyword:"not",schemaPath:r,instancePath:n,params:{}})}function gy(t,e,r,n){let o=r.oneOf.reduce((i,a)=>{let u=new ot;return z(t,u,a,n)?[...i,u]:i},[]);return s.IsEqual(o.length,1)&&e.Merge(o)}function hy(t,e,r,n,o,i){let a=[],u=[],p=o.oneOf.reduce((l,m,c)=>{let h=new Le,y=`${r}/oneOf/${c}`,k=de(t,h,y,n,m,i);return k&&u.push(c),k||a.push(h),k?[...l,h]:l},[]),d=s.IsEqual(p.length,1)&&e.Merge(p);return!d&&s.IsEqual(u.length,0)&&a.forEach(l=>l.GetErrors().forEach(m=>e.AddError(m))),d||e.AddError({keyword:"oneOf",schemaPath:r,instancePath:n,params:{passingSchemas:u}})}function cl(t,e,r,n){return(s.IsString(r.pattern)?new RegExp(r.pattern,"u"):r.pattern).test(n)}function yy(t,e,r,n,o,i){return cl(t,e,o,i)||e.AddError({keyword:"pattern",schemaPath:r,instancePath:n,params:{pattern:o.pattern}})}function ky(t,e,r,n){return s.Every(s.Entries(r.patternProperties),0,([o,i])=>{let a=new RegExp(o,"u");return s.Every(s.Entries(n),0,([u,p])=>!a.test(u)||vt(t,e,i,p)&&e.AddKey(u))})}function Sy(t,e,r,n,o,i){return s.EveryAll(s.Entries(o.patternProperties),0,([a,u])=>{let p=`${r}/patternProperties/${a}`,d=new RegExp(a,"u");return s.EveryAll(s.Entries(i),0,([l,m])=>{let c=`${n}/${l}`;return!d.test(l)||bt(t,e,p,c,u,m)&&e.AddKey(l)})})}function Iy(t,e,r,n){return s.IsEqual(n.length,0)||s.Every(r.prefixItems,0,(o,i)=>s.IsLessEqualThan(n.length,i)||vt(t,e,o,n[i])&&e.AddIndex(i))}function xy(t,e,r,n,o,i){return s.IsEqual(i.length,0)||s.EveryAll(o.prefixItems,0,(a,u)=>{let p=`${r}/prefixItems/${u}`,d=`${n}/${u}`;return s.IsLessEqualThan(i.length,u)||bt(t,e,p,d,a,i[u])&&e.AddIndex(u)})}var kt={};Ct(kt,{Get:()=>p$,Reset:()=>a$,Set:()=>u$});var _r={immutableTypes:!1,maxErrors:8,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1};function a$(){_r.immutableTypes=!1,_r.maxErrors=8,_r.useAcceleration=!0,_r.exactOptionalPropertyTypes=!1,_r.enumerableKind=!1,_r.correctiveParse=!1}function u$(t){for(let e of s.Keys(t)){let r=t[e];r!==void 0&&Object.defineProperty(_r,e,{value:r})}}function p$(){return _r}function fl(t,e){return t.includes(e)||kt.Get().exactOptionalPropertyTypes}function gl(t,e){return s.IsUndefined(t[e])}function Py(t,e,r,n){let o=gn(r)?r.required:[];return s.Every(s.Entries(r.properties),0,([a,u])=>{let p=!s.HasPropertyKey(n,a)||vt(t,e,u,n[a])&&e.AddKey(a);return fl(o,a)?p:gl(n,a)||p})}function wy(t,e,r,n,o,i){let a=gn(o)?o.required:[];return s.EveryAll(s.Entries(o.properties),0,([p,d])=>{let l=`${r}/properties/${p}`,m=`${n}/${p}`,c=()=>!s.HasPropertyKey(i,p)||bt(t,e,l,m,d,i[p])&&e.AddKey(p);return fl(a,p)?c():gl(i,p)||c()})}function vy(t,e,r,n){return s.Every(s.Keys(n),0,(o,i)=>z(t,e,r.propertyNames,o))}function by(t,e,r,n,o,i){let a=[];return s.EveryAll(s.Keys(i),0,(p,d)=>{let l=`${n}/${p}`,m=`${r}/propertyNames`,c=new Le,h=de(t,c,m,l,o.propertyNames,p);return h||a.push(p),h})||e.AddError({keyword:"propertyNames",schemaPath:r,instancePath:n,params:{propertyNames:a}})}function Ay(t,e,r,n){let o=t.RecursiveRef(r)??!1;return M(o)&&z(t,e,o,n)}function Ty(t,e,r,n,o,i){let a=t.RecursiveRef(o)??!1;return M(a)&&de(t,e,"#",n,a,i)}function Ry(t,e,r,n){let o=t.Ref(r)??!1,i=new ot,a=M(o)&&z(t,i,o,n);return a&&e.Merge([i]),a}function Cy(t,e,r,n,o,i){let a=t.Ref(o)??!1,u=new Le,p=M(a)&&de(t,u,"#",n,a,i);return p&&e.Merge([u]),p||u.GetErrors().forEach(d=>e.AddError(d)),p}function Ey(t,e,r,n){return s.Every(r.required,0,o=>s.HasPropertyKey(n,o))}function $y(t,e,r,n,o,i){let a=[];return s.EveryAll(o.required,0,p=>{let d=s.HasPropertyKey(i,p);return d||a.push(p),d})||e.AddError({keyword:"required",schemaPath:r,instancePath:n,params:{requiredProperties:a}})}function hl(t,e,r,n,o){return s.IsEqual(r,"object")?s.IsObjectNotArray(o):s.IsEqual(r,"array")?s.IsArray(o):s.IsEqual(r,"boolean")?s.IsBoolean(o):s.IsEqual(r,"integer")?s.IsInteger(o):s.IsEqual(r,"number")?s.IsNumber(o):s.IsEqual(r,"null")?s.IsNull(o):s.IsEqual(r,"string")?s.IsString(o):s.IsEqual(r,"asyncIterator")?s.IsAsyncIterator(o):s.IsEqual(r,"bigint")?s.IsBigInt(o):s.IsEqual(r,"constructor")?s.IsConstructor(o):s.IsEqual(r,"function")?s.IsFunction(o):s.IsEqual(r,"iterator")?s.IsIterator(o):s.IsEqual(r,"symbol")?s.IsSymbol(o):s.IsEqual(r,"undefined")?s.IsUndefined(o):s.IsEqual(r,"void")?s.IsUndefined(o):!0}function My(t,e,r,n,o){return r.some(i=>hl(t,e,i,n,o))}function Oy(t,e,r,n){return s.IsArray(r.type)?My(t,e,r.type,r,n):hl(t,e,r.type,r,n)}function _y(t,e,r,n,o,i){return(s.IsArray(o.type)?My(t,e,o.type,o,i):hl(t,e,o.type,o,i))||e.AddError({keyword:"type",schemaPath:r,instancePath:n,params:{type:o.type}})}function Dy(t,e,r,n){let o=e.GetIndices();return s.Every(n,0,(i,a)=>(o.has(a)||z(t,e,r.unevaluatedItems,i))&&e.AddIndex(a))}function Ly(t,e,r,n,o,i){let a=e.GetIndices(),u=[];return s.EveryAll(i,0,(d,l)=>{let m=new Le,c=(a.has(l)||de(t,m,r,n,o.unevaluatedItems,d))&&e.AddIndex(l);return c||u.push(l),c})||e.AddError({keyword:"unevaluatedItems",schemaPath:r,instancePath:n,params:{unevaluatedItems:u}})}function Fy(t,e,r,n){let o=e.GetKeys();return s.Every(s.Entries(n),0,([i,a])=>o.has(i)||z(t,e,r.unevaluatedProperties,a)&&e.AddKey(i))}function Ny(t,e,r,n,o,i){let a=e.GetKeys(),u=[];return s.EveryAll(s.Entries(i),0,([d,l])=>{let m=new Le,c=a.has(d)||de(t,m,r,n,o.unevaluatedProperties,l)&&e.AddKey(d);return c||u.push(d),c})||e.AddError({keyword:"unevaluatedProperties",schemaPath:r,instancePath:n,params:{unevaluatedProperties:u}})}function qy(t){return!s.IsEqual(t.uniqueItems,!1)}function By(t,e,r,n){if(!qy(r))return!0;let o=new Set(n.map(Mr.Hash)).size,i=n.length;return s.IsEqual(o,i)}function Wy(t,e,r,n,o,i){if(!qy(o))return!0;let a=new Set,u=i.reduce((d,l,m)=>{let c=Mr.Hash(l);return a.has(c)?[...d,m]:(a.add(c),d)},[]);return s.IsEqual(u.length,0)||e.AddError({keyword:"uniqueItems",schemaPath:r,instancePath:n,params:{duplicateItems:u}})}function vt(t,e,r,n){return e.Push()&&z(t,e,r,n)&&e.Pop()}function z(t,e,r,n){t.Push(r);let o=Fa(r)?Kd(t,e,r,n):(!Bd(r)||Oy(t,e,r,n))&&(!(s.IsObject(n)&&!s.IsArray(n))||(!gn(r)||Ey(t,e,r,n))&&(!sr(r)||xh(t,e,r,n))&&(!Id(r)||Eh(t,e,r,n))&&(!xd(r)||Mh(t,e,r,n))&&(!Pd(r)||_h(t,e,r,n))&&(!ai(r)||ky(t,e,r,n))&&(!ui(r)||Py(t,e,r,n))&&(!Ld(r)||vy(t,e,r,n))&&(!Wa(r)||dl(t,e,r,n))&&(!Md(r)||il(t,e,r,n)))&&(!s.IsArray(n)||(!hd(r)||kh(t,e,r,n))&&(!cn(r)||Gd(t,e,r,n))&&(!eo(r)||ty(t,e,r,n))&&(!Ed(r)||tl(t,e,r,n))&&(!qa(r)||nl(t,e,r,n))&&(!fn(r)||sl(t,e,r,n))&&(!si(r)||ul(t,e,r,n))&&(!ro(r)||Iy(t,e,r,n))&&(!pi(r)||By(t,e,r,n)))&&(!s.IsString(n)||(!$d(r)||ol(t,e,r,n))&&(!Ba(r)||pl(t,e,r,n))&&(!Na(r)||el(t,e,r,n))&&(!Ua(r)||cl(t,e,r,n)))&&(!(s.IsNumber(n)||s.IsBigInt(n))||(!Ad(r)||Jd(t,e,r,n))&&(!Xn(r)||Qd(t,e,r,n))&&(!Cd(r)||rl(t,e,r,n))&&(!to(r)||al(t,e,r,n))&&(!Od(r)||ll(t,e,r,n)))&&(!Nd(r)||Ry(t,e,r,n))&&(!Fd(r)||Ay(t,e,r,n))&&(!wd(r)||Lh(t,e,r,n))&&(!fd(r)||ah(t,e,r,n))&&(!Sd(r)||jd(t,e,r,n))&&(!bd(r)||zd(t,e,r,n))&&(!Td(r)||Xh(t,e,r,n))&&(!_d(r)||ml(t,e,r,n))&&(!yd(r)||wh(t,e,r,n))&&(!kd(r)||bh(t,e,r,n))&&(!Dd(r)||gy(t,e,r,n))&&(!ja(r)||!s.IsArray(n)||Dy(t,e,r,n))&&(!Ga(r)||!s.IsObject(n)||Fy(t,e,r,n))&&(!gd(r)||gh(t,e,r,n));return t.Pop(r),o}function bt(t,e,r,n,o,i){return e.Push()&&de(t,e,r,n,o,i)&&e.Pop()}function de(t,e,r,n,o,i){t.Push(o);let a=Fa(o)?Th(t,e,r,n,o,i):!!(+(!Bd(o)||_y(t,e,r,n,o,i))&+(!(s.IsObject(i)&&!s.IsArray(i))||!!(+(!gn(o)||$y(t,e,r,n,o,i))&+(!sr(o)||Ph(t,e,r,n,o,i))&+(!Id(o)||$h(t,e,r,n,o,i))&+(!xd(o)||Oh(t,e,r,n,o,i))&+(!Pd(o)||Dh(t,e,r,n,o,i))&+(!ai(o)||Sy(t,e,r,n,o,i))&+(!ui(o)||wy(t,e,r,n,o,i))&+(!Ld(o)||by(t,e,r,n,o,i))&+(!Wa(o)||my(t,e,r,n,o,i))&+(!Md(o)||ay(t,e,r,n,o,i))))&+(!s.IsArray(i)||!!(+(!hd(o)||Sh(t,e,r,n,o,i))&+(!cn(o)||Ch(t,e,r,n,o,i))&+(!eo(o)||ry(t,e,r,n,o,i))&+(!Ed(o)||ny(t,e,r,n,o,i))&+(!qa(o)||iy(t,e,r,n,o,i))&+(!fn(o)||uy(t,e,r,n,o,i))&+(!si(o)||dy(t,e,r,n,o,i))&+(!ro(o)||xy(t,e,r,n,o,i))&+(!pi(o)||Wy(t,e,r,n,o,i))))&+(!s.IsString(i)||!!(+(!$d(o)||sy(t,e,r,n,o,i))&+(!Ba(o)||ly(t,e,r,n,o,i))&+(!Na(o)||Zh(t,e,r,n,o,i))&+(!Ua(o)||yy(t,e,r,n,o,i))))&+(!(s.IsNumber(i)||s.IsBigInt(i))||!!(+(!Ad(o)||qh(t,e,r,n,o,i))&+(!Xn(o)||Bh(t,e,r,n,o,i))&+(!Cd(o)||oy(t,e,r,n,o,i))&+(!to(o)||py(t,e,r,n,o,i))&+(!Od(o)||cy(t,e,r,n,o,i))))&+(!Nd(o)||Cy(t,e,r,n,o,i))&+(!Fd(o)||Ty(t,e,r,n,o,i))&+(!wd(o)||Fh(t,e,r,n,o,i))&+(!fd(o)||uh(t,e,r,n,o,i))&+(!Sd(o)||Rh(t,e,r,n,o,i))&+(!bd(o)||Nh(t,e,r,n,o,i))&+(!Td(o)||ey(t,e,r,n,o,i))&+(!_d(o)||fy(t,e,r,n,o,i))&+(!yd(o)||vh(t,e,r,n,o,i))&+(!kd(o)||Ah(t,e,r,n,o,i))&+(!Dd(o)||hy(t,e,r,n,o,i))&+(!ja(o)||!s.IsArray(i)||Ly(t,e,r,n,o,i))&+(!Ga(o)||!s.IsObject(i)||Ny(t,e,r,n,o,i)))&&(!gd(o)||hh(t,e,r,n,o,i));return t.Pop(o),a}var Dr={};Ct(Dr,{DynamicRef:()=>v$,Ref:()=>kl});var pr={};Ct(pr,{Delete:()=>y$,Get:()=>g$,Has:()=>f$,Indices:()=>mi,Set:()=>h$});function Uy(t){if(t.length===0)throw Error("Cannot set root")}function Ky(t){if(!s.IsObject(t))throw Error("Cannot set value")}function d$(t){if(s.IsUnsafePropertyKey(t))throw Error("Pointer contains unsafe property key")}function jy(t){for(let e of t)d$(e)}function l$(t){return/^(0|[1-9]\d*)$/.test(t)}function Gy(t){return[t.slice(0,t.length-1),t.slice(t.length-1)[0]]}function m$(t,e){return s.IsObject(e)&&s.HasPropertyKey(e,t)}function c$(t,e){return s.IsObject(e)&&!s.IsUnsafePropertyKey(t)?e[t]:void 0}function yl(t,e){return t.reduce((r,n)=>c$(n,r),e)}function mi(t){if(s.IsEqual(t.length,0))return[];let e=t.split("/").map(r=>r.replace(/~1/g,"/").replace(/~0/g,"~"));return e.length>0&&e[0]===""?e.slice(1):e}function f$(t,e){let r=t;return mi(e).every(n=>m$(n,r)?(r=r[n],!0):!1)}function g$(t,e){let r=mi(e);return yl(r,t)}function h$(t,e,r){let n=mi(e);Uy(n),jy(n);let[o,i]=Gy(n),a=yl(o,t);return Ky(a),a[i]=r,t}function y$(t,e){let r=mi(e);Uy(r),jy(r);let[n,o]=Gy(r),i=yl(n,t);return Ky(i),s.IsArray(i)&&l$(o)?i.splice(+o,1):delete i[o],t}function k$(t,e,r){if(t.$id===r.hash)return t;let n=new URL(t.$id,e.href),o=new URL(r.href,e.href);if(s.IsEqual(n.pathname,o.pathname))return r.hash.startsWith("#")?Vy(t,e,r):t}function S$(t,e,r){let n=new URL(`#${t.$anchor}`,e.href),o=new URL(r.href,e.href);return s.IsEqual(n.href,o.href)?t:void 0}function I$(t,e,r){let n=new URL(`#${t.$dynamicAnchor}`,e.href),o=new URL(r.href,e.href);return s.IsEqual(n.href,o.href)?t:void 0}function Vy(t,e,r){if(r.href.endsWith("#"))return t;if(!r.hash.startsWith("#"))return;let n=decodeURIComponent(r.hash.slice(1));if(n.startsWith("/"))return pr.Get(t,n)}function x$(t,e,r){if(ur(t)){let n=k$(t,e,r);if(!s.IsUndefined(n))return n}if(ii(t)){let n=S$(t,e,r);if(!s.IsUndefined(n))return n}if(Er(t)){let n=I$(t,e,r);if(!s.IsUndefined(n))return n}return Vy(t,e,r)}function P$(t,e,r){return t.reduce((n,o)=>{let i=Sl(o,e,r);return s.IsUndefined(i)?n:i},void 0)}function w$(t,e,r){return s.Keys(t).reduce((n,o)=>{let i=Sl(t[o],e,r);return s.IsUndefined(i)?n:i},void 0)}function Sl(t,e,r){let n=Mt(t)&&ur(t)?new URL(t.$id,e.href):e;if(Mt(t)){let o=x$(t,n,r);if(!s.IsUndefined(o))return o}if(s.IsArray(t))return P$(t,n,r);if(s.IsObject(t))return w$(t,n,r)}function kl(t,e){let r=new URL("http://unknown/"),n=ur(t)?new URL(t.$id,r.href):r,o=new URL(e,n.href);return Sl(t,n,o)}function v$(t,e,r,n){let o=r.$dynamicRef.startsWith("#")?kl(e,r.$dynamicRef):kl(t,r.$dynamicRef);return s.IsUndefined(o)?void 0:!Mt(o)||!Er(o)||new URL(r.$dynamicRef,"http://unknown/").hash.startsWith("#/")?o:n.find(u=>u.$dynamicAnchor===o.$dynamicAnchor)??o}var ao=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Lr,Hy,zy,Jy,Qy,kn=class{constructor(e,r){Lr.add(this),this.context=e,this.schema=r,this.ids=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[]}BaseURL(){return this.ids.reduce((e,r)=>new URL(r.$id,e),new URL("http://unknown"))}Base(){return this.ids[this.ids.length-1]??this.schema}Push(e){Mt(e)&&(ur(e)&&(this.ids.push(e),ao(this,Lr,"m",Hy).call(this,e)),ii(e)&&this.anchors.push(e),Ka(e)&&this.recursiveAnchors.push(e),Er(e)&&this.dynamicAnchors.push(e))}Pop(e){Mt(e)&&(ur(e)&&(this.ids.pop(),ao(this,Lr,"m",zy).call(this,e)),ii(e)&&this.anchors.pop(),Ka(e)&&this.recursiveAnchors.pop(),Er(e)&&this.dynamicAnchors.pop())}Ref(e){return ao(this,Lr,"m",Jy).call(this,e)??ao(this,Lr,"m",Qy).call(this,e)}RecursiveRef(e){return Ka(this.Base())?Dr.Ref(this.recursiveAnchors[0],e.$recursiveRef):Dr.Ref(this.Base(),e.$recursiveRef)}DynamicRef(e){let r=this.schema;return Dr.DynamicRef(r,this.Base(),e,this.dynamicAnchors)}};Lr=new WeakSet,Hy=function t(e,r=!0){if(!Mt(e))return;let n=e;if(!(!r&&ur(n))){!r&&Er(n)&&this.dynamicAnchors.push(n);for(let o of s.Keys(n))ao(this,Lr,"m",t).call(this,n[o],!1)}},zy=function t(e,r=!0){if(!Mt(e))return;let n=e;if(!(!r&&ur(n))){!r&&Er(n)&&this.dynamicAnchors.pop();for(let o of s.Keys(n))ao(this,Lr,"m",t).call(this,n[o],!1)}},Jy=function(e){return s.HasPropertyKey(this.context,e.$ref)?this.context[e.$ref]:void 0},Qy=function(e){let r=this.schema;return e.$ref.startsWith("#")?Dr.Ref(this.Base(),e.$ref):Dr.Ref(r,e.$ref)};function Zy(t){switch(t.keyword){case"additionalProperties":return"must not have additional properties";case"anyOf":return"must match a schema in anyOf";case"boolean":return"schema is false";case"const":return"must be equal to constant";case"contains":return"must contain at least 1 valid item";case"dependencies":return`must have properties ${t.params.dependencies.join(", ")} when property ${t.params.property} is present`;case"dependentRequired":return`must have properties ${t.params.dependencies.join(", ")} when property ${t.params.property} is present`;case"enum":return"must be equal to one of the allowed values";case"exclusiveMaximum":return`must be ${t.params.comparison} ${t.params.limit}`;case"exclusiveMinimum":return`must be ${t.params.comparison} ${t.params.limit}`;case"format":return`must match format "${t.params.format}"`;case"if":return`must match "${t.params.failingKeyword}" schema`;case"maxItems":return`must not have more than ${t.params.limit} items`;case"maxLength":return`must not have more than ${t.params.limit} characters`;case"maxProperties":return`must not have more than ${t.params.limit} properties`;case"maximum":return`must be ${t.params.comparison} ${t.params.limit}`;case"minItems":return`must not have fewer than ${t.params.limit} items`;case"minLength":return`must not have fewer than ${t.params.limit} characters`;case"minProperties":return`must not have fewer than ${t.params.limit} properties`;case"minimum":return`must be ${t.params.comparison} ${t.params.limit}`;case"multipleOf":return`must be multiple of ${t.params.multipleOf}`;case"not":return"must not be valid";case"oneOf":return"must match exactly one schema in oneOf";case"pattern":return`must match pattern "${t.params.pattern}"`;case"propertyNames":return`property names ${t.params.propertyNames.join(", ")} are invalid`;case"required":return`must have required properties ${t.params.requiredProperties.join(", ")}`;case"type":return typeof t.params.type=="string"?`must be ${t.params.type}`:`must be either ${t.params.type.join(" or ")}`;case"unevaluatedItems":return"must not have unevaluated items";case"unevaluatedProperties":return"must not have unevaluated properties";case"uniqueItems":return"must not have duplicate items";case"~guard":return"must match check function";case"~refine":return t.params.message;default:return"an unknown validation error occurred"}}var A$=Zy;function Xy(){return A$}function mu(...t){let[e,r,n]=ee.Match(t,{3:(l,m,c)=>[l,m,c],2:(l,m)=>[{},l,m]}),o=kt.Get(),i=Xy(),a=[],u=new kn(e,r),p=new di(l=>{if(!s.IsGreaterEqualThan(a.length,o.maxErrors))return a.push({...l,message:i(l)})});return[de(u,p,"#","",r,n),a]}function xl(...t){let[e,r,n]=ee.Match(t,{3:(a,u,p)=>[a,u,p],2:(a,u)=>[{},a,u]}),o=new kn(e,r),i=new ot;return z(o,i,r,n)}var g={};Ct(g,{Assign:()=>R$,Clone:()=>ci,Create:()=>_$,Discard:()=>D$,Metrics:()=>Nt,Update:()=>L$});var Nt={assign:0,create:0,clone:0,discard:0,update:0};function R$(t,e){return Nt.assign+=1,{...t,...e}}function C$(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~guard")}function E$(t){return t.map(e=>Pl(e))}function $$(t){let e={},r=Object.getOwnPropertyDescriptors(t);for(let n of Object.keys(r)){let o=r[n];s.HasPropertyKey(o,"value")&&Object.defineProperty(e,n,{...o,value:Pl(o.value)})}return e}function M$(t){return new RegExp(t.source,t.flags)}function Pl(t){return t instanceof RegExp?M$(t):C$(t)?t:s.IsArray(t)?E$(t):s.IsObject(t)?$$(t):t}function ci(t){return Nt.clone+=1,Pl(t)}function O$(t,e){for(let r of Object.keys(e))Object.defineProperty(t,r,{configurable:!0,writable:!0,enumerable:!1,value:e[r]});return t}function tk(t,e){return{...t,...e}}function _$(t,e,r={}){Nt.create+=1;let n=kt.Get(),o=tk(e,r),i=n.enumerableKind?tk(o,t):O$(o,t);return n.immutableTypes?Object.freeze(i):i}function D$(t,e){Nt.discard+=1;let r={},n=Object.getOwnPropertyDescriptors(ci(t)),o=new Set(e);for(let i of Object.keys(n))o.has(i)||Object.defineProperty(r,i,n[i]);return r}function L$(t,e,r){Nt.update+=1;let n=kt.Get(),o=ci(t);for(let i of Object.keys(e))Object.defineProperty(o,i,{configurable:!0,writable:!0,enumerable:n.enumerableKind,value:e[i]});for(let i of Object.keys(r))Object.defineProperty(o,i,{configurable:!0,enumerable:!0,writable:!0,value:r[i]});return o}function v(t,e){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.IsEqual(t["~kind"],e)}function le(t){return s.IsObject(t)}function rk(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"OptionalAddAction")&&le(t.type)}function nk(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"OptionalRemoveAction")&&le(t.type)}function ok(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"ReadonlyAddAction")&&le(t.type)}function ik(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"ReadonlyRemoveAction")&&le(t.type)}function E(t,e,r){return g.Create({"~kind":"Deferred"},{action:t,parameters:e,options:r},{})}function Fr(t){return v(t,"Deferred")}function dr(t,e){return g.Create({"~kind":"Promise"},{type:"promise",item:t},e)}function Ge(t){return v(t,"Promise")}function sk(t){return g.Discard(t,["~kind","type","item"])}function ak(t){return g.Update(t,{"~immutable":!0},{})}function uo(t){return ak(t)}function fi(t){return le(t)&&s.HasPropertyKey(t,"~immutable")}function po(t){return g.Discard(t,["~optional"])}function Sn(t){return g.Update(t,{"~optional":!0},{})}function uk(t){return Sn(t)}function Ue(t){return le(t)&&s.HasPropertyKey(t,"~optional")}function cu(t){return g.Discard(t,["~readonly"])}function In(t){return g.Update(t,{"~readonly":!0},{})}function pk(t){return In(t)}function gi(t){return le(t)&&s.HasPropertyKey(t,"~readonly")}function Qt(t){return v(t,"Base")}function lr(t,e){return g.Create({"~kind":"Array"},{type:"array",items:t},e)}function te(t){return v(t,"Array")}function fu(t){return g.Discard(t,["~kind","type","items"])}function mr(t,e){return g.Create({"~kind":"AsyncIterator"},{type:"asyncIterator",iteratorItems:t},e)}function st(t){return v(t,"AsyncIterator")}function dk(t){return g.Discard(t,["~kind","type","iteratorItems"])}function xn(t,e,r={}){return g.Create({"~kind":"Constructor"},{type:"constructor",parameters:t,instanceType:e},r)}function Fe(t){return v(t,"Constructor")}function lk(t){return g.Discard(t,["~kind","type","parameters","instanceType"])}function Pn(t,e,r={}){return g.Create({"~kind":"Function"},{type:"function",parameters:t,returnType:e},r)}function Ne(t){return v(t,"Function")}function mk(t){return g.Discard(t,["~kind","type","parameters","returnType"])}function St(t,e){return g.Create({"~kind":"Ref"},{$ref:t},e)}function se(t){return v(t,"Ref")}function wl(t,e){return g.Create({"~kind":"Generic"},{type:"generic",parameters:t,expression:e})}function gu(t){return v(t,"Generic")}function vl(t){return g.Create({"~kind":"Any"},{},t)}function Ve(t){return v(t,"Any")}var ck="(?!)";function oe(t){return g.Create({"~kind":"Never"},{not:{}},t)}function Nr(t){return v(t,"Never")}function fk(t){return s.Keys(t).filter(e=>!Ue(t[e]))}function hu(t){return s.Keys(t)}function yu(t){return s.Values(t)}function O(t,e={}){let r=fk(t),n=r.length>0?{required:r}:{};return g.Create({"~kind":"Object"},{type:"object",...n,properties:t},e)}function N(t){return v(t,"Object")}function gk(t){return g.Discard(t,["~kind","type","properties","required"])}function B(t,e={}){return g.Create({"~kind":"Union"},{anyOf:t},e)}function b(t){return v(t,"Union")}function hk(t){return g.Discard(t,["~kind","anyOf"])}function Yt(t){return g.Create({"~kind":"Unknown"},{},t)}function Ze(t){return v(t,"Unknown")}function qr(t,e,r){let n=s.Keys(t).reduce((o,i)=>({...o,[i]:g.Update(t[i],{},{$id:i})}),{});return g.Create({"~kind":"Cyclic"},{$defs:n,$ref:e},r)}function he(t){return v(t,"Cyclic")}function yk(t){return s.IsObjectNotArray(t)&&s.HasPropertyKey(t,"~unsafe")&&s.IsNull(t["~unsafe"])}function $e(t){return v(t,"Infer")}function qe(t){return v(t,"Enum")}function qt(t,e={}){return g.Create({"~kind":"Intersect"},{allOf:t},e)}function D(t){return v(t,"Intersect")}function kk(t){return g.Discard(t,["~kind","allOf"])}function bl(t){return le(t)&&s.HasPropertyKey(t,"~codec")&&s.IsObject(t["~codec"])&&s.HasPropertyKey(t["~codec"],"encode")&&s.HasPropertyKey(t["~codec"],"decode")}var Ik="-?(?:0|[1-9][0-9]*)n";function xk(t){return g.Create({"~kind":"BigInt"},{type:"bigint"},t)}function Bt(t){return v(t,"BigInt")}function At(t){return v(t,"Boolean")}var ku="-?(?:0|[1-9][0-9]*)";function Su(t){return g.Create({"~kind":"Integer"},{type:"integer"},t)}function at(t){return v(t,"Integer")}function cr(t,e){return g.Create({"~kind":"Iterator"},{type:"iterator",iteratorItems:t},e)}function ut(t){return v(t,"Iterator")}function Pk(t){return g.Discard(t,["~kind","type","iteratorItems"])}var Al=class extends Error{constructor(e){super("Invalid Literal value"),Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}};function N$(t){return s.IsBigInt(t)?"bigint":s.IsBoolean(t)?"boolean":s.IsNumber(t)?"number":s.IsString(t)?"string":(()=>{throw new Al(t)})()}function Z(t,e){return g.Create({"~kind":"Literal"},{type:N$(t),const:t},e)}function Tl(t){return s.IsBigInt(t)||s.IsBoolean(t)||s.IsNumber(t)||s.IsString(t)}function wk(t){return G(t)&&s.IsBigInt(t.const)}function vk(t){return G(t)&&s.IsBoolean(t.const)}function Iu(t){return G(t)&&s.IsNumber(t.const)}function xu(t){return G(t)&&s.IsString(t.const)}function G(t){return v(t,"Literal")}function hi(t){return g.Create({"~kind":"Null"},{type:"null"},t)}function wn(t){return v(t,"Null")}var Pu="-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?";function Wt(t){return g.Create({"~kind":"Number"},{type:"number"},t)}function Ae(t){return v(t,"Number")}function Rl(t){return g.Create({"~kind":"Symbol"},{type:"symbol"},t)}function lo(t){return v(t,"Symbol")}var wu=".*";function Tt(t){return g.Create({"~kind":"String"},{type:"string"},t)}function Xe(t){return v(t,"String")}function yi(t){let e=bk(t);return s.IsEqual(e.length,2)?e[0]:[]}function q$(t){return!0}function Ak(t){return s.TakeLeft(t,(e,r)=>B$(e)?Ak(r):!1,()=>!0)}function Tk(t){return s.IsEqual(t.length,0)?!1:Ak(t)}function B$(t){return b(t)?Tk(t.anyOf):G(t)?q$(t.const):!1}function vu(t){return Tk(t)}function bu(t){return g.Create({"~kind":"TemplateLiteral"},{type:"string",pattern:t},{})}function Rk(t,e,r=[]){return s.TakeLeft(t,(n,o)=>Rk(o,e,[...r,`${n}${e}`]),()=>r)}function W$(t,e){return s.IsEqual(t.length,0)?[`${e}`]:Rk(t,e)}function Ck(t,e,r=[]){return s.TakeLeft(e,(n,o)=>Ck(t,o,[...r,...Ek(t,n)]),()=>r)}function Ek(t,e){return b(e)?Ck(t,e.anyOf):G(e)?W$(t,e.const):Y()}function $k(t,e){return s.TakeLeft(e,(r,n)=>$k(Ek(t,r),n),()=>t)}function U$(t){return t.map(e=>Z(e))}function K$(t){let e=$k([],t),r=U$(e);return B(r)}function j$(t){return s.IsEqual(t.length,0)?Y():s.IsEqual(t.length,1)&&G(t[0])?t[0]:K$(t)}function Cl(t){let e=yi(t);return s.IsEqual(e.length,0)?Tt():vu(e)?j$(e):bu(t)}function He(t){let e=Cl(t);return Te(e)?Tt():e}function ft(t,e){let r="object",n={[t]:e};return g.Create({"~kind":"Record"},{type:r,patternProperties:n})}function Mk(t){return ft(Br,t)}function Ok(t){return O({true:t,false:t})}function G$(t){return s.IsString(t)||s.IsNumber(t)?Z(t):s.IsNull(t)?hi():oe()}function Ut(t){return t.map(r=>G$(r))}function ki(t){let e=Ut(t);return B(e)}function mo(t){return ki(t.enum)}function _k(t,e){let r=ki(t);return Wr(r,e)}function Dk(t,e){return ft(co,e)}function Ke(t,e={}){let[r,n,o]=[t,t.length,!1];return g.Create({"~kind":"Tuple"},{type:"array",additionalItems:o,items:r,minItems:n},e)}function V(t){return v(t,"Tuple")}function Lk(t){return g.Discard(t,["~kind","type","items","minItems","additionalItems"])}function El(t){return t.reduceRight((r,n,o)=>({[o]:n,...r}),{})}function Fk(t){let e=El(t.items);return O(e)}function V$(t,e){return gi(t)?!!gi(e):!1}function H$(t,e){return Ue(t)?!!Ue(e):!1}function z$(t,e){let r=V$(t,e),n=H$(t,e),o=Se([t,e]),i=cu(po(o));return r&&n?In(Sn(i)):r&&!n?In(i):!r&&n?Sn(i):i}function J$(t,e,r){return r in t?r in e?z$(t[r],e[r]):t[r]:r in e?e[r]:oe()}function Q$(t,e){return[...new Set([...s.Keys(e),...s.Keys(t)])].reduce((n,o)=>({...n,[o]:J$(t,e,o)}),{})}function Nk(t){return N(t)?t.properties:V(t)?El(t.items):Y()}function qk(t,e){let r=Nk(t),n=Nk(e),o=Q$(r,n);return O(o)}function Bk(t,e){let r=vn(t,e);return s.IsEqual(r,Ii)?t:s.IsEqual(r,xi)||s.IsEqual(r,Si)?e:oe()}function Wk(t){return N(t)||V(t)}function Y$(t,e){let r=b(t),n=b(e);return r||n}function Z$(t,e){let r=bn(t),n=bn(e),o=Y$(r,n),i=Wk(r),a=Wk(n);return o?Se([r,n]):i&&a?qk(r,n):i&&!a?r:!i&&a?n:Bk(r,n)}function Uk(t,e,r=[]){return s.TakeLeft(e,(n,o)=>Uk(t,o,[...r,Z$(t,n)]),()=>s.IsEqual(r.length,0)?[t]:r)}function Kk(t,e,r=[]){return s.TakeLeft(t,(n,o)=>Kk(o,e,[...r,...Pi([n],e)]),()=>r)}function Pi(t,e=[]){return s.TakeLeft(t,(r,n)=>b(r)?Pi(n,Kk(r.anyOf,e)):Pi(n,Uk(r,e)),()=>e)}function Se(t){let e=Pi(t);return $l(e)}function Ot(t){return $l(t)}function bn(t){return D(t)?Se(t.allOf):b(t)?Ot(t.anyOf):t}function An(t){return s.IsEqual(t.length,1)?t[0]:s.IsEqual(t.length,0)?oe():B(t)}function jk(t,e){let r=Se(t);return Wr(r,e)}function Gk(t,e){return s.IsString(t)||s.IsNumber(t)?O({[t]:e}):s.IsEqual(t,!1)?O({false:e}):s.IsEqual(t,!0)?O({true:e}):O({})}function Vk(t,e){return ft(Au,e)}function Hk(t,e){return s.HasPropertyKey(t,"pattern")&&(s.IsString(t.pattern)||t.pattern instanceof RegExp)?ft(t.pattern.toString(),e):ft(Br,e)}function zk(t,e){let r=yi(t);return vu(r)?Wr(He(t),e):ft(t,e)}function X$(t){return b(t)?Zt(t.anyOf):[t]}function Zt(t){return t.reduce((e,r)=>[...e,...X$(r)],[])}function eM(t){return t.some(e=>Xe(e)||Ae(e)||at(e))}function tM(t,e){return s.IsEqual(eM(t),!0)?ft(Br,e):void 0}function rM(t,e){return t.reduce((r,n)=>G(n)&&(s.IsString(n.const)||s.IsNumber(n.const))?{...r,[n.const]:e}:r,{})}function nM(t,e){let r=rM(t,e);return O(r)}function Jk(t,e){let r=Zt(t),n=tM(r,e);return le(n)?n:nM(r,e)}function Wr(t,e){return Ve(t)?Mk(e):At(t)?Ok(e):qe(t)?_k(t.enum,e):at(t)?Dk(t,e):D(t)?jk(t.allOf,e):G(t)?Gk(t.const,e):Ae(t)?Vk(t,e):b(t)?Jk(t.anyOf,e):Xe(t)?Hk(t,e):Te(t)?zk(t.pattern,e):O({})}function Ml(t,e,r){return L([t])?g.Update(Wr(t,e),{},r):Ol(t,e,r)}function Qk(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return Ml(i,a,o)}var co=`^${ku}$`,Au=`^${Pu}$`,Br=`^${wu}$`;function Ol(t,e,r={}){return E("Record",[t,e],r)}function Yk(t,e,r={}){return Ml(t,e,r)}function Zk(t,e){return ft(t,e)}function _t(t){return s.Keys(t.patternProperties)[0]}function Tu(t){let e=_t(t);return s.IsEqual(e,Br)?Tt():s.IsEqual(e,co)?Su():s.IsEqual(e,Au)?Wt():Cl(e)}function et(t){return t.patternProperties[_t(t)]}function Me(t){return v(t,"Record")}function _l(t){return g.Create({"~kind":"Rest"},{type:"rest",items:t},{})}function fo(t){return v(t,"Rest")}function Xk(t){return v(t,"This")}function Dl(t){return g.Create({"~kind":"Undefined"},{type:"undefined"},t)}function Tn(t){return v(t,"Undefined")}function Kt(t){return v(t,"Void")}function eS(t){return xk()}function tS(t){return Tt()}function rS(t){return Wt()}function nS(t){return Su()}function oS(t){return oe()}function iS(t){return Z(t)}function sS(t){return B(t[1])}function aS(t){return t.length===3?[...t[0],...t[2]]:t.length===1?[...t[0]]:[]}function uS(t){return[t[0],...t[1]]}function pS(t){return t[1]}function Cu(t){return J(t.length,2)}function It(t,e,r){return Cu(t)?e(t[0],t[1]):r()}function aM(t,e){return J(e.indexOf(t),0)?[t,e.slice(t.length)]:[]}function Xt(t,e){for(let r=0;r<t.length;r++){let n=aM(t[r],e);if(Cu(n))return n}return[]}function sm(t,e){return Array.from({length:e-t+1},(r,n)=>String.fromCharCode(t+n))}var dS=[...sm(97,122),...sm(65,90)],lS="0",mS=sm(49,57),go=[lS,...mS],cS=" ",wi=`
|
|
238
|
-
`;var ho="_";var fS="$";var gS="//",hS="/*",pM="*/";function yS(t){let e=t.indexOf(pM);return J(e,-1)?"":t.slice(e+2)}function kS(t){let e=t.indexOf(wi);return J(e,-1)?"":t.slice(e)}function dM(t){return t.replace(/^[ \t\r\f\v]+/,"")}function Eu(t){let e=dM(t);return e.startsWith(hS)?Eu(yS(e.slice(2))):e.startsWith(gS)?Eu(kS(e.slice(2))):e}function jt(t){let e=t.trimStart();return e.startsWith(hS)?jt(yS(e.slice(2))):e.startsWith(gS)?jt(kS(e.slice(2))):e}var fee=[...go,ho];function am(t,e){return Xt([t],e)}function Gt(t,e){return J(t,"")?["",e]:t.startsWith(wi)?am(t,Eu(e)):t.startsWith(cS)?am(t,e):am(t,jt(e))}var gM=[...dS,ho,fS];var Wee=[...gM,...go];var Zee=[...go,ho];function hM(t){return J(t,"")?[]:[t.slice(0,1),t.slice(1)]}function SS(t,e){return La(t,(r,n)=>e.startsWith(r)?!0:SS(n,e),()=>!1)}function vi(t,e,r=""){return It(hM(e),(n,o)=>SS(t,e)?[r,e]:vi(t,o,`${r}${n}`),()=>[])}function IS(t,e){return It(vi(t,e),(r,n)=>J(r,"")?[]:[r,n],()=>[])}var X=(t,e,r=()=>[])=>t.length===2?e(t):r();var kM=t=>X(Gt("-?(?:0|[1-9][0-9]*)n",t),([e,r])=>[eS(e),r]),SM=t=>X(Gt(".*",t),([e,r])=>[tS(e),r]),IM=t=>X(Gt("-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?",t),([e,r])=>[rS(e),r]),xM=t=>X(Gt("-?(?:0|[1-9][0-9]*)",t),([e,r])=>[nS(e),r]),PM=t=>X(Gt("(?!)",t),([e,r])=>[oS(e),r]),wM=t=>X(IS(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],t),([e,r])=>[iS(e),r]),vM=t=>X(X(kM(t),([e,r])=>[e,r],()=>X(SM(t),([e,r])=>[e,r],()=>X(IM(t),([e,r])=>[e,r],()=>X(xM(t),([e,r])=>[e,r],()=>X(PM(t),([e,r])=>[e,r],()=>X(bM(t),([e,r])=>[e,r],()=>X(wM(t),([e,r])=>[e,r],()=>[]))))))),([e,r])=>[e,r]),bM=t=>X(X(Gt("(",t),([e,r])=>X(pm(r),([n,o])=>X(Gt(")",o),([i,a])=>[[e,n,i],a]))),([e,r])=>[sS(e),r]),xS=t=>X(X(X(um(t),([e,r])=>X(Gt("|",r),([n,o])=>X(xS(o),([i,a])=>[[e,n,i],a]))),([e,r])=>[e,r],()=>X(X(um(t),([e,r])=>[[e],r]),([e,r])=>[e,r],()=>X([[],t],([e,r])=>[e,r],()=>[]))),([e,r])=>[aS(e),r]),um=t=>X(X(vM(t),([e,r])=>X(pm(r),([n,o])=>[[e,n],o])),([e,r])=>[uS(e),r]),pm=t=>X(X(xS(t),([e,r])=>[e,r],()=>X(um(t),([e,r])=>[e,r],()=>[])),([e,r])=>[e,r]),bk=t=>X(X(Gt("^",t),([e,r])=>X(pm(r),([n,o])=>X(Gt("$",o),([i,a])=>[[e,n,i],a]))),([e,r])=>[pS(e),r]);function TM(t){return t.join("|")}function RM(t){return t.slice(1,t.length-1)}function CM(t,e,r){return Ur(e,`${r}${t}`)}function EM(t,e){return Ur(t,`${e}${Ik}`)}function $M(t,e){return Ur(t,`${e}${ku}`)}function MM(t,e){return Ur(t,`${e}${Pu}`)}function OM(t,e){return $u(B([Z("false"),Z("true")]),t,e)}function _M(t,e){return Ur(t,`${e}${wu}`)}function DM(t,e,r){return Ur(e,`${r}${RM(t)}`)}function LM(t,e,r){let n=Mu(t,{});return $u(n,e,r)}function FM(t,e,r){let n=Ut(t);return dm(n,e,r)}function dm(t,e,r,n=[]){return s.TakeLeft(t,(o,i)=>dm(i,e,r,[...n,$u(o,[],"")]),()=>Ur(e,`${r}(${TM(n)})`))}function $u(t,e,r){return qe(t)?FM(t.enum,e,r):at(t)?$M(e,r):G(t)?CM(t.const,e,r):Bt(t)?EM(e,r):At(t)?OM(e,r):Ae(t)?MM(e,r):Xe(t)?_M(e,r):Te(t)?DM(t.pattern,e,r):wS(t)?LM(t.parameters[0],e,r):b(t)?dm(t.anyOf,e,r):ck}function Ur(t,e){return s.TakeLeft(t,(r,n)=>$u(r,n,e),()=>e)}function NM(t){return`^${Ur(t,"")}$`}function PS(t){let e=NM(t);return bu(e)}function Mu(t,e){return L(t)?g.Update(PS(t),{},e):Ll(t,e)}function vS(t,e,r,n){let o=Rt(t,e,r);return Mu(o,n)}function Ll(t,e={}){return E("TemplateLiteral",[t],e)}function wS(t){return le(t)&&s.HasPropertyKey(t,"action")&&s.IsEqual(t.action,"TemplateLiteral")}function Te(t){return v(t,"TemplateLiteral")}var F={};Ct(F,{ExtendsFalse:()=>W,ExtendsTrue:()=>A,ExtendsUnion:()=>lm,IsExtendsFalse:()=>qM,IsExtendsTrue:()=>AS,IsExtendsTrueLike:()=>yo,IsExtendsUnion:()=>bS,Match:()=>Oe});function lm(t){return g.Create({"~kind":"ExtendsUnion"},{inferred:t})}function bS(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"inferred")&&s.IsEqual(t["~kind"],"ExtendsUnion")&&s.IsObject(t.inferred)}function A(t){return g.Create({"~kind":"ExtendsTrue"},{inferred:t})}function AS(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"inferred")&&s.IsEqual(t["~kind"],"ExtendsTrue")&&s.IsObject(t.inferred)}function W(){return g.Create({"~kind":"ExtendsFalse"},{})}function qM(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.IsEqual(t["~kind"],"ExtendsFalse")}function yo(t){return bS(t)||AS(t)}function Oe(t,e,r){return yo(t)?e(t.inferred):r()}function BM(t,e,r,n){return Oe(re(t,r,n),o=>A(g.Assign(g.Assign(t,o),{[e]:r})),()=>W())}function WM(t,e){return A(t)}function UM(t,e,r){let n=ki(r);return re(t,e,n)}function TS(t,e,r){return s.TakeLeft(r,(n,o)=>Oe(re(t,e,n),i=>TS(i,e,o),()=>W()),()=>A(t))}function KM(t,e,r){let n=He(r);return re(t,e,n)}function RS(t,e,r){return s.TakeLeft(r,(n,o)=>Oe(re(t,e,n),i=>A(i),()=>RS(t,e,o)),()=>W())}function U(t,e,r){return Ve(r)?WM(t,e):qe(r)?UM(t,e,r.enum):$e(r)?BM(t,r.name,e,r.extends):D(r)?TS(t,e,r.allOf):Te(r)?KM(t,e,r.pattern):b(r)?RS(t,e,r.anyOf):Ze(r)?A(t):W()}function CS(t,e,r){return $e(r)?U(t,e,r):Ve(r)?A(t):Ze(r)?A(t):lm(t)}function jM(t,e){let r=fi(t),n=fi(e);return r&&n||!r&&n?!0:!(r&&!n)}function ES(t,e,r,n){return te(n)?jM(e,n)?re(t,r,n.items):W():U(t,e,n)}function $S(t,e,r){return st(r)?re(t,e,r.iteratorItems):U(t,mr(e),r)}function MS(t,e,r){return Bt(r)?A(t):U(t,e,r)}function OS(t,e,r){return At(r)?A(t):U(t,e,r)}function GM(t,e,r,n,o){let i=$e(n)?e:n,a=$e(n)?n:e,u=Ue(e),p=Ue(n);return!u&&p?W():Oe(re(t,i,a),d=>bi(d,r,o),()=>W())}function VM(t,e,r,n){return s.TakeLeft(n,(o,i)=>GM(t,e,r,o,i),()=>Ue(e)?A(t):W())}function HM(t,e,r){return s.TakeLeft(e,(n,o)=>VM(t,n,o,r),()=>A(t))}function bi(t,e,r){return HM(t,e,r)}function Ou(t,e,r){return Kt(r)?A(t):re(t,e,r)}function _S(t,e,r,n){return Ve(n)?A(t):Ze(n)?A(t):Fe(n)?Oe(bi(t,e,n.parameters),o=>Ou(o,r,n.instanceType),()=>W()):W()}function DS(t,e,r){return re(t,mo(e),r)}function LS(t,e,r,n){return Ve(n)?A(t):Ze(n)?A(t):Ne(n)?Oe(bi(t,e,n.parameters),o=>Ou(o,r,n.returnType),()=>W()):W()}function FS(t,e,r){return at(r)?A(t):Ae(r)?A(t):U(t,e,r)}function NS(t,e,r){let n=Se(e);return re(t,n,r)}function qS(t,e,r){return ut(r)?re(t,e,r.iteratorItems):U(t,cr(e),r)}function _u(t,e,r){return e===r?A(t):W()}function zM(t,e,r){return G(r)?_u(t,e,r.const):Bt(r)?A(t):U(t,Z(e),r)}function JM(t,e,r){return G(r)?_u(t,e,r.const):At(r)?A(t):U(t,Z(e),r)}function QM(t,e,r){return G(r)?_u(t,e,r.const):Ae(r)?A(t):U(t,Z(e),r)}function YM(t,e,r){return G(r)?_u(t,e,r.const):Xe(r)?A(t):U(t,Z(e),r)}function BS(t,e,r){return s.IsBigInt(e.const)?zM(t,e.const,r):s.IsBoolean(e.const)?JM(t,e.const,r):s.IsNumber(e.const)?QM(t,e.const,r):s.IsString(e.const)?YM(t,e.const,r):Y()}function WS(t,e,r){return $e(r)?U(t,e,r):A(t)}function US(t,e,r){return wn(r)?A(t):U(t,e,r)}function KS(t,e,r){return Ae(r)?A(t):U(t,e,r)}function ZM(t,e,r){return Ue(e)?Ue(r)?A(t):W():A(t)}function XM(t,e,r){return $e(r)&&Nr(r.extends)?W():Oe(re(t,e,r),n=>ZM(n,e,r),()=>W())}function eO(t,e){return t.reduce((r,n)=>n in e?yo(e[n])?{...r,...e[n].inferred}:Y():Y(),{})}function tO(t,e,r){let n={};for(let a of s.Keys(r))n[a]=a in e?XM({},e[a],r[a]):Ue(r[a])?$e(r[a])?A(g.Assign(t,{[r[a].name]:r[a].extends})):A(t):W();let o=s.Values(n).every(a=>yo(a)),i=o?eO(s.Keys(n),n):{};return o?A(i):W()}function rO(t,e,r){let n=tO(t,e,r);return yo(n)?A(g.Assign(t,n.inferred)):W()}function nO(t,e,r){return rO(t,e,r)}function jS(t,e,r){return N(r)?nO(t,e,r.properties):U(t,O(e),r)}function GS(t,e,r){return Ge(r)?re(t,e,r.item):U(t,dr(e),r)}function VS(t,e,r){return Xe(r)?A(t):U(t,e,r)}function HS(t,e,r){return lo(r)?A(t):U(t,e,r)}function zS(t,e,r){let n=He(e);return re(t,n,r)}function mm(t,e){return g.Create({"~kind":"Inferrable"},{name:t,type:e},{})}function Ai(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"name")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"Inferrable")&&s.IsString(t.name)&&s.IsObject(t.type)}function cm(t){return fo(t)?$e(t.items)?te(t.items.extends)?mm(t.items.name,t.items.extends.items):Ze(t.items.extends)?mm(t.items.name,t.items.extends):void 0:Y():void 0}function Du(t){return $e(t)?mm(t.name,t.extends):void 0}function fm(t,e,r=[]){return s.TakeLeft(t,(n,o)=>Oe(re({},n,e),()=>fm(o,e,[...r,n]),()=>{}),()=>r)}function JS(t,e,r,n){let o=fm(r,n);return s.IsArray(o)?A(g.Assign(t,{[e]:Ke(o)})):W()}function Lu(t,e,r,n){let o=fm(r,n);return s.IsArray(o)?A(g.Assign(t,{[e]:B(o)})):W()}function oO(t){return[...t].reverse()}function gm(t,e){return e?oO(t):t}function iO(t){let e=t.length>0?t[0]:void 0,r=le(e)?cm(e):void 0;return le(r)}function sO(t,e,r,n,o,i){return Oe(re(t,r,o),a=>QS(a,e,n,i),()=>W())}function aO(t,e,r,n,o){let i=cm(n);return Ai(i)?JS(t,i.name,gm(r,e),i.type):s.TakeLeft(r,(a,u)=>sO(t,e,a,u,n,o),()=>W())}function uO(t,e,r,n){return s.TakeLeft(n,(o,i)=>aO(t,e,r,o,i),()=>s.IsEqual(r.length,0)?A(t):W())}function QS(t,e,r,n){return uO(t,e,r,n)}function pO(t,e,r){let n=Kr(t,{callstack:[]},r),o=iO(n);return QS(t,o,gm(e,o),gm(n,o))}function YS(t,e,r){let n=Du(r);return Ai(n)?Lu(t,n.name,e,n.type):s.TakeLeft(e,(o,i)=>Oe(re(t,o,r),a=>YS(a,i,r),()=>W()),()=>A(t))}function ZS(t,e,r){let n=Kr(t,{callstack:[]},e);return V(r)?pO(t,n,r.items):te(r)?YS(t,n,r.items):U(t,Ke(n),r)}function XS(t,e,r){return Kt(r)?A(t):Tn(r)?A(t):U(t,e,r)}function eI(t,e,r){return s.TakeLeft(r,(n,o)=>Oe(re(t,e,n),i=>A(i),()=>eI(t,e,o)),()=>W())}function hm(t,e,r){return s.TakeLeft(e,(n,o)=>Oe(eI(t,n,r),i=>hm(i,o,r),()=>W()),()=>A(t))}function tI(t,e,r){let n=Du(r);return Ai(n)?Lu(t,n.name,e,n.type):b(r)?hm(t,e,r.anyOf):hm(t,e,[r])}function rI(t,e,r){return $e(r)?U(t,e,r):Ve(r)?A(t):Ze(r)?A(t):W()}function nI(t,e,r){return Kt(r)?A(t):U(t,e,r)}function re(t,e,r){return Ve(e)?CS(t,e,r):te(e)?ES(t,e,e.items,r):st(e)?$S(t,e.iteratorItems,r):Bt(e)?MS(t,e,r):At(e)?OS(t,e,r):Fe(e)?_S(t,e.parameters,e.instanceType,r):qe(e)?DS(t,e,r):Ne(e)?LS(t,e.parameters,e.returnType,r):at(e)?FS(t,e,r):D(e)?NS(t,e.allOf,r):ut(e)?qS(t,e.iteratorItems,r):G(e)?BS(t,e,r):Nr(e)?WS(t,e,r):wn(e)?US(t,e,r):Ae(e)?KS(t,e,r):N(e)?jS(t,e.properties,r):Ge(e)?GS(t,e.item,r):Xe(e)?VS(t,e,r):lo(e)?HS(t,e,r):Te(e)?zS(t,e.pattern,r):V(e)?ZS(t,e.items,r):Tn(e)?XS(t,e,r):b(e)?tI(t,e.anyOf,r):Ze(e)?rI(t,e,r):Kt(e)?nI(t,e,r):W()}function dO(t,e){return Se([...t,O(e)])}function oI(t,e,r){return L(t)?g.Update(dO(t,e),{},r):Fl(t,e,r)}function iI(t,e,r,n,o){let i=Rt(t,e,r),a=Ti(t,e,n);return oI(i,a,o)}function Fl(t,e,r={}){return E("Interface",[t,e],r)}function ko(t){return le(t)&&s.HasPropertyKey(t,"action")&&s.IsEqual(t.action,"Interface")}function lO(t,e,r){return t.includes(r)?!0:jr([...t,r],e,e[r])}function sI(t,e,r){let n=yu(r);return Rn(t,e,n)}function Rn(t,e,r){return s.TakeLeft(r,(n,o)=>jr(t,e,n)?!0:Rn(t,e,o),()=>!1)}function jr(t,e,r){return se(r)?lO(t,e,r.$ref):te(r)?jr(t,e,r.items):st(r)?jr(t,e,r.iteratorItems):Fe(r)?Rn(t,e,[...r.parameters,r.instanceType]):Ne(r)?Rn(t,e,[...r.parameters,r.returnType]):ko(r)?sI(t,e,r.parameters[1]):D(r)?Rn(t,e,r.allOf):ut(r)?jr(t,e,r.iteratorItems):N(r)?sI(t,e,r.properties):Ge(r)?jr(t,e,r.item):b(r)?Rn(t,e,r.anyOf):V(r)?Rn(t,e,r.items):Me(r)?jr(t,e,et(r)):!1}function Fu(t,e,r){return jr(t,e,r)}function mO(t,e){return e.reduce((r,n)=>n in t?Fu([n],t,t[n])?[...r,n]:r:Y(),[])}function aI(t){let e=hu(t);return mO(t,e)}function cO(t,e,r){return r.includes(e)?r:e in t?Gr(t,t[e],[...r,e]):Y()}function uI(t,e,r){let n=yu(e);return So(t,n,r)}function So(t,e,r){return e.reduce((n,o)=>Gr(t,o,n),r)}function Gr(t,e,r){return se(e)?cO(t,e.$ref,r):te(e)?Gr(t,e.items,r):st(e)?Gr(t,e.iteratorItems,r):Fe(e)?So(t,[...e.parameters,e.instanceType],r):Ne(e)?So(t,[...e.parameters,e.returnType],r):ko(e)?uI(t,e.parameters[1],r):D(e)?So(t,e.allOf,r):ut(e)?Gr(t,e.iteratorItems,r):N(e)?uI(t,e.properties,r):Ge(e)?Gr(t,e.item,r):b(e)?So(t,e.anyOf,r):V(e)?So(t,e.items,r):Me(e)?Gr(t,et(e),r):r}function pI(t,e,r){return Gr(t,r,[e])}function fO(t){return vl()}function gO(t){return s.Keys(t).reduce((e,r)=>({...e,[r]:er(t[r])}),{})}function Ri(t){return t.reduce((e,r)=>[...e,er(r)],[])}function er(t){return se(t)?fO(t.$ref):te(t)?lr(er(t.items),fu(t)):st(t)?mr(er(t.iteratorItems)):Fe(t)?xn(Ri(t.parameters),er(t.instanceType)):Ne(t)?Pn(Ri(t.parameters),er(t.returnType)):D(t)?qt(Ri(t.allOf)):ut(t)?cr(er(t.iteratorItems)):N(t)?O(gO(t.properties)):Ge(t)?dr(er(t.item)):Me(t)?Yk(Tu(t),er(et(t))):b(t)?B(Ri(t.anyOf)):V(t)?Ke(Ri(t.items)):t}function hO(t,e){return e in t?er(t[e]):Yt()}function dI(t){return hO(t.$defs,t.$ref)}function yO(t,e,r){let n=Rt(t,{callstack:[]},e),o=Ti({},{callstack:[]},r);return Se([...n,O(o)])}function kO(t,e){return s.Keys(t).filter(n=>e.includes(n)).reduce((n,o)=>{let i=t[o],a=ko(i)?yO(t,i.parameters[0],i.parameters[1]):i;return{...n,[o]:a}},{})}function lI(t,e,r){let n=pI(t,e,r),o=kO(t,n);return qr(o,e)}function mI(t,e){return e in t?se(t[e])?mI(t,t[e].$ref):t[e]:oe()}function tr(t,e){return mI(t,e)}function cI(t){return he(t)?dI(t):yk(t)?Yt():t}function pt(t,e,r){let n=cI(e),o=cI(r);return re(t,n,o)}var Si="equal",SO="disjoint",Ii="left-inside",xi="right-inside";function vn(t,e){let r=[Ze(t)?F.ExtendsFalse():pt({},t,e),Ze(t)?F.ExtendsTrue({}):pt({},e,t)];return F.IsExtendsTrueLike(r[0])&&F.IsExtendsTrueLike(r[1])?Si:F.IsExtendsTrueLike(r[0])&&F.IsExtendsFalse(r[1])?Ii:F.IsExtendsFalse(r[0])&&F.IsExtendsTrueLike(r[1])?xi:SO}function IO(t,e){return e.filter(r=>vn(t,r)!==xi)}function xO(t,e){let r=e.some(n=>{let o=vn(t,n);return s.IsEqual(o,Ii)||s.IsEqual(o,Si)});return s.IsEqual(r,!1)}function PO(t,e){let r=bn(t);return Ve(r)?[r]:xO(r,e)?[...IO(r,e),r]:e}function wO(t){return t.reduce((e,r)=>N(r)?[...e,r]:Nr(r)?e:PO(r,e),[])}function $l(t){let e=wO(t),r=Zt(e);return r.length===0?oe():r.length===1?r[0]:B(r)}function ym(t,e){return g.Update(bn(t),{},e)}function fI(t,e,r,n){let o=P(t,e,r);return ym(o,n)}function Ci(t,e=[]){return Fr(t)&&s.IsEqual(t.action,"Conditional")?se(t.parameters[0])?Ci(t.parameters[2],Ci(t.parameters[3],[...e,t.parameters[0].$ref])):Ci(t.parameters[2],Ci(t.parameters[3],e)):Fr(t)&&s.IsEqual(t.action,"Mapped")&&Fr(t.parameters[1])&&s.IsEqual(t.parameters[1].action,"KeyOf")&&se(t.parameters[1].parameters[0])?[...e,t.parameters[1].parameters[0].$ref]:e}function vO(t,e){return t.reduce((r,n)=>[...r,e.includes(n.name)],[])}function yI(t,e,r=[]){return s.TakeLeft(t,(n,o)=>s.TakeLeft(e,(i,a)=>yI(o,a,[...r,[i,n]]),()=>r),()=>r)}function bO(t){return b(t)?[...t.anyOf]:[t]}function AO(t,e){return t.reduce((r,n)=>[...r,[...n,e]],[])}function gI(t,e){return e.reduce((r,n)=>[...r,...AO(t,n)],[])}function hI(t){return t.reduce((e,r)=>s.IsEqual(r[0],!0)?gI(e,bO(r[1])):gI(e,[r[1]]),[[]])}function kI(t,e,r){let n=Ci(r),o=vO(t,n),i=yI(e,o);return Fr(r)&&s.IsEqual(r.action,"Conditional")||Fr(r)&&s.IsEqual(r.action,"Mapped")?hI(i):[e]}function TO(){return["(not-resolvable)",oe()]}function RO(){return["(not-generic)",oe()]}function CO(t,e,r){return[t,wl(e,r)]}function EO(t,e,r){return e in t?SI(t,e,t[e],r):TO()}function SI(t,e,r,n){return gu(r)?CO(e,r.parameters,r.expression):se(r)?EO(t,r.$ref,n):RO()}function II(t,e,r){return SI(t,"(anonymous)",e,r)}function $O(t,e,r){if($e(e)||Nu(e)||F.IsExtendsTrueLike(pt({},e,r)))return;let n={parameter:t,expect:r,actual:e};throw new Error(`Argument for parameter ${t} does not satisfy constraint`,{cause:n})}function xI(t,e,r,n,o){let i=P(t,e,o);return $O(r,i,n),g.Assign(t,{[r]:i})}function MO(t,e,r,n,o){let i=P(t,e,r.extends),a=P(t,e,r.equals);return s.TakeLeft(o,(u,p)=>km(xI(t,e,r.name,i,u),e,n,p),()=>km(xI(t,e,r.name,i,a),e,n,[]))}function km(t,e,r,n){return s.TakeLeft(r,(o,i)=>MO(t,e,o,i,n),()=>t)}function PI(t,e,r,n){return km(t,e,r,n)}function OO(t){return s.IsGreaterThan(t.callstack.length,0)?t.callstack[t.callstack.length-1]:""}function _O(t,e){return s.IsEqual(OO(t),e)}function DO(t,e,r,n,o,i){let a=PI(t,e,n,i),u=P(a,{callstack:[...e.callstack,r.$ref]},o);return P(t,e,u)}function LO(t,e,r,n,o,i){return i.reduce((a,u)=>[...a,DO(t,e,r,n,o,u)],[])}function FO(t,e,r,n,o,i){let a=kI(n,i,o),u=LO(t,e,r,n,o,a);return s.IsEqual(u.length,1)?u[0]:Ot(u)}function Sm(t,e,r,n){let o=Rt(t,e,n),i=II(t,r,n),a=i[0],u=i[1];return gu(u)?_O(e,a)?Ru(St(a),o):FO(t,e,St(a),u.parameters,u.expression,o):Ru(r,o)}function Ru(t,e){return g.Create({"~kind":"Call"},{target:t,arguments:e},{})}function Nu(t){return v(t,"Call")}function wI(t,e){return t(e)}function vI(t,e){return s.IsString(e)?Z(wI(t,e)):Z(e)}function bI(t,e){let r=He(e);return fr(t,r)}function AI(t,e){let r=e.map(n=>fr(t,n));return B(r)}function fr(t,e){return G(e)?vI(t,e.const):Te(e)?bI(t,e.pattern):b(e)?AI(t,e.anyOf):e}function Nl(t,e={}){return E("Capitalize",[t],e)}function ql(t,e={}){return E("Lowercase",[t],e)}function Bl(t,e={}){return E("Uncapitalize",[t],e)}function Wl(t,e={}){return E("Uppercase",[t],e)}var NO=t=>t[0].toUpperCase()+t.slice(1),qO=t=>t.toLowerCase(),BO=t=>t[0].toLowerCase()+t.slice(1),WO=t=>t.toUpperCase();function TI(t,e){return L([t])?g.Update(fr(NO,t),{},e):Nl(t,e)}function RI(t,e){return L([t])?g.Update(fr(qO,t),{},e):ql(t,e)}function CI(t,e){return L([t])?g.Update(fr(BO,t),{},e):Bl(t,e)}function EI(t,e){return L([t])?g.Update(fr(WO,t),{},e):Wl(t,e)}function $I(t,e,r,n){let o=P(t,e,r);return TI(o,n)}function MI(t,e,r,n){let o=P(t,e,r);return RI(o,n)}function OI(t,e,r,n){let o=P(t,e,r);return CI(o,n)}function _I(t,e,r,n){let o=P(t,e,r);return EI(o,n)}function Ul(t,e,r,n,o={}){return E("Conditional",[t,e,r,n],o)}function UO(t,e,r,n,o,i){let a=pt(t,r,n);return F.IsExtendsUnion(a)?B([P(a.inferred,e,o),P(t,e,i)]):F.IsExtendsTrue(a)?P(a.inferred,e,o):P(t,e,i)}function DI(t,e,r,n,o,i,a){return L([r,n])?g.Update(UO(t,e,r,n,o,i),{},a):Ul(r,n,o,i,a)}function LI(t,e,r,n,o,i,a){let u=P(t,e,r),p=P(t,e,n);return DI(t,e,u,p,o,i,a)}function Kl(t,e={}){return E("ConstructorParameters",[t],e)}function KO(t){let e=Fe(t)?t.parameters:[],r=Kr({},{callstack:[]},e);return Ke(r)}function FI(t,e){return L([t])?g.Update(KO(t),{},e):Kl(t,e)}function NI(t,e,r,n){let o=P(t,e,r);return FI(o,n)}function jl(t,e,r={}){return E("Exclude",[t,e],r)}function qI(t,e){return t.reduce((r,n)=>[...r,...BI(n,e)],[])}function BI(t,e){let r=pt({},t,e);return F.IsExtendsTrueLike(r)?[]:[t]}function WI(t,e){let r=qe(t)?qI(Ut(t.enum),e):b(t)?qI(Zt(t.anyOf),e):BI(t,e);return Ot(r)}function qu(t,e,r){return L([t,e])?g.Update(WI(t,e),{},r):jl(t,e,r)}function UI(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return qu(i,a,o)}function Gl(t,e,r={}){return E("Extract",[t,e],r)}function jI(t,e){return t.reduce((r,n)=>[...r,...GI(n,e)],[])}function GI(t,e){let r=pt({},t,e);return F.IsExtendsTrueLike(r)?[t]:[]}function VI(t,e){let r=qe(t)?jI(Ut(t.enum),e):b(t)?jI(Zt(t.anyOf),e):GI(t,e);return Ot(r)}function KI(t,e,r){return L([t,e])?g.Update(VI(t,e),{},r):Gl(t,e,r)}function HI(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return KI(i,a,o)}function Vl(t,e,r={}){return E("Index",[t,e],r)}function QI(t,e){let r=tr(t,e);return Vt(r)}function jO(t,e){let r=s.Keys(t).filter(l=>!s.HasPropertyKey(e,l)),n=s.Keys(e).filter(l=>!s.HasPropertyKey(t,l)),o=s.Keys(t).filter(l=>s.HasPropertyKey(e,l)),i=r.reduce((l,m)=>({...l,[m]:t[m]}),{}),a=n.reduce((l,m)=>({...l,[m]:e[m]}),{}),u=o.reduce((l,m)=>({...l,[m]:Se([t[m],e[m]])}),{}),p=g.Assign(i,a);return g.Assign(p,u)}function YI(t){return t.reduce((e,r)=>jO(e,Vt(r)),{})}function ZI(t){let e=Fk(Ke(t));return Vt(e)}function GO(t,e){return s.Keys(t).filter(o=>o in e).reduce((o,i)=>({...o,[i]:Ot([t[i],e[i]])}),{})}function XI(t,e){return s.TakeLeft(t,(r,n)=>XI(n,GO(e,Vt(r))),()=>e)}function ex(t){return s.TakeLeft(t,(e,r)=>XI(r,Vt(e)),()=>Y())}function Vt(t){return he(t)?QI(t.$defs,t.$ref):D(t)?YI(t.allOf):b(t)?ex(t.anyOf):V(t)?ZI(t.items):N(t)?t.properties:{}}function Io(t){let e=Vt(t);return O(e)}var VO=new RegExp("^(?:0|[1-9][0-9]*)$");function xo(t){let e=`${t}`;return VO.test(e)?parseInt(e):t}function HO(t){return Z(xo(t))}function tx(t){return t.map(e=>rx(e))}function rx(t){return D(t)?qt(tx(t.allOf)):b(t)?B(tx(t.anyOf)):G(t)?HO(t.const):t}function nx(t,e){let r=rx(e),n=pt({},r,Wt());return F.IsExtendsTrueLike(n)?t:G(e)&&s.IsEqual(e.const,"length")?Wt():oe()}function ox(t,e){let r=tr(t,e);return rr(r)}function Bu(t){return t.reduce((e,r)=>[...e,...rr(r)],[])}function ix(t){let e=Ut(t);return Bu(e)}function sx(t){let e=Se(t);return rr(e)}function ax(t){return[`${t}`]}function ux(t){let e=He(t);return rr(e)}function rr(t){return he(t)?ox(t.$defs,t.$ref):qe(t)?ix(t.enum):D(t)?sx(t.allOf):G(t)?ax(t.const):Te(t)?ux(t.pattern):b(t)?Bu(t.anyOf):[]}function Po(t){return rr(t)}function Ei(t,e){return e.map(r=>Vr(t,r))}function Vr(t,e){return te(e)?lr(Vr(t,e.items)):st(e)?mr(Vr(t,e.iteratorItems)):Fe(e)?xn(Ei(t,e.parameters),Vr(t,e.instanceType)):Ne(e)?Pn(Ei(t,e.parameters),Vr(t,e.returnType)):ut(e)?cr(Vr(t,e.iteratorItems)):Ge(e)?dr(Vr(t,e.item)):V(e)?Ke(Ei(t,e.items)):b(e)?B(Ei(t,e.anyOf)):D(e)?qt(Ei(t,e.allOf)):Xk(e)?O(t):e}function px(t,e){return Vr(t,e)}function zO(t,e){let r=e in t?t[e]:oe();return px(t,r)}function dx(t,e){return e.reduce((r,n)=>[...r,zO(t,n)],[])}function JO(t,e){let r=Po(e),n=dx(t,r);return Ot(n)}var QO=new RegExp(co);function YO(t){return t.filter(r=>QO.test(r))}function ZO(t){let e=hu(t),r=YO(e),n=dx(t,r);return Ot(n)}function lx(t,e){return Ae(e)?ZO(t):JO(t,e)}function XO(t){return Z(xo(t))}function mx(t){return t.map(e=>Im(e))}function Im(t){return D(t)?qt(mx(t.allOf)):b(t)?B(mx(t.anyOf)):G(t)?XO(t.const):t}function e_(t,e){return t.reduceRight((r,n,o)=>{let i=pt({},Z(o),e);return F.IsExtendsTrueLike(i)?[n,...r]:r},[])}function t_(t,e){let r=Im(e),n=e_(t,r);return An(n)}function r_(t){return An(t)}function cx(t,e){return G(e)&&s.IsEqual(e.const,"length")?Z(t.length):Ae(e)||at(e)?r_(t):t_(t,e)}function fx(t,e){return te(t)?nx(t.items,e):N(t)?lx(t.properties,e):V(t)?cx(t.items,e):oe()}function n_(t){return he(t)||D(t)||b(t)?Io(t):t}function JI(t,e,r){return L([t,e])?g.Update(fx(n_(t),e),{},r):Vl(t,e,r)}function gx(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return JI(i,a,o)}function Hl(t,e={}){return E("InstanceType",[t],e)}function o_(t){return Fe(t)?t.instanceType:oe()}function hx(t,e){return L([t])?g.Update(o_(t),{},e):Hl(t,e)}function yx(t,e,r,n={}){let o=P(t,e,r);return hx(o,n)}function zl(t,e={}){return E("KeyOf",[t],e)}function Sx(){return B([Wt(),Tt(),Rl()])}function Ix(t){return Wt()}function i_(t){return t.reduce((r,n)=>Tl(n)?[...r,Z(xo(n))]:Y(),[])}function xx(t){let e=s.Keys(t),r=i_(e);return An(r)}function Px(t){return Tu(t)}function wx(t){let e=t.map((r,n)=>Z(n));return An(e)}function vx(t){return Ve(t)?Sx():te(t)?Ix(t.items):N(t)?xx(t.properties):Me(t)?Px(t):V(t)?wx(t.items):oe()}function s_(t){return he(t)||D(t)||b(t)?Io(t):t}function kx(t,e){return L([t])?g.Update(vx(s_(t)),{},e):zl(t,e)}function bx(t,e,r,n){let o=P(t,e,r);return kx(o,n)}function Jl(t,e,r,n,o={}){return E("Mapped",[t,e,r,n],o)}function a_(t){let e=He(t);return xm(e)}function Tx(t){return t.reduce((e,r)=>[...e,...xm(r)],[])}function u_(t){return s.IsNumber(t)?[Z(`${t}`)]:[Z(t)]}function xm(t){return qe(t)?Tx(Ut(t.enum)):G(t)?u_(t.const):Te(t)?a_(t.pattern):b(t)?Tx(t.anyOf):[t]}function Rx(t){return xm(t)}function p_(t){return Te(t)?He(t.pattern):t}function d_(t,e,r,n,o,i){let a=g.Assign(t,{[r.name]:n}),u=P(a,e,o),p=p_(u),d=P(a,e,i);return Iu(p)||xu(p)?{[p.const]:d}:{}}function l_(t,e,r,n,o,i){return n.reduce((a,u)=>[...a,d_(t,e,r,u,o,i)],[])}function m_(t){return t.reduce((e,r)=>[...e,O(r)],[])}function Cx(t,e,r,n,o,i){let a=Rx(n),u=l_(t,e,r,a,o,i),p=m_(u);return Se(p)}function Ax(t,e,r,n,o,i,a){return L([n])?g.Update(Cx(t,e,r,n,o,i),{},a):Jl(r,n,o,i,a)}function Ex(t,e,r,n,o,i,a){let u=P(t,e,n);return Ax(t,e,r,u,o,i,a)}function c_(t,e){return s.Keys(t).filter(n=>e.includes(n)).reduce((n,o)=>({...n,[o]:lI(t,o,t[o])}),{})}function f_(t,e){return s.Keys(t).filter(n=>!e.includes(n)).reduce((n,o)=>({...n,[o]:P(t,{callstack:[]},t[o])}),{})}function g_(t,e){let r=aI(t),n=c_(t,r),o=f_(t,r),i={...n,...o};return g.Update(i,{},e)}function $x(t,e,r,n){let o=g.Assign(t,r);return g_(o,n)}function Ql(t,e={}){return E("NonNullable",[t],e)}function h_(t){let e=B([hi(),Dl()]);return qu(t,e,{})}function Mx(t,e){return L([t])?g.Update(h_(t),{},e):Ql(t,e)}function Ox(t,e,r,n){let o=P(t,e,r);return Mx(o,n)}function Yl(t,e,r={}){return E("Omit",[t,e],r)}function Wu(t){let e=Io(t);return N(e)?e.properties:Y()}function y_(t,e){return s.Keys(t).reduce((n,o)=>e.includes(o)?n:{...n,[o]:t[o]},{})}function Dx(t,e){let r=Wu(t),n=Po(e),o=y_(r,n);return O(o)}function _x(t,e,r){return L([t,e])?g.Update(Dx(t,e),{},r):Yl(t,e,r)}function Lx(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return _x(i,a,o)}function Zl(t,e){return E("Options",[t,e],{})}function Fx(t,e){return Pm(t,e)}function Pm(t,e){return L([t])?g.Update(t,{},e):Zl(t,e)}function Nx(t,e,r,n){let o=P(t,e,r);return Pm(o,n)}function Xl(t,e={}){return E("Parameters",[t],e)}function k_(t){let e=Ne(t)?t.parameters:[],r=Kr({},{callstack:[]},e);return Ke(r)}function qx(t,e){return L([t])?g.Update(k_(t),{},e):Xl(t,e)}function Bx(t,e,r,n){let o=P(t,e,r);return qx(o,n)}function em(t,e={}){return E("Partial",[t],e)}function Ux(t,e){let r=tr(t,e),n=Hr(r);return qr(g.Assign(t,{[e]:n}),e)}function Kx(t){let e=t.map(r=>Hr(r));return Se(e)}function jx(t){let e=t.map(r=>Hr(r));return B(e)}function Gx(t){let e=s.Keys(t).reduce((n,o)=>({...n,[o]:uk(t[o])}),{});return O(e)}function Hr(t){return he(t)?Ux(t.$defs,t.$ref):D(t)?Kx(t.allOf):b(t)?jx(t.anyOf):N(t)?Gx(t.properties):O({})}function Wx(t,e){return L([t])?g.Update(Hr(t),{},e):em(t,e)}function Vx(t,e,r,n){let o=P(t,e,r);return Wx(o,n)}function tm(t,e,r={}){return E("Pick",[t,e],r)}function S_(t,e){return s.Keys(t).reduce((n,o)=>e.includes(o)?g.Assign(n,{[o]:t[o]}):n,{})}function zx(t,e){let r=Wu(t),n=Po(e),o=S_(r,n);return O(o)}function Hx(t,e,r){return L([t,e])?g.Update(zx(t,e),{},r):tm(t,e,r)}function Jx(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return Hx(i,a,o)}function rm(t,e={}){return E("ReadonlyObject",[t],e)}function Yx(t){return uo(lr(t))}function Zx(t,e){let r=tr(t,e),n=zr(r);return qr(g.Assign(t,{[e]:n}),e)}function Xx(t){let e=t.map(r=>zr(r));return Se(e)}function eP(t){let e=s.Keys(t).reduce((n,o)=>({...n,[o]:pk(t[o])}),{});return O(e)}function tP(t){return uo(Ke(t))}function rP(t){let e=t.map(r=>zr(r));return B(e)}function zr(t){return te(t)?Yx(t.items):he(t)?Zx(t.$defs,t.$ref):D(t)?Xx(t.allOf):N(t)?eP(t.properties):V(t)?tP(t.items):b(t)?rP(t.anyOf):t}function Qx(t,e){return L([t])?g.Update(zr(t),{},e):rm(t)}function nP(t,e,r,n){let o=P(t,e,r);return Qx(o,n)}function oP(t,e,r,n){return n in t?Fu([n],t,t[n])?r:P(t,e,t[n]):r}function iP(t,e){let r=tr(t,e),n=Jr(r);return qr(g.Assign(t,{[e]:n}),e)}function sP(t){let e=t.map(r=>Jr(r));return Se(e)}function aP(t){let e=t.map(r=>Jr(r));return B(e)}function uP(t){let e=s.Keys(t).reduce((n,o)=>({...n,[o]:po(t[o])}),{});return O(e)}function Jr(t){return he(t)?iP(t.$defs,t.$ref):D(t)?sP(t.allOf):b(t)?aP(t.anyOf):N(t)?uP(t.properties):O({})}function nm(t,e={}){return E("Required",[t],e)}function pP(t,e){return L([t])?g.Update(Jr(t),{},e):nm(t,e)}function dP(t,e,r,n){let o=P(t,e,r);return pP(o,n)}function om(t,e={}){return E("ReturnType",[t],e)}function I_(t){return Ne(t)?t.returnType:oe()}function lP(t,e){return L([t])?g.Update(I_(t),{},e):om(t,e)}function mP(t,e,r,n={}){let o=P(t,e,r);return lP(o,n)}function x_(t){return fo(t)?V(t.items)?wm(t.items.items):$e(t.items)?[t]:se(t.items)?[t]:[oe()]:[t]}function wm(t){return t.reduce((r,n)=>[...r,...x_(n)],[])}function L(t){return s.TakeLeft(t,(e,r)=>se(e)?!1:L(r),()=>!0)}function $i(t,e,r){return ik(t)?$i(t.type,"remove",r):nk(t)?$i(t.type,e,"remove"):ok(t)?$i(t.type,"add",r):rk(t)?$i(t.type,e,"add"):[t,e,r]}function P_(t,e){return s.IsEqual(t,"remove")?cu(e):s.IsEqual(t,"add")?In(e):e}function w_(t,e){return s.IsEqual(t,"remove")?po(e):s.IsEqual(t,"add")?Sn(e):e}function Ti(t,e,r){return s.Keys(r).reduce((n,o)=>({...n,[o]:P(t,e,r[o])}),{})}function Kr(t,e,r){let n=Rt(t,e,r);return wm(n)}function Rt(t,e,r){return r.map(n=>P(t,e,n))}function v_(t,e,r,n,o){return s.IsEqual(r,"Awaited")?cP(t,e,n[0],o):s.IsEqual(r,"Capitalize")?$I(t,e,n[0],o):s.IsEqual(r,"Conditional")?LI(t,e,n[0],n[1],n[2],n[3],o):s.IsEqual(r,"ConstructorParameters")?NI(t,e,n[0],o):s.IsEqual(r,"Evaluate")?fI(t,e,n[0],o):s.IsEqual(r,"Exclude")?UI(t,e,n[0],n[1],o):s.IsEqual(r,"Extract")?HI(t,e,n[0],n[1],o):s.IsEqual(r,"Index")?gx(t,e,n[0],n[1],o):s.IsEqual(r,"InstanceType")?yx(t,e,n[0],o):s.IsEqual(r,"Interface")?iI(t,e,n[0],n[1],o):s.IsEqual(r,"KeyOf")?bx(t,e,n[0],o):s.IsEqual(r,"Lowercase")?MI(t,e,n[0],o):s.IsEqual(r,"Mapped")?Ex(t,e,n[0],n[1],n[2],n[3],o):s.IsEqual(r,"Module")?$x(t,e,n[0],o):s.IsEqual(r,"NonNullable")?Ox(t,e,n[0],o):s.IsEqual(r,"Pick")?Jx(t,e,n[0],n[1],o):s.IsEqual(r,"Options")?Nx(t,e,n[0],n[1]):s.IsEqual(r,"Parameters")?Bx(t,e,n[0],o):s.IsEqual(r,"Partial")?Vx(t,e,n[0],o):s.IsEqual(r,"Omit")?Lx(t,e,n[0],n[1],o):s.IsEqual(r,"ReadonlyObject")?nP(t,e,n[0],o):s.IsEqual(r,"Record")?Qk(t,e,n[0],n[1],o):s.IsEqual(r,"Required")?dP(t,e,n[0],o):s.IsEqual(r,"ReturnType")?mP(t,e,n[0],o):s.IsEqual(r,"TemplateLiteral")?vS(t,e,n[0],o):s.IsEqual(r,"Uncapitalize")?OI(t,e,n[0],o):s.IsEqual(r,"Uppercase")?_I(t,e,n[0],o):E(r,n,o)}function P(t,e,r){let n=fi(r),o=$i(r,gi(r)?"add":"none",Ue(r)?"add":"none"),i=Qt(o[0])?o[0].Clone():o[0],a=se(i)?oP(t,e,i,i.$ref):te(i)?lr(P(t,e,i.items),fu(i)):st(i)?mr(P(t,e,i.iteratorItems),dk(i)):Nu(i)?Sm(t,e,i.target,i.arguments):Fe(i)?xn(Rt(t,e,i.parameters),P(t,e,i.instanceType),lk(i)):Fr(i)?v_(t,e,i.action,i.parameters,i.options):Ne(i)?Pn(Rt(t,e,i.parameters),P(t,e,i.returnType),mk(i)):D(i)?qt(Rt(t,e,i.allOf),kk(i)):ut(i)?cr(P(t,e,i.iteratorItems),Pk(i)):N(i)?O(Ti(t,e,i.properties),gk(i)):Ge(i)?dr(P(t,e,i.item),sk(i)):Me(i)?Zk(_t(i),P(t,e,et(i))):fo(i)?_l(P(t,e,i.items)):V(i)?Ke(Kr(t,e,i.items),Lk(i)):b(i)?B(Rt(t,e,i.anyOf),hk(i)):i,u=n?uo(a):a;return P_(o[1],w_(o[2],u))}function nr(t,e){return P(t,{callstack:[]},e)}function fP(t){return Ge(t)?fP(t.item):t}function gP(t,e){return L([t])?g.Update(fP(t),{},e):im(t,e)}function cP(t,e,r,n){let o=P(t,e,r);return gP(o,n)}function im(t,e={}){return E("Awaited",[t],e)}function Qr(t,e={}){return ym(t,e)}function ae(...t){let[e,r,n]=ee.Match(t,{3:(o,i,a)=>[o,i,a],2:(o,i)=>[{},o,i]});return xl(e,r,n)}function gr(...t){let[e,r,n]=ee.Match(t,{3:(a,u,p)=>[a,u,p],2:(a,u)=>[{},a,u]}),[o,i]=mu(e,r,n);return i}var Yr=class extends Error{constructor(e,r,n){super(e),Object.defineProperty(this,"cause",{value:{source:e,errors:n,value:r},writable:!1,configurable:!1,enumerable:!1})}};function hP(t,e,r){return s.IsArray(r)?r.map(n=>Be(t,e.items,n)):r}function yP(t,e,r){return e.Clean(r)}function kP(t,e,r){return Be({...t,...e.$defs},St(e.$ref),r)}function b_(t,e){let r=s.HasPropertyKey(e,"unevaluatedProperties")?{additionalProperties:e.unevaluatedProperties}:{},n=nr(t,e),o=Qr(n);return N(o)?Fx(o,r):o}function SP(t,e,r){let n=b_(t,e);return Be(t,n,r)}function Uu(t){return s.HasPropertyKey(t,"additionalProperties")?t.additionalProperties:void 0}function IP(t,e,r){if(!s.IsObject(r)||s.IsArray(r))return r;let n=Uu(e);for(let o of s.Keys(r)){if(s.HasPropertyKey(e.properties,o)){r[o]=Be(t,e.properties[o],r[o]);continue}if(s.IsBoolean(n)&&s.IsEqual(n,!0)||le(n)&&ae(t,n,r[o])){r[o]=Be(t,n,r[o]);continue}delete r[o]}return r}function xP(t,e,r){if(!s.IsObject(r))return r;let n=Uu(e),[o,i]=[new RegExp(_t(e)),et(e)];for(let a of s.Keys(r)){if(o.test(a)){r[a]=Be(t,i,r[a]);continue}if(s.IsBoolean(n)&&s.IsEqual(n,!0)||le(n)&&ae(t,n,r[a])){r[a]=Be(t,n,r[a]);continue}delete r[a]}return r}function PP(t,e,r){return s.HasPropertyKey(t,e.$ref)?Be(t,t[e.$ref],r):r}function wP(t,e,r){if(!s.IsArray(r))return r;let n=Math.min(r.length,e.items.length);for(let o=0;o<n;o++)r[o]=Be(t,e.items[o],r[o]);return s.IsGreaterThan(r.length,n)?r.slice(0,n):r}function A_(t){let e={};for(let r of s.Keys(t))s.IsUnsafePropertyKey(r)||(e[r]=ue(t[r]));for(let r of s.Symbols(t))e[r]=ue(t[r]);return e}function T_(t){return s.IsClassInstance(t)?t:A_(t)}function R_(t){return t.map(e=>ue(e))}function C_(t){return t.slice()}function E_(t){return new Map(ue([...t.entries()]))}function $_(t){return new Set(ue([...t.values()]))}function ue(t){return nt.IsTypeArray(t)?C_(t):nt.IsMap(t)?E_(t):nt.IsSet(t)?$_(t):s.IsArray(t)?R_(t):s.IsObject(t)?T_(t):t}function vP(t,e){return JSON.stringify(t).localeCompare(JSON.stringify(e))}function Mi(t,e=1){return t.sort((r,n)=>{let o=vn(r,n);return(s.IsEqual(o,"disjoint")?vP(r,n):s.IsEqual(o,"right-inside")?1:s.IsEqual(o,"left-inside")?-1:vP(r,n))*e})}function bP(t,e,r){for(let n of Mi(e.anyOf)){let o=Be(t,n,ue(r));if(ae(t,n,o))return o}return r}function Be(t,e,r){return te(e)?hP(t,e,r):Qt(e)?yP(t,e,r):he(e)?kP(t,e,r):D(e)?SP(t,e,r):N(e)?IP(t,e,r):Me(e)?xP(t,e,r):se(e)?PP(t,e,r):V(e)?wP(t,e,r):b(e)?bP(t,e,r):r}function Ht(...t){let[e,r,n]=ee.Match(t,{3:(o,i,a)=>[o,i,a],2:(o,i)=>[{},o,i]});return Be(e,r,n)}var Q={};Ct(Q,{Fail:()=>En,IsOk:()=>vm,Ok:()=>T,TryArray:()=>M_,TryBigInt:()=>bm,TryBoolean:()=>j_,TryNull:()=>J_,TryNumber:()=>X_,TryString:()=>e0,TryUndefined:()=>i0});function vm(t){return s.IsObject(t)&&s.HasPropertyKey(t,"value")}function T(t){return{value:t}}function En(){}function M_(t){return s.IsArray(t)?T(t):T([t])}function O_(t){return s.IsEqual(t,!0)?T(BigInt(1)):T(BigInt(0))}var __=/^-?(0|[1-9]\d*)n$/,D_=/^-?(0|[1-9]\d*)\.\d+$/,L_=/^-?(0|[1-9]\d*)$/;function F_(t){return __.test(t)}function N_(t){return D_.test(t)}function q_(t){return L_.test(t)}function B_(t){let e=t.toLowerCase();return F_(t)?T(BigInt(t.slice(0,t.length-1))):N_(t)?T(BigInt(t.split(".")[0])):q_(t)?T(BigInt(t)):s.IsEqual(e,"false")?T(BigInt(0)):s.IsEqual(e,"true")?T(BigInt(1)):void 0}function bm(t){return s.IsBigInt(t)?T(t):s.IsBoolean(t)?O_(t):s.IsNumber(t)?T(BigInt(Math.trunc(t))):s.IsNull(t)?T(BigInt(0)):s.IsString(t)?B_(t):s.IsUndefined(t)?T(BigInt(0)):void 0}function W_(t){return s.IsEqual(t,BigInt(0))?T(!1):s.IsEqual(t,BigInt(1))?T(!0):void 0}function U_(t){return s.IsEqual(t,0)?T(!1):s.IsEqual(t,1)?T(!0):void 0}function K_(t){return s.IsEqual(t.toLowerCase(),"false")?T(!1):s.IsEqual(t.toLowerCase(),"true")?T(!0):s.IsEqual(t,"0")?T(!1):s.IsEqual(t,"1")?T(!0):void 0}function j_(t){return s.IsBigInt(t)?W_(t):s.IsBoolean(t)?T(t):s.IsNumber(t)?U_(t):s.IsNull(t)?T(!1):s.IsString(t)?K_(t):s.IsUndefined(t)?T(!1):void 0}function G_(t){return s.IsEqual(t,BigInt(0))?T(null):void 0}function V_(t){return s.IsEqual(t,!1)?T(null):void 0}function H_(t){return s.IsEqual(t,0)?T(null):void 0}function z_(t){let e=t.toLowerCase();return s.IsEqual(e,"undefined")||s.IsEqual(e,"null")||s.IsEqual(t,"")||s.IsEqual(t,"0")?T(null):void 0}function J_(t){return s.IsBigInt(t)?G_(t):s.IsBoolean(t)?V_(t):s.IsNumber(t)?H_(t):s.IsNull(t)?T(null):s.IsString(t)?z_(t):s.IsUndefined(t)?T(null):void 0}var AP=BigInt(Number.MAX_SAFE_INTEGER),TP=BigInt(Number.MIN_SAFE_INTEGER);function Q_(t){return t<=AP&&t>=TP?T(Number(t)):void 0}function Y_(t){return T(t?1:0)}function Z_(t){let e=+t;if(s.IsNumber(e))return T(e);let r=t.toLowerCase();if(s.IsEqual(r,"false"))return T(0);if(s.IsEqual(r,"true"))return T(1);let n=bm(t);return vm(n)?n.value<=AP&&n.value>=TP?T(Number(n.value)):void 0:void 0}function X_(t){return s.IsBigInt(t)?Q_(t):s.IsBoolean(t)?Y_(t):s.IsNumber(t)?T(t):s.IsNull(t)?T(0):s.IsString(t)?Z_(t):s.IsUndefined(t)?T(0):void 0}function e0(t){return s.IsBigInt(t)?T(t.toString()):s.IsBoolean(t)?T(t.toString()):s.IsNumber(t)?T(t.toString()):s.IsNull(t)?T("null"):s.IsString(t)?T(t):s.IsUndefined(t)?T(""):void 0}function t0(t){return s.IsEqual(t,BigInt(0))?T(void 0):void 0}function r0(t){return s.IsEqual(t,!1)?T(void 0):void 0}function n0(t){return s.IsEqual(t,0)?T(void 0):void 0}function o0(t){let e=t.toLowerCase();return s.IsEqual(e,"undefined")||s.IsEqual(e,"null")||s.IsEqual(t,"")||s.IsEqual(t,"0")?T(void 0):void 0}function i0(t){return s.IsBigInt(t)?t0(t):s.IsBoolean(t)?r0(t):s.IsNumber(t)?n0(t):s.IsNull(t)?T(void 0):s.IsString(t)?o0(t):s.IsUndefined(t)?T(t):void 0}function RP(t,e,r){return Q.TryArray(r).value.map(o=>Re(t,e.items,o))}function CP(t,e,r){return e.Convert(r)}function EP(t,e,r){let n=Q.TryBigInt(r);return Q.IsOk(n)?n.value:r}function $P(t,e,r){let n=Q.TryBoolean(r);return Q.IsOk(n)?n.value:r}function MP(t,e,r){return Re({...t,...e.$defs},St(e.$ref),r)}function Ku(t,e,r){if(e.anyOf.some(a=>ae(t,a,r)))return r;let i=e.anyOf.map(a=>Re(t,a,ue(r))).find(a=>ae(t,e,a));return s.IsUndefined(i)?r:i}function OP(t,e,r){let n=mo(e);return Ku(t,n,r)}function _P(t,e,r){let n=Q.TryNumber(r);return Q.IsOk(n)?Math.trunc(n.value):r}function DP(t,e,r){let n=nr(t,e),o=Qr(n);return Re(t,o,r)}function s0(t,e,r){let n=Q.TryBigInt(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function a0(t,e,r){let n=Q.TryBoolean(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function u0(t,e,r){let n=Q.TryNumber(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function p0(t,e,r){let n=Q.TryString(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function LP(t,e,r){return s.IsEqual(e.const,r)?r:wk(e)?s0(t,e,r):vk(e)?a0(t,e,r):Iu(e)?u0(t,e,r):xu(e)?p0(t,e,r):Y()}function FP(t,e,r){let n=Q.TryNull(r);return Q.IsOk(n)?n.value:r}function NP(t,e,r){let n=Q.TryNumber(r);return Q.IsOk(n)?n.value:r}function ju(t,e,r,n){let o=s.Keys(n);for(let[i,a]of e)for(let u of o)i.test(u)||(n[u]=Re(t,r,n[u]));return n}function Oi(t,e,r){return Ue(t)&&s.IsUndefined(r[e])}function d0(t,e,r){let n=s.EntriesRegExp(e.properties),o=s.Keys(r);for(let[i,a]of n)for(let u of o)!i.test(u)||Oi(a,u,r)||(r[u]=Re(t,a,r[u]));return s.HasPropertyKey(e,"additionalProperties")&&s.IsObject(e.additionalProperties)?ju(t,n,e.additionalProperties,r):r}function qP(t,e,r){return s.IsObjectNotArray(r)?d0(t,e,r):r}function l0(t,e,r){let n=s.EntriesRegExp(e.patternProperties),o=s.Keys(r);for(let[i,a]of n)for(let u of o)i.test(u)&&(r[u]=Re(t,a,r[u]));return s.HasPropertyKey(e,"additionalProperties")&&s.IsObject(e.additionalProperties)?ju(t,n,e.additionalProperties,r):r}function BP(t,e,r){return s.IsObjectNotArray(r)?l0(t,e,r):r}function WP(t,e,r){return s.HasPropertyKey(t,e.$ref)?Re(t,t[e.$ref],r):r}function UP(t,e,r){let n=Q.TryString(r);return Q.IsOk(n)?n.value:r}function KP(t,e,r){let n=He(e.pattern);return Re(t,n,r)}function jP(t,e,r){if(!s.IsArray(r))return r;for(let n=0;n<Math.min(e.items.length,r.length);n++)r[n]=Re(t,e.items[n],r[n]);return r}function GP(t,e,r){let n=Q.TryUndefined(r);return Q.IsOk(n)?n.value:r}function VP(t,e,r){let n=Q.TryUndefined(r);return Q.IsOk(n)?void 0:r}function Re(t,e,r){return te(e)?RP(t,e,r):Qt(e)?CP(t,e,r):Bt(e)?EP(t,e,r):At(e)?$P(t,e,r):he(e)?MP(t,e,r):qe(e)?OP(t,e,r):at(e)?_P(t,e,r):D(e)?DP(t,e,r):G(e)?LP(t,e,r):wn(e)?FP(t,e,r):Ae(e)?NP(t,e,r):N(e)?qP(t,e,r):Me(e)?BP(t,e,r):se(e)?WP(t,e,r):Xe(e)?UP(t,e,r):Te(e)?KP(t,e,r):V(e)?jP(t,e,r):Tn(e)?GP(t,e,r):b(e)?Ku(t,e,r):Kt(e)?VP(t,e,r):r}function hr(...t){let[e,r,n]=ee.Match(t,{3:(o,i,a)=>[o,i,a],2:(o,i)=>[{},o,i]});return Re(e,r,n)}function HP(t,e,r){if(!s.IsArray(r))return r;for(let n=0;n<r.length;n++)r[n]=_e(t,e.items,r[n]);return r}function zP(t,e,r){return e.Default(r)}function JP(t,e,r){return _e({...t,...e.$defs},St(e.$ref),r)}function QP(t,e){return s.IsUndefined(e)?s.IsFunction(t.default)?t.default():ue(t.default):e}function YP(t,e,r){let n=nr(t,e),o=Qr(n);return _e(t,o,r)}function ZP(t,e,r){if(!s.IsObject(r))return r;let n=s.Keys(e.properties);for(let o of n){let i=_e(t,e.properties[o],r[o]);s.IsUndefined(i)&&(Ue(e.properties[o])||!s.HasPropertyKey(e.properties[o],"default"))||(r[o]=_e(t,e.properties[o],r[o]))}if(!sr(e)||s.IsBoolean(e.additionalProperties))return r;for(let o of s.Keys(r))n.includes(o)||(r[o]=_e(t,e.additionalProperties,r[o]));return r}function XP(t,e,r){if(!s.IsObject(r))return r;let[n,o]=[new RegExp(_t(e)),et(e)];for(let i of s.Keys(r))n.test(i)&&ar(o)&&(r[i]=_e(t,o,r[i]));if(!sr(e))return r;for(let i of s.Keys(r))n.test(i)||(r[i]=_e(t,e.additionalProperties,r[i]));return r}function ew(t,e,r){return s.HasPropertyKey(t,e.$ref)?_e(t,t[e.$ref],r):r}function tw(t,e,r){if(!s.IsArray(r))return r;let[n,o]=[e.items,Math.max(e.items.length,r.length)];for(let i=0;i<o;i++)i<n.length&&(r[i]=_e(t,n[i],r[i]));return r}function rw(t,e,r){for(let n of e.anyOf){let o=_e(t,n,ue(r));if(ae(t,n,o))return o}return r}function _e(t,e,r){let n=ar(e)?QP(e,r):r;return te(e)?HP(t,e,n):Qt(e)?zP(t,e,n):he(e)?JP(t,e,n):D(e)?YP(t,e,n):N(e)?ZP(t,e,n):Me(e)?XP(t,e,n):se(e)?ew(t,e,n):V(e)?tw(t,e,n):b(e)?rw(t,e,n):n}function Zr(...t){let[e,r,n]=ee.Match(t,{3:(o,i,a)=>[o,i,a],2:(o,i)=>[{},o,i]});return _e(e,r,n)}function wo(t){return(...e)=>{let[r,n,o]=ee.Match(e,{3:(i,a,u)=>[i,a,u],2:(i,a)=>[{},i,a]});return t.reduce((i,a)=>a(r,n,i),o)}}function m0(t,e,r){return e["~codec"].decode(r)}function c0(t,e,r){return e["~codec"].encode(r)}function ge(t,e,r,n){return bl(r)?s.IsEqual(t,"Decode")?m0(e,r,n):c0(e,r,n):n}function f0(t,e,r,n){if(!s.IsArray(n))return Y();for(let o=0;o<n.length;o++)n[o]=ye(t,e,r.items,n[o]);return ge(t,e,r,n)}function g0(t,e,r,n){let o=ge(t,e,r,n);if(!s.IsArray(o))return o;for(let i=0;i<o.length;i++)o[i]=ye(t,e,r.items,o[i]);return o}function nw(t,e,r,n){return s.IsEqual(t,"Decode")?f0(t,e,r,n):g0(t,e,r,n)}function ow(t,e,r,n){return n=ye(t,{...e,...r.$defs},St(r.$ref),n),ge(t,e,r,n)}function iw(t){return t.reduce((e,r)=>({...e,...r}),{})}function sw(t,e){for(let r of e)if(!s.IsDeepEqual(t,r))return r;return t}function h0(t,e,r,n){if(s.IsEqual(r.allOf.length,0))return ge(t,e,r,n);let o=r.allOf.map(u=>ye(t,e,u,Ht(u,ue(n)))),a=o.every(u=>s.IsObject(u))?iw(o):sw(n,o);return ge(t,e,r,a)}function y0(t,e,r,n){if(s.IsEqual(r.allOf.length,0))return ge(t,e,r,n);let o=ge(t,e,r,n),i=r.allOf.map(u=>ye(t,e,u,Ht(u,ue(o))));return i.every(u=>s.IsObject(u))?iw(i):sw(o,i)}function aw(t,e,r,n){return s.IsEqual(t,"Decode")?h0(t,e,r,n):y0(t,e,r,n)}function k0(t,e,r,n){if(!s.IsObjectNotArray(n))return Y();for(let o of s.Keys(r.properties))!s.HasPropertyKey(n,o)||Oi(r.properties[o],o,n)||(n[o]=ye(t,e,r.properties[o],n[o]));return ge(t,e,r,n)}function S0(t,e,r,n){let o=ge(t,e,r,n);if(!s.IsObjectNotArray(o))return o;for(let i of s.Keys(r.properties))!s.HasPropertyKey(o,i)||Oi(r.properties[i],i,o)||(o[i]=ye(t,e,r.properties[i],o[i]));return o}function uw(t,e,r,n){return s.IsEqual(t,"Decode")?k0(t,e,r,n):S0(t,e,r,n)}function I0(t,e,r,n){if(!s.IsObjectNotArray(n))return Y();let o=new RegExp(_t(r));for(let i of s.Keys(n))o.test(i)||Y(),n[i]=ye(t,e,et(r),n[i]);return ge(t,e,r,n)}function x0(t,e,r,n){let o=ge(t,e,r,n);if(!s.IsObjectNotArray(o))return o;let i=new RegExp(_t(r));for(let a of s.Keys(o))i.test(a)&&(o[a]=ye(t,e,et(r),o[a]));return o}function pw(t,e,r,n){return s.IsEqual(t,"Decode")?I0(t,e,r,n):x0(t,e,r,n)}function dw(t,e,r,n){return s.HasPropertyKey(e,r.$ref)?ye(t,e,e[r.$ref],n):n}function lw(t,e,r,n){return s.IsEqual(t,"Decode")?ge(t,e,r,dw(t,e,r,n)):dw(t,e,r,ge(t,e,r,n))}function P0(t,e,r,n){if(!s.IsArray(n))return Y();for(let o=0;o<Math.min(r.items.length,n.length);o++)n[o]=ye(t,e,r.items[o],n[o]);return ge(t,e,r,n)}function w0(t,e,r,n){let o=ge(t,e,r,n);if(!s.IsArray(o))return n;for(let i=0;i<Math.min(r.items.length,o.length);i++)o[i]=ye(t,e,r.items[i],o[i]);return o}function mw(t,e,r,n){return s.IsEqual(t,"Decode")?P0(t,e,r,n):w0(t,e,r,n)}function v0(t,e,r,n){for(let o of Mi(r.anyOf,1)){if(!ae(e,o,n))continue;let i=ye(t,e,o,n);return ge(t,e,r,i)}return n}function b0(t,e,r,n){let o=ge(t,e,r,n);for(let i of Mi(r.anyOf,-1)){let a=ye(t,e,i,ue(o));if(ae(e,i,a))return a}return o}function cw(t,e,r,n){return s.IsEqual(t,"Decode")?v0(t,e,r,n):b0(t,e,r,n)}function ye(t,e,r,n){return te(r)?nw(t,e,r,n):he(r)?ow(t,e,r,n):D(r)?aw(t,e,r,n):N(r)?uw(t,e,r,n):Me(r)?pw(t,e,r,n):se(r)?lw(t,e,r,n):V(r)?mw(t,e,r,n):b(r)?cw(t,e,r,n):ge(t,e,r,n)}var Am=class extends Yr{constructor(e,r){super("Decode",e,r)}};function A0(t,e,r){if(!ae(t,e,r))throw new Am(r,gr(t,e,r));return r}function T0(t,e,r){return ye("Decode",t,e,r)}var MCe=wo([(t,e,r)=>ue(r),(t,e,r)=>Zr(t,e,r),(t,e,r)=>hr(t,e,r),(t,e,r)=>Ht(t,e,r),(t,e,r)=>A0(t,e,r),(t,e,r)=>T0(t,e,r)]);var Tm=class extends Yr{constructor(e,r){super("Encode",e,r)}};function R0(t,e,r){if(!ae(t,e,r))throw new Tm(r,gr(t,e,r));return r}function C0(t,e,r){return ye("Encode",t,e,r)}var jCe=wo([(t,e,r)=>ue(r),(t,e,r)=>C0(t,e,r),(t,e,r)=>Zr(t,e,r),(t,e,r)=>hr(t,e,r),(t,e,r)=>Ht(t,e,r),(t,e,r)=>R0(t,e,r)]);var Vu=class extends Yr{constructor(e,r){super("Parse",e,r)}};function E0(t,e,r){if(!ae(t,e,r))throw new Vu(r,gr(t,e,r));return r}var $0=wo([(t,e,r)=>ue(r),(t,e,r)=>Zr(t,e,r),(t,e,r)=>hr(t,e,r),(t,e,r)=>Ht(t,e,r),(t,e,r)=>E0(t,e,r)]);var O0=O({type:Z("insert"),path:Tt(),value:Yt()}),_0=Object({type:Z("update"),path:Tt(),value:Yt()}),D0=O({type:Z("delete"),path:Tt()}),TOe=B([O0,_0,D0]);var GDe=new Jg(512);function kw(t){return{success:!1,error:{issues:[{path:[],message:t}]}}}function Rm(){return{safeParse(t){return t===void 0?{success:!0,data:void 0}:!t||typeof t!="object"||Array.isArray(t)?kw("expected config object"):Object.keys(t).length>0?kw("config must be empty"):{success:!0,data:t}},jsonSchema:{type:"object",additionalProperties:!1,properties:{}}}}function j0(t,e){let r=!1,n;return()=>(r||(n=(typeof t=="function"?t():t)??e,r=!0),n)}function Hu({id:t,name:e,description:r,kind:n,configSchema:o=Rm,reload:i,nodeHostCommands:a,securityAuditCollectors:u,register:p}){let d=j0(o);return{id:t,name:e,description:r,...n?{kind:n}:{},...i?{reload:i}:{},...a?{nodeHostCommands:a}:{},...u?{securityAuditCollectors:u}:{},get configSchema(){return d()},register:p}}function J0(t){let e=parseInt(process.env.OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS??"168",10)||168,r=e*60*60*1e3,n=Date.now()-r,o=new Set(t.listPersistedSessions().map(p=>p.worktreePath).filter(p=>typeof p=="string"&&p.length>0)),i=new Set,a=process.env.OPENCLAW_WORKTREE_DIR??K.worktreeDir;if(a)i.add(a);else for(let p of t.listPersistedSessions())if(p.workdir)try{let d=z0("git",["rev-parse","--show-toplevel"],{cwd:p.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();d&&i.add(Sw(d,".worktrees"))}catch{}if(i.size===0)return;let u=0;for(let p of i)try{let d=G0(p);for(let l of d){if(!l.startsWith("openclaw-worktree-"))continue;let m=Sw(p,l);try{let c=V0(m);if(!c.isDirectory()||c.mtimeMs>n||o.has(m))continue;H0(m,{recursive:!0,force:!0}),u++}catch(c){console.warn(`[index] Failed to clean up orphaned worktree ${m}: ${c instanceof Error?c.message:String(c)}`)}}}catch{}u>0&&console.info(`[index] Cleaned up ${u} orphaned worktree(s) at startup (age > ${e}h)`)}function Q0(t){let e=null,r=null,n=!1,o=!1,i=t.registerTool;qn(t.runtime);let a=m=>{if(n){m&&!o&&(qn(t.runtime,m.config),o=!0);return}let c=t.pluginConfig??{};_m(c),m?(qn(t.runtime,m.config),o=!0):(qn(t.runtime),o=!1),e=new Ea(K.maxSessions,K.maxPersistedSessions,{worktreeSummaryProvider:fg()}),r=new Js(e),Ju(e),Qu(r),r.start(),J0(e),e.bootstrapMaintenanceSchedules(),n=!0},u=()=>{r&&r.stop(),e&&e.killAll("shutdown"),e&&e.dispose(),r=null,e=null,n=!1,o=!1,qn(void 0),Qu(null),Ju(null)},p=(m,c)=>{i(h=>(a(),m(h)),c)},d={...t,registerCommand(m){t.registerCommand({...m,handler:c=>(a(),m.handler(c))})}},l=m=>{let c=Cf(m);t.registerInteractiveHandler({...c,handler:async h=>(a(),c.handler(h))})};p(m=>Sc(m),{optional:!1,name:"agent_launch"}),p(m=>Vc(m),{optional:!1,name:"agent_sessions"}),p(m=>Hc(m),{optional:!1,name:"agent_kill"}),p(m=>Ts(m),{optional:!1,name:"agent_output"}),p(m=>Xc(m),{optional:!1,name:"agent_respond"}),p(m=>ef(m),{optional:!1,name:"agent_request_plan_approval"}),p(m=>rf(m),{optional:!1,name:"agent_send_plan_offer"}),p(m=>nf(m),{optional:!1,name:"agent_stats"}),p(m=>Ds(m),{optional:!1,name:"agent_merge"}),p(m=>zo(m),{optional:!1,name:"agent_pr"}),p(m=>hf(m),{optional:!1,name:"agent_worktree_cleanup"}),p(m=>yf(m),{optional:!1,name:"agent_worktree_status"}),p(m=>kf(m),{optional:!1,name:"goal_launch"}),p(m=>If(m),{optional:!1,name:"goal_status"}),p(m=>xf(m),{optional:!1,name:"goal_stop"}),p(m=>Pf(m),{optional:!1,name:"goal_edit"}),l("telegram"),l("discord"),$f(d),Mf(d),Of(d),_f(d),Df(d),Lf(d),Nf(d),qf(d),Bf(d),Uf(d),t.registerService({id:"openclaw-code-agent",start:a,stop:u})}var KLe=Hu({id:"openclaw-code-agent",name:"OpenClaw Code Agent",description:"Multi-session coding-agent orchestration from OpenClaw chat",register:Q0});export{KLe as default,Q0 as register};
|
|
224
|
+
`)}`:void 0}}buildNotificationDedupeKey(e,n){let r=n.idempotencyKey?.trim();if(!r)return;let o=this.getDeliveryRef(e);if(!o)return;let i=Ae(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,n,r){let o=this.notificationDedupe.deliveredRecords(n,e?this.getPersistedSession?.(e)?.notificationDedupe:void 0,r);o&&this.applyNotificationDedupePatch(e,o)}releaseNotificationDedupe(e,n){let r=this.notificationDedupe.releasedRecords(n,e?this.getPersistedSession?.(e)?.notificationDedupe:void 0);r&&this.applyNotificationDedupePatch(e,r)}applyNotificationDedupePatch(e,n){this.getPersistedSession&&e&&this.applyPersistedPatch(e,{notificationDedupe:n})}markCompletionSummaryDelivered(e,n,r,o){let i=this.completionSummaries.completionRecordsAfterDelivery(n,e?this.getPersistedSession?.(e)?.completionSummaryDedupe:void 0,r,o);i&&this.applyCompletionSummaryDedupePatch(e,i)}applyCompletionSummaryDedupePatch(e,n){this.getPersistedSession&&e&&this.applyPersistedPatch(e,{completionSummaryDedupe:n})}logNotificationDecision(e){let n=Ae(e.session);ag({event:"oca_notification_decision",sessionId:"id"in e.session?e.session.id:e.session.sessionId,sessionName:e.session.name,harnessSessionId:e.session.harnessSessionId,originRoute:n?{provider:n.provider,accountId:n.accountId,target:n.target,threadId:n.threadId,sessionKey:n.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 rg("sha256").update(e).digest("hex").slice(0,16)}};fe();import{existsSync as dg}from"fs";var Hr=class{getCompletionState(e,n,r,o){return Nt(e,r,o)?"has-commits":Nt(e,o,r)?"base-advanced":lt(n)?"dirty-uncommitted":"no-change"}isResolvedWorktreeEligibleForCleanup(e,n,r){if(!e.worktreePath||!e.workdir||!dg(e.worktreePath)||e.pendingWorktreeDecisionSince||e.worktreeState==="pending_decision")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&&n-i>=r}};var jr=class{constructor(e,n,r,o){this.pendingQuestions=e;this.dispatchSessionNotification=n;this.clearWaitingTimestamp=r;this.getQuestionButtons=o}pendingQuestions;dispatchSessionNotification;clearWaitingTimestamp;getQuestionButtons;async handleAskUserQuestion(e,n){let i=n?.questions??[];if(i.length===0)throw new Error("AskUserQuestion: no questions in input");let s=i[0],a=s.options??[],d=this.getQuestionButtons(e.id,a),l=`â [${e.name}] ${s.question}`,u=e.pendingInputState?.requestId??`${s.question}:${a.map(c=>c.label).join("|")}`,p=[`[ASK USER QUESTION] Session "${e.name}" has a question requiring user input.`,"",`Question: ${s.question}`,...a.length>0?["Options:",...a.map((c,f)=>` ${f+1}. ${c.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${e.id}", message="<answer>") with their answer.`].join(`
|
|
225
|
+
`);return new Promise((c,f)=>{let g=setTimeout(()=>{this.pendingQuestions.delete(e.id),f(new Error(`AskUserQuestion timed out after 600s for session "${e.name}"`))},6e5);g.unref?.(),this.pendingQuestions.set(e.id,{resolve:c,reject:f,questions:i,timeoutHandle:g}),this.dispatchSessionNotification(e,{label:"ask-user-question",idempotencyKey:`ask-user-question:${e.id}:${u}`,userMessage:l,notifyUser:"always",buttons:d,wakeMessageOnNotifySuccess:["AskUserQuestion delivered to the user.",`Session: ${e.name} | ID: ${e.id}`,`Question: ${s.question}`,"Await their selection â do NOT answer this question yourself."].join(`
|
|
226
|
+
`),wakeMessageOnNotifyFailed:p})})}resolveAskUserQuestion(e,n){let r=this.pendingQuestions.get(e);if(!r){`${e}`;return}clearTimeout(r.timeoutHandle),this.pendingQuestions.delete(e);let o=r.questions[0],i=o.options??[],s=i[n];if(!s){r.reject(new Error(`AskUserQuestion: invalid option index ${n} (${i.length} options available)`));return}this.clearWaitingTimestamp(e),r.resolve({behavior:"allow",updatedInput:{questions:r.questions,answers:{[o.question]:s.label}}})}dispose(){for(let e of this.pendingQuestions.values())clearTimeout(e.timeoutHandle),e.reject(new Error("SessionManager disposed before AskUserQuestion resolved."));this.pendingQuestions.clear()}};Q();Bt();var zr=class t{constructor(e,n,r,o){this.buildRoutingProxy=e;this.dispatchNotification=n;this.updatePersistedSession=r;this.getWorktreeDecisionButtons=o}buildRoutingProxy;dispatchNotification;updatePersistedSession;getWorktreeDecisionButtons;static REMINDER_THRESHOLD_MS=10800*1e3;static REMINDER_INTERVAL_MS=10800*1e3;getNextReminderAt(e){let n=new Date(e.pendingWorktreeDecisionSince).getTime();if(this.getWorktreeDecisionReminderStatus(e,n)!=="pending")return;let r=[n+t.REMINDER_THRESHOLD_MS];if(e.worktreeDecisionSnoozedUntil){let o=new Date(e.worktreeDecisionSnoozedUntil).getTime();Number.isFinite(o)&&r.push(o)}if(e.lastWorktreeReminderAt){let o=new Date(e.lastWorktreeReminderAt).getTime();Number.isFinite(o)&&r.push(o+t.REMINDER_INTERVAL_MS)}return Math.max(...r)}sendReminderIfDue(e,n=Date.now()){this.clearResolvedReminderState(e);let r=this.getNextReminderAt(e);if(r==null||r>n)return!1;let o=n-new Date(e.pendingWorktreeDecisionSince).getTime(),i=Math.floor(Math.max(0,o)/(3600*1e3));try{this.sendReminderNotification(e,i)}catch(s){return`${e.name}${s instanceof Error?s.message:String(s)}`,!1}for(let s of ae(e))this.updatePersistedSession(s,{lastWorktreeReminderAt:new Date(n).toISOString()});return!0}sendReminderNotification(e,n){let r=this.buildRoutingProxy({id:e.sessionId??e.name??T(e)??e.harnessSessionId,sessionId:e.sessionId,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef,route:e.route});if(e.worktreeStrategy==="delegate"){this.dispatchNotification(r,{label:`worktree-stale-reminder-${e.name}`,wakeMessage:gi(e,n),notifyUser:"never"});return}let o=[`â° Reminder: branch \`${e.worktreeBranch??"unknown"}\` is still waiting for a merge decision.`,`Session: ${e.name} | Pending: ${n}h`,"",`agent_merge(session="${e.name}") or agent_pr(session="${e.name}") or agent_worktree_cleanup() to resolve.`].join(`
|
|
227
|
+
`);this.dispatchNotification(r,{label:`worktree-stale-reminder-${e.name}`,userMessage:o,notifyUser:"always",buttons:this.getWorktreeDecisionButtons(N(e)??e.harnessSessionId)})}clearResolvedReminderState(e){if(!e.pendingWorktreeDecisionSince&&!e.lastWorktreeReminderAt&&!e.worktreeDecisionSnoozedUntil||this.getWorktreeDecisionReminderStatus(e)!=="resolved")return!1;let n=!1;for(let r of ae(e))n=this.updatePersistedSession(r,{pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDecisionSnoozedUntil:void 0})||n;return n}getWorktreeDecisionReminderStatus(e,n){if(!e.pendingWorktreeDecisionSince)return"inactive";let r=n??new Date(e.pendingWorktreeDecisionSince).getTime();if(!Number.isFinite(r))return"inactive";if(e.worktreeMerged||e.worktreePrUrl||e.lifecycle==="terminal")return"resolved";let o=new Set(["merged","released","dismissed","none","cleanup_failed"]);if(e.worktreeState&&o.has(e.worktreeState))return"resolved";let i=new Set(["merged","released","dismissed","no_change","none","cleanup_failed"]);if(e.worktreeLifecycle?.state&&i.has(e.worktreeLifecycle.state))return"resolved";let s=e.worktreeState==="pending_decision"||e.lifecycle==="awaiting_worktree_decision"||e.worktreeLifecycle?.state==="pending_decision",a=e.worktreeState==null&&e.lifecycle==null&&e.worktreeLifecycle?.state==null&&!e.worktreeMerged&&!e.worktreePrUrl;if(!s&&!a)return"inactive";let d=Ke(e,{activeSession:!1,includePrSync:!1});return d.derivedState==="merged"||d.derivedState==="released"||d.derivedState==="cleanup_failed"?"resolved":"pending"}};fe();Q();ke();function Jt(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&lg(t.approvalPromptStatus)}function lg(t){return t==="delivered"||t==="fallback_delivered"}function Yt(t,e){return!t||e==null?!1:!!(t.pendingPlanApproval&&t.approvalState==="pending"&&t.lifecycle==="awaiting_plan_decision"&&(t.actionablePlanDecisionVersion??t.planDecisionVersion)===e)}function St(t,e,n=!1){let r="id"in t?t.id:t.sessionId??"unknown-session";return[n?"Plan review fallback text delivered to the user because interactive buttons could not be delivered.":"Plan approval buttons delivered to the user.",`Session: ${t.name??"unknown"} | ID: ${r} | Plan v${e??"?"}`,`Wait for their ${n?"explicit reply":"button callback"} â do NOT approve or reject this plan yourself.`].join(`
|
|
228
|
+
`)}function Qr(t){let e="id"in t.session?t.session.id:t.session.sessionId??"unknown-session",n=t.originThreadLine??(t.session.originThreadId!=null?`Origin thread: ${t.session.originThreadId}`:"");return["[PLAN APPROVAL DELIVERY FAILED] The plugin could not deliver the canonical plan review buttons or the explicit fallback text to the user.",`Name: ${t.session.name??"unknown"} | ID: ${e} | Plan v${t.planDecisionVersion??"?"}`,n,"","No user-visible actionable review prompt is confirmed for this plan version.","Intervene manually before assuming the user saw the plan review request."].filter(Boolean).join(`
|
|
229
|
+
`)}import{existsSync as ug,readFileSync as pg}from"fs";function cg(t,e){if(t.latestPlanArtifactVersion===e&&t.latestPlanArtifact)return t.latestPlanArtifact;let n=t.planFilePath?.trim();if(!(!n||!ug(n)))try{let r=pg(n,"utf-8").trim();return r?{markdown:r,steps:[]}:void 0}catch{return}}var Jr=class{constructor(e){this.deps=e}deps;dispatchPlanApprovalFallback(e,n,r){let o=new Date().toISOString();this.deps.dispatchSessionNotification(e,{label:"plan-approval-fallback",idempotencyKey:`plan-approval:${e.id}:v${n??"unknown"}:fallback`,userMessage:jt({session:e,summary:r}),notifyUser:"always",shouldDispatch:()=>Yt(e,n),hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,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:n,approvalPromptVersion:n,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:St(e,n,!0),wakeMessageOnNotifyFailed:Qr({session:e,planDecisionVersion:n,originThreadLine:this.deps.originThreadLine(e)})})}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:!!Ae(e)}handleTurnEnd(e,n){if(e.status!=="running"){`${e.id}${e.status}`;return}if(!e.goalTaskId){if(n||e.pendingPlanApproval){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}let n={notificationSent:!1,worktreeRemoved:!1};e.worktreePath&&e.originalWorkdir&&(n=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),d=e.worktreeBranch,l=de(e);`${e.name}${e.costUsd.toFixed(2)}${e.duration}`;let u=!1;if(a&&!l&&(u=me(a,e.worktreePath)),a&&d&&!l&&u&&be(a,d),u){for(let p of ae(e))this.deps.updatePersistedSession(p,{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),d=de(e);n.worktreeRemoved?`${e.name}`:o?`${e.name}${e.worktreeStrategy}`:a&&!d&&me(a,e.worktreePath)}if(n.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,ne(a,200),r);return}let i=`$${(e.costUsd??0).toFixed(2)}`,s=e.duration;if(e.killReason==="idle-timeout"){let a=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0;if(e.pendingPlanApproval){let d=e.actionablePlanDecisionVersion??e.planDecisionVersion,l=Jt(e,d);if(a==="delegate"){this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",idempotencyKey:`plan-approval-timeout:${e.id}:v${d??"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(`
|
|
230
|
+
`),notifyUser:"never"}),this.deps.clearRetryTimersForSession(e.id);return}if(a==="ask"&&l){this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",idempotencyKey:`plan-approval-timeout:${e.id}:v${d??"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${d??"?"}`,this.deps.originThreadLine(e),"Do NOT post another approval summary unless canonical delivery is known to be missing."].join(`
|
|
231
|
+
`)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",idempotencyKey:`plan-approval-timeout:${e.id}:v${d??"unknown"}:user-prompt`,userMessage:[`đ [${e.name}] Plan v${d??"?"} still awaiting approval after idle timeout | ${i} | ${ve(s)}`,"","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(`
|
|
232
|
+
`),notifyUser:"always",buttons:a==="ask"&&!l?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:d}):void 0}),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} | ${ve(s)}`,notifyUser:"always",buttons:this.deps.getResumeButtons(e.id,e)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.notifySession(e,`â [${e.name}] ${di(e.killReason)} | ${i} | ${ve(s)}`),this.deps.clearRetryTimersForSession(e.id)}emitWaitingForInput(e){if(!this.deps.debounceWaitingEvent(e.id))return;let n=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0,r=e.actionablePlanDecisionVersion??e.planDecisionVersion,o=e.pendingPlanApproval&&n==="ask"&&Jt(e,r),i=e.pendingPlanApproval?void 0:this.deps.getOutputPreview(e),s=!e.pendingPlanApproval&&e.pendingInputState?.promptText?e.pendingInputState.promptText:!e.pendingPlanApproval&&i!==void 0?i:this.deps.getOutputPreview(e,e.pendingPlanApproval&&n!=="delegate"?Number.POSITIVE_INFINITY:void 0),a=e.pendingPlanApproval&&n==="ask"&&!o?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:r}):!e.pendingPlanApproval&&e.pendingInputState?.options.length?this.deps.getQuestionButtons(e.id,e.pendingInputState.options.map(p=>({label:p}))):void 0,d=cg(e,r),l=wi({session:e,preview:s,questionText:e.pendingPlanApproval?void 0:e.pendingInputState?.promptText,questionContextPreview:i,planArtifact:d,originThreadLine:this.deps.originThreadLine(e),planApprovalMode:n,planApprovalButtons:a,questionButtons:e.pendingPlanApproval?void 0:a}),u=l.planReviewSummary??s;if(l.label==="plan-approval"&&n==="ask"&&o){this.deps.dispatchSessionNotification(e,{label:l.label,idempotencyKey:`plan-approval:${e.id}:v${r??"unknown"}:canonical`,userMessage:l.userMessage,userMessages:l.userMessages,notifyUser:"never",buttons:l.buttons,wakeMessage:l.wakeMessage});return}if(l.label==="plan-approval"&&n==="ask"){this.deps.dispatchSessionNotification(e,{label:l.label,idempotencyKey:`plan-approval:${e.id}:v${r??"unknown"}:canonical`,userMessage:l.userMessage,userMessages:l.userMessages,notifyUser:"always",buttons:l.buttons,hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{canonicalPlanPromptVersion:r,approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},shouldDispatch:()=>Yt(e,r),onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,r,u),wakeMessageOnNotifySuccess:St(e,r)});return}if(l.label==="plan-approval"){this.deps.dispatchSessionNotification(e,{label:l.label,idempotencyKey:`plan-approval:${e.id}:v${r??"unknown"}:wake-only`,userMessage:l.userMessage,wakeMessage:l.wakeMessage,notifyUser:"never",buttons:l.buttons});return}this.deps.dispatchSessionNotification(e,{label:l.label,idempotencyKey:`waiting:${e.id}:${e.pendingInputState?.requestId??`${l.label}:${l.userMessage}`}`,userMessage:l.userMessage,notifyUser:"always",buttons:l.buttons,wakeMessageOnNotifyFailed:l.wakeMessage})}emitTurnComplete(e){`${e.id}${e.result?.num_turns??0}${e.worktreeStrategy??"none"}`;let n=mi({session:e,originThreadLine:this.deps.originThreadLine(e),preview:this.deps.getOutputPreview(e)});this.deps.dispatchSessionNotification(e,{label:"turn-complete",idempotencyKey:`turn-complete:${e.id}:${e.result?.num_turns??0}`,userMessage:n.userMessage,wakeMessage:n.wakeMessage,notifyUser:"always",onUserNotifyFailed:()=>{`${e.id}`,this.deps.shouldEmitTerminalWake(e)&&this.emitCompleted(e)}})}emitCompleted(e){let n=this.deps.getOutputPreview(e),r=this.shouldRequestCompletionFollowup(e),o=ui({session:e,originThreadLine:this.deps.originThreadLine(e),preview:n}),i;this.deps.dispatchSessionNotification(e,{label:"completed",idempotencyKey:`terminal-completed:${e.id}`,userMessage:o.userMessage,notifyUser:"always",completionSummary:{required:r,producer:"terminal",outcomeKey:`terminal:${e.id}`},completionWakeSummaryRequired:r,completionWakeOutcomeKey:`terminal:${e.id}`,requireDirectUserNotification:!0,wakeMessageOnNotifySuccess:r?o.wakeMessageOnNotifySuccess:void 0,wakeMessageOnNotifyFailed:r?o.wakeMessageOnNotifyFailed:void 0,hooks:{onNotifySucceeded:()=>{i=!0,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_succeeded",canonicalStatusDelivered:i,followupSummaryRequired:r})},onNotifyFailed:()=>{i=!1,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_failed",canonicalStatusDelivered:i,followupSummaryRequired:r})},onWakeSucceeded:()=>{this.logCompletionWakeDiagnostic({session:e,event:"completion_wake_succeeded",canonicalStatusDelivered:i,followupSummaryRequired:r})}}})}emitFailed(e,n,r){let o=ci({session:e,originThreadLine:this.deps.originThreadLine(e),errorSummary:n,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}:${n}`,userMessage:o.userMessage,wakeMessage:o.wakeMessage,notifyUser:"always",buttons:o.buttons})}};Q();fe();import{existsSync as mg}from"fs";var Yr=class{constructor(e){this.deps=e}deps;async dismissWorktree(e){let n=this.deps.getPersistedSession(e),r=this.deps.resolveActiveSession(e),o=r??n;if(!o)return`Error: Session "${e}" not found.`;let i=r?.worktreePath??n?.worktreePath,s=this.deps.resolveWorktreeRepoDir(r?.originalWorkdir??n?.workdir,i),a=r?.worktreeBranch??n?.worktreeBranch,d=r?.name??n?.name??e;if(!s)return`Error: No workdir found for session "${e}".`;let l=de(o);!l&&i&&mg(i)&&me(s,i,{destructive:!0}),a&&be(s,a);for(let p of ae(r??n))this.deps.updatePersistedSession(p,{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:n?.worktreeLifecycle?.baseBranch,targetRepo:n?.worktreePrTargetRepo,pushRemote:n?.worktreePushRemote}});let u=l?`đī¸ [${d}] Branch \`${a??"unknown"}\` dismissed. Native backend worktree released for backend cleanup.`:`đī¸ [${d}] Branch \`${a??"unknown"}\` dismissed and permanently deleted.`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:N(r??n??{id:e})??e,sessionId:n?.sessionId,harnessSessionId:r?.harnessSessionId??n?.harnessSessionId,backendRef:r?.backendRef??n?.backendRef,route:r?.route??n?.route}),{label:"worktree-dismissed",idempotencyKey:`worktree-dismissed:${N(r??n??{id:e})??e}:${a??"unknown"}`,userMessage:u,notifyUser:"always"}),u}snoozeWorktreeDecision(e,n={}){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 d of ae(r))this.deps.updatePersistedSession(d,{worktreeDecisionSnoozedUntil:i,lastWorktreeReminderAt:new Date(o).toISOString()});let a=`âī¸ Reminder snoozed 24h for \`${r.worktreeBranch??"unknown"}\` (session: ${r.name})`;return n.notifyUser!==!1&&this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:N(r)??T(r)??r.harnessSessionId,sessionId:r.sessionId,harnessSessionId:r.harnessSessionId,backendRef:r.backendRef,route:r.route}),{label:"worktree-snoozed",idempotencyKey:`worktree-snoozed:${N(r)??T(r)??r.harnessSessionId}:${i}`,userMessage:a,notifyUser:"always"}),a}};var Vd=new Set(["starting","running"]),Zr=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>Vd.has(e.status)).length}uniqueName(e){let n=new Set([...this.sessions.values()].filter(o=>Vd.has(o.status)).map(o=>o.name));if(!n.has(e))return e;let r=2;for(;n.has(`${e}-${r}`);)r+=1;return`${e}-${r}`}add(e){this.sessions.set(e.id,e)}remove(e){this.sessions.delete(e)}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()]}};var Xr=class{constructor(e){this.deps=e}deps;initializeSession(e,n,r,o={}){if(this.deps.hydrateSpawnedSession(e,n,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)}),e.start(),o.notifyLaunch!==!1){let i=this.deps.formatLaunchWorkdirLabel(e),s=`đ [${e.name}] Launched | ${i} | ${$t({harness:e.harnessName,model:e.model})??"default"}`;this.deps.notifySession(e,s,"launch")}return e}};var eo=class{buildNoChangeNotification(e){let{session:n,nativeBackendWorktree:r,cleanupSucceeded:o,worktreePath:i,preview:s,originThreadLine:a}=e,d=o?r?"native backend worktree released for backend cleanup":"worktree cleaned up":`cleanup failed; worktree still exists at ${i}`;return{label:o?"worktree-no-changes":"worktree-no-changes-cleanup-failed",idempotencyKey:`worktree-no-change:${n.id}:${o?"cleaned":"cleanup-failed"}`,userMessage:o?r?`âšī¸ [${n.name}] Session completed with no changes â native backend worktree released for backend cleanup`:`âšī¸ [${n.name}] Session completed with no changes â worktree cleaned up`:`â ī¸ [${n.name}] Session completed with no changes, but worktree cleanup failed. Worktree still exists at ${i}`,wakeMessage:hi({sessionName:n.name,sessionId:n.id,cleanupSummary:d,preview:s,originThreadLine:a,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,approvalState:n.approvalState,planApproval:n.planApproval,approvalPromptStatus:n.approvalPromptStatus,approvalPromptMessageKind:n.approvalPromptMessageKind,approvalPromptDeliveredAt:n.approvalPromptDeliveredAt}),notifyUser:"always"}}buildAskNotification(e){let{session:n,branchName:r,baseBranch:o,diffSummary:i,buttons:s,summaryLines:a=[]}=e,d=i.commitMessages.slice(0,5).map(p=>`âĸ ${p.hash} ${p.message} (${p.author})`),l=i.commits>5?`...and ${i.commits-5} more`:"",u=n.worktreePrTargetRepo?`Branch: \`${r}\` â \`${o}\` | PR target: ${n.worktreePrTargetRepo}`:`Branch: \`${r}\` â \`${o}\``;return{label:"worktree-merge-ask",idempotencyKey:["worktree-decision",n.id,r,o,i.commits,i.commitMessages.map(p=>p.hash).join(",")].join(":"),userMessage:[`đ Worktree decision required for session \`${n.name}\``,"",u,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`,"",...a.length>0?["Summary:",...a.map(p=>`- ${p}`),""]:[],"Recent commits:",...d,...l?[l]:[],"",`â ī¸ Discard will permanently delete branch \`${r}\` and all local changes. This cannot be undone.`].join(`
|
|
233
|
+
`),notifyUser:"always",buttons:s,wakeMessageOnNotifySuccess:["Worktree decision buttons delivered to the user.",`Session: ${n.name} | ID: ${n.id}`,u,"Wait for their button callback â do NOT act on this worktree yourself."].join(`
|
|
234
|
+
`),wakeMessageOnNotifyFailed:[`đ Worktree decision required for session \`${n.name}\``,"",u,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`].join(`
|
|
235
|
+
`)}}buildDelegateNotification(e){let{session:n,branchName:r,baseBranch:o,diffSummary:i,originThreadLine:s}=e,a=i.commitMessages.slice(0,5).map(u=>`âĸ ${u.hash} ${u.message} (${u.author})`),d=i.commits>5?`...and ${i.commits-5} more`:void 0,l=n.prompt?n.prompt.slice(0,500):"(no prompt)";return{label:"worktree-delegate",idempotencyKey:["worktree-delegate",n.id,r,o,i.commits,i.commitMessages.map(u=>u.hash).join(",")].join(":"),userMessage:[`đ Worktree decision pending for session \`${n.name}\``,"",`Branch: \`${r}\` â \`${o}\``,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`,"","The delegated reviewer is deciding whether to merge, open a PR, or ask for your choice."].join(`
|
|
236
|
+
`),wakeMessage:fi({sessionName:n.name,sessionId:n.id,branchName:r,baseBranch:o,promptSnippet:l,commitLines:a,moreNote:d,originThreadLine:s,diffSummary:i}),notifyUser:"always"}}};function Gd(t,e=1e3){let n=!Number.isFinite(e),r=typeof t.getOutput=="function"?t.getOutput():[],o=n?r.join(`
|
|
237
|
+
`):fg(t);return n?o:o.length>e?Hd(t)?vn(o,e):ks(o,e):o}function fg(t){let e=typeof t.getOutput=="function"?t.getOutput():[],n=e.join(`
|
|
238
|
+
`).trim();return n?Hd(t)?gg(n)??n:e.slice(-20).join(`
|
|
239
|
+
`):""}function Hd(t){if(t.status==="completed"||t.killReason==="done")return!0;let e=t;return e.approvalState==="approved"||e.planModeApproved===!0||(e.planDecisionVersion??0)>0}function gg(t){let n=t.split(/\n\s*\n+/).map(r=>r.trim()).filter(r=>/[A-Za-z0-9]/.test(r)).at(-1);if(n)return n.length>=120||n.includes(`
|
|
240
|
+
`)?n:void 0}ke();fe();te();import{unlinkSync as hg}from"fs";var to=class t{timers=new Map;disposed=!1;static MAX_DELAY_MS=2147483647;schedule(e,n,r){if(this.disposed)return;this.cancel(e);let o=Math.max(0,n-Date.now()),i=setTimeout(()=>{if(this.timers.delete(e),!this.disposed){if(n-Date.now()>0){this.schedule(e,n,r);return}r()}},Math.min(o,t.MAX_DELAY_MS));i.unref?.(),this.timers.set(e,i)}cancel(e){let n=this.timers.get(e);n&&(clearTimeout(n),this.timers.delete(e))}cancelPrefix(e){for(let n of this.timers.keys())n.startsWith(e)&&this.cancel(n)}dispose(){this.disposed=!0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};Q();Bt();fe();var jd=10080*60*1e3,Sg=300*1e3,zd="tmp-output:cleanup";function yg(t){return t instanceof Error?t.message:String(t)}var no=class{constructor(e){this.deps=e}deps;scheduler=new to;schedule(e,n,r){this.scheduler.schedule(e,n,r)}cancel(e){this.scheduler.cancel(e)}cancelPrefix(e){this.scheduler.cancelPrefix(e)}bootstrapMaintenanceSchedules(){let e=Date.now();this.deps.store.cleanupTmpOutputFiles(e);for(let n of this.deps.store.listPersistedSessions())this.syncPersistedSessionMaintenance(n);this.syncActionTokenExpiryDeadline(),this.deps.store.cleanupOrphanOutputFiles(),this.syncTmpOutputCleanupDeadline(e)}syncRuntimeGcDeadline(e){if(!e.completedAt)return;let n=this.runtimeGcKey(e.id);this.schedule(n,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),this.deps.persistSession(r,{scheduleRuntimeGc:!1}),this.deps.clearRuntimeSessionState(e.id)})}cancelRuntimeGc(e){this.cancel(this.runtimeGcKey(e))}cancelPersistedMaintenance(e){let n=this.persistedMaintenanceRef(e);n&&this.cancelPrefix(`persisted:${n}:`)}syncPersistedSessionMaintenance(e){let n=this.persistedMaintenanceRef(e);if(!n)return;this.cancel(this.persistedMaintenanceKey(n,"worktree-reminder"));let r=this.deps.reminders.getNextReminderAt(e);r!=null?this.schedulePersistedWorktreeReminder(n,r):this.deps.reminders.clearResolvedReminderState(e),this.cancel(this.persistedMaintenanceKey(n,"worktree-retention"));let o=Ke(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(n,"worktree-retention"),a+jd,()=>{let d=this.deps.store.getPersistedSession(n);d&&this.reconcileResolvedWorktreeRetention(d,Date.now())})}}reconcileResolvedWorktreeRetention(e,n){let r=Ke(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),o=this.resolvedAtIso(e),i=o?new Date(o).getTime():0,s=this.isLegacyResolvedWorktree(e);if(!(!r.cleanupSafe&&!s||!i||n-i<jd))try{if(!e.worktreePath&&!de(e))return;let a=this.deps.resolveWorktreeRepoDir(e.workdir,e.worktreePath);if(!a)return;let d=de(e)?!1:me(a,e.worktreePath);if(!de(e)&&!d)return;for(let l of ae(e))this.deps.updatePersistedSession(l,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",worktreeLifecycle:{...e.worktreeLifecycle??r.lifecycle,state:r.derivedState,updatedAt:new Date(n).toISOString(),resolvedAt:e.worktreeLifecycle?.resolvedAt??new Date(n).toISOString(),resolutionSource:e.worktreeLifecycle?.resolutionSource??"maintenance",notes:r.reasons}})}catch(a){`${e.worktreePath}${yg(a)}`}}syncActionTokenExpiryDeadline(){let e="tokens:expiry";this.cancel(e);let n=this.deps.store.getNextActionTokenExpiry();n!=null&&this.schedule(e,n,()=>{this.deps.store.purgeExpiredActionTokens(Date.now())})}syncTmpOutputCleanupDeadline(e=Date.now()){this.cancel(zd);let n=this.deps.store.getNextTmpOutputCleanupAt(e);n!=null&&this.schedule(zd,n,()=>{let r=Date.now();this.deps.store.cleanupTmpOutputFiles(r),this.syncTmpOutputCleanupDeadline(r)})}enforcePersistedRetention(){let e=this.deps.store.evictOldestPersisted(this.deps.getMaxPersistedSessions());for(let n of e)this.cancelPersistedMaintenance(n),n.sessionId&&this.cancelRuntimeGc(n.sessionId),this.cleanupOutputPathIfUnreferenced(n.outputPath)}dispose(){this.scheduler.dispose()}persistedMaintenanceRef(e){return e.sessionId??T(e)??e.harnessSessionId}runtimeGcKey(e){return`runtime-gc:${e}`}persistedMaintenanceKey(e,n){return`persisted:${e}:${n}`}runtimeGcMaxAgeMs(){return(E.sessionGcAgeMinutes??1440)*6e4}schedulePersistedWorktreeReminder(e,n){let r=this.persistedMaintenanceKey(e,"worktree-reminder");this.schedule(r,n,()=>{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()+Sg))})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.deps.store.hasOutputPathReference(e)))try{hg(e)}catch{}}resolvedAtIso(e){return e.worktreeLifecycle?.resolvedAt??e.worktreeMergedAt??e.worktreeDismissedAt??(e.completedAt?new Date(e.completedAt).toISOString():void 0)}isLegacyResolvedWorktree(e){return e.worktreeMerged===!0||e.worktreeDisposition==="dismissed"||e.worktreeDisposition==="no-change-cleaned"||e.worktreeState==="merged"||e.worktreeState==="dismissed"}};ar();var Qd=new Set(["completed","failed","killed"]),kg=new Set(["starting","running"]),vg=5e3,ro=class t{registry;sessions;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueue=new ht;pendingAskUserQuestions=new Map;store;metrics;wakeDispatcher;interactions;notifications;worktrees;questions;reminders;lifecycle;restore;stateSync;references;worktreeStrategy;worktreeDecisions;runtimeBootstrap;worktreeMessages;maintenance;constructor(e=20,n=50,r={}){this.maxSessions=e,this.maxPersistedSessions=n;let o=t.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.reminders=o.reminders,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}static createServiceBundle(e,n){let r=new Zr,o=r.sessions,i=new $r(n.store),s=new Dr,a=new Fr,d=new qr(i.actionTokenStore,_e),l=new br(o,i),u=new Pr({store:i,sessions:o,resolveSession:S=>l.resolveActive(S)}),p=new Gr(a,(S,R)=>u.applySessionPatch(S,R),{getPersistedSession:S=>i.getPersistedSession(S)}),c=new Hr,f=new wr(S=>i.getPersistedSession(S)),g=new eo,h=new Ir({shouldRunWorktreeStrategy:S=>e.shouldRunWorktreeStrategy(S),isAlreadyMerged:S=>e.isAlreadyMerged(S),resolveWorktreeRepoDir:(S,R)=>e.resolveWorktreeRepoDir(S,R),getWorktreeCompletionState:(S,R,H,_)=>e.getWorktreeCompletionState(S,R,H,_),updatePersistedSession:(S,R)=>e.updatePersistedSession(S,R),dispatchSessionNotification:(S,R)=>e.dispatchSessionNotification(S,R),getOutputPreview:(S,R)=>e.getOutputPreview(S,R),originThreadLine:S=>e.originThreadLine(S),getWorktreeDecisionButtons:S=>e.getWorktreeDecisionButtons(S),makeOpenPrButton:S=>e.makeActionButton(S,"worktree-create-pr","Open PR"),worktreeSummaryProvider:n.worktreeSummaryProvider,worktreeMessages:g,enqueueMerge:(S,R,H)=>e.enqueueMerge(S,R,H),mergeBranch:Ln,spawnConflictResolver:async({session:S,worktreePath:R,prompt:H})=>e.spawn({prompt:H,workdir:R,name:`${S.name}-conflict-resolver`,harness:S.harnessName||se(),model:S.model,reasoningEffort:S.reasoningEffort,fastMode:S.fastMode,permissionMode:"bypassPermissions",multiTurn:!0,worktreeStrategy:"off",autoMergeParentSessionId:S.id,route:S.route,originChannel:S.originChannel,originThreadId:S.originThreadId,originAgentId:S.originAgentId,originSessionKey:S.originSessionKey},{notifyLaunch:!1}),runAutoPr:async(S,R)=>{let{makeAgentPrTool:H}=await Promise.resolve().then(()=>(dr(),ya));return{success:(await H().execute("auto-pr",{session:S.id,base_branch:R}))?.meta?.success===!0}}}),y=new jr(e.pendingAskUserQuestions,(S,R)=>e.dispatchSessionNotification(S,R),S=>{e.lastWaitingEventTimestamps.delete(S)},(S,R)=>d.getQuestionButtons(S,R)),k=new zr(S=>e.buildRoutingProxy(S),(S,R)=>p.dispatch(S,R),(S,R)=>e.updatePersistedSession(S,R),S=>e.getWorktreeDecisionButtons(S)),b=new no({store:i,sessions:o,reminders:k,removeRuntimeSession:S=>r.remove(S),persistSession:(S,R)=>e.persistSession(S,R),clearRuntimeSessionState:S=>{e.lastWaitingEventTimestamps.delete(S),e.lastTurnCompleteMarkers.delete(S),e.lastTerminalWakeMarkers.delete(S)},resolveWorktreeRepoDir:(S,R)=>e.resolveWorktreeRepoDir(S,R),updatePersistedSession:(S,R)=>e.updatePersistedSession(S,R),getMaxPersistedSessions:()=>e.maxPersistedSessions});i.onActionTokensChanged(()=>e.syncActionTokenExpiryDeadline());let A=new Jr({persistSession:S=>e.persistSession(S),clearWaitingTimestamp:S=>{e.lastWaitingEventTimestamps.delete(S)},handleWorktreeStrategy:S=>e.handleWorktreeStrategy(S),resolveWorktreeRepoDir:(S,R)=>e.resolveWorktreeRepoDir(S,R),updatePersistedSession:(S,R)=>e.updatePersistedSession(S,R),dispatchSessionNotification:(S,R)=>e.dispatchSessionNotification(S,R),notifySession:(S,R,H)=>e.notifySession(S,R,H),clearRetryTimersForSession:S=>a.clearRetryTimersForSession(S),hasTurnCompleteWakeMarker:S=>e.lastTurnCompleteMarkers.has(S),shouldEmitTurnCompleteWake:S=>e.shouldEmitTurnCompleteWake(S),shouldEmitTerminalWake:S=>e.shouldEmitTerminalWake(S),resolvePlanApprovalMode:S=>e.resolvePlanApprovalMode(S),getPlanApprovalButtons:(S,R)=>d.getPlanApprovalButtons(S,R),getResumeButtons:(S,R)=>d.getResumeButtons(S,R),getQuestionButtons:(S,R)=>d.getQuestionButtons(S,R),extractLastOutputLine:S=>e.extractLastOutputLine(S),getOutputPreview:(S,R)=>e.getOutputPreview(S,R),originThreadLine:S=>e.originThreadLine(S),debounceWaitingEvent:S=>e.debounceWaitingEvent(S),isAlreadyMerged:S=>e.isAlreadyMerged(S)}),I=new Yr({getPersistedSession:S=>i.getPersistedSession(S),resolveActiveSession:S=>l.resolveActive(S),resolveWorktreeRepoDir:(S,R)=>e.resolveWorktreeRepoDir(S,R),updatePersistedSession:(S,R)=>e.updatePersistedSession(S,R),dispatchNotification:(S,R)=>p.dispatch(S,R),buildRoutingProxy:S=>e.buildRoutingProxy(S)}),W=new Xr({hydrateSpawnedSession:(S,R,H)=>{f.hydrateSpawnedSession(S,R,H)},markRunning:S=>{i.markRunning(S),e.onPersistedSessionChanged(i.getPersistedSession(S.id))},handleTerminal:async S=>e.onSessionTerminal(S),handleTurnEnd:(S,R)=>A.handleTurnEnd(S,R),formatLaunchWorkdirLabel:S=>e.formatLaunchWorkdirLabel(S),notifySession:(S,R,H)=>e.notifySession(S,R,H)});return{registry:r,sessions:o,store:i,metrics:s,wakeDispatcher:a,interactions:d,notifications:p,worktrees:c,questions:y,reminders:k,lifecycle:A,restore:f,stateSync:u,references:l,worktreeStrategy:h,worktreeDecisions:I,runtimeBootstrap:W,worktreeMessages:g,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,n={}){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.`);if(e.sessionIdOverride){let c=this.registry.get(e.sessionIdOverride);if(c?.status==="starting"||c?.status==="running")throw new Error(`Cannot reuse session ID ${e.sessionIdOverride}: that session is still ${c.status}.`);c&&this.registry.remove(c.id),this.lastWaitingEventTimestamps.delete(e.sessionIdOverride),this.lastTurnCompleteMarkers.delete(e.sessionIdOverride),this.lastTerminalWakeMarkers.delete(e.sessionIdOverride),this.maintenance.cancelRuntimeGc(e.sessionIdOverride)}let o=e.name||Ss(e.prompt),i=this.uniqueName(o);if(i!==o&&`${o}${i}`,!e.route?.provider||!e.route.target)throw new Error(`Cannot launch session "${i}": missing explicit route metadata.`);let s=this.restore.prepareSpawn(e,i),a=e.harness??"claude-code",d=this,l,u=a==="claude-code"&&!e.canUseTool?async(c,f)=>{if(!l)throw new Error("canUseTool called before session ID was set");return d.handleAskUserQuestion(l,f)}:e.canUseTool,p=new qn({...e,workdir:s.actualWorkdir,systemPrompt:s.effectiveSystemPrompt,canUseTool:u},i);return l=p.id,this.registry.add(p),this.metrics.incrementLaunched(),this.runtimeBootstrap.initializeSession(p,s,e,n)}async spawnAndAwaitRunning(e,n={}){let r=this.spawn(e,n);return await this.waitForRunningSession(r),r}async waitForRunningSession(e){if(e.status==="running")return;if(Qd.has(e.status))throw new Error(this.describeLaunchFailure(e));let n=e.on?.bind(e),r=e.off?.bind(e)??e.removeListener?.bind(e);if(!n||!r)throw new Error(`Session ${e.name} [${e.id}] did not expose lifecycle events during startup.`);await new Promise((o,i)=>{let s=(d,l)=>{if(l==="running"){a(),o();return}Qd.has(l)&&(a(),i(new Error(this.describeLaunchFailure(e))))},a=()=>{r("statusChange",s)};n("statusChange",s)})}describeLaunchFailure(e){let n=e.killReason?` (reason: ${e.killReason})`:"",r=e.error||e.result?.result||`status=${e.status}${n}`;return`Session ${e.name} [${e.id}] failed to start: ${r}`}formatLaunchResult(e,n){return Xt({prompt:e.prompt,workdir:e.workdir,harness:e.harness,permissionMode:e.permissionMode??E.permissionMode,planApproval:e.planApproval,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,forceNewSession:e.forceNewSession,clearedPersistedCodexResume:e.clearedPersistedCodexResume},n)}shouldRunWorktreeStrategy(e){let n=e.lifecycle;return!(n==="starting"||n==="awaiting_plan_decision"||n==="awaiting_user_input"||e.pendingPlanApproval)}makeActionButton(e,n,r,o={}){return this.interactions.makeActionButton(e,n,r,o)}consumeActionToken(e){return this.interactions.consumeActionToken(e)}getActionToken(e){return this.interactions.getActionToken(e)}clearPlanDecisionTokens(e,n){this.interactions.clearPlanDecisionTokens(e,n)}isCurrentPendingPlanDecision(e,n){let r=this.resolve(e)??this.getPersistedSession(e);return Yt(r,n)}dispatchPlanApprovalFallback(e,n,r){let o=new Date().toISOString();this.notifications.dispatch(e,{label:"plan-approval-fallback",idempotencyKey:`plan-approval:${e.id}:v${n??"unknown"}:fallback`,userMessage:jt({session:e,summary:r}),notifyUser:"always",shouldDispatch:()=>this.isCurrentPendingPlanDecision(e.id,n),hooks:{onNotifyStarted:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,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:n,approvalPromptVersion:n,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:St(e,n,!0),wakeMessageOnNotifyFailed:Qr({session:e,planDecisionVersion:n})})}getWorktreeDecisionButtons(e,n={}){let r=this.resolve(e)??this.getPersistedSession(e);if(!(!r||r.worktreeStrategy==="delegate"&&n.allowDelegate!==!0))return this.interactions.getWorktreeDecisionButtons(e,r)}getWorktreeCompletionState(e,n,r,o){return this.worktrees.getCompletionState(e,n,r,o)}notifyWorktreeOutcome(e,n,r){this.notifications.notifyWorktreeOutcome(e,n,r)}requestPlanApprovalFromUser(e,n){let r=n.trim();if(!r)return"Error: summary must not be empty.";let o=ki(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 d=N(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 l=a.actionablePlanDecisionVersion??a.planDecisionVersion;if(Jt(a,l))return[`An actionable plan review prompt already exists for session ${a.name} [${d}].`,"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} [${d}].`,"Wait for delivery to finish before retrying."].join(" ");let u=this.interactions.getPlanApprovalButtons(d,{...a,planDecisionVersion:l}),p=[`đ [${a.name}] Plan v${l??"?"} needs your decision:`,"","Why this was escalated:","",o,"","Choose Approve, Revise, or Reject below."].join(`
|
|
241
|
+
`);return this.notifications.dispatch(this.buildRoutingProxy({id:d,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:${d}:v${l??"unknown"}:canonical`,userMessage:p,notifyUser:"always",buttons:u,hooks:{onNotifyStarted:()=>{this.updatePersistedSession(d,{approvalPromptRequiredVersion:l,approvalPromptStatus:"sending",approvalPromptVersion:l,approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.updatePersistedSession(d,{canonicalPlanPromptVersion:l,approvalPromptRequiredVersion:l,approvalPromptVersion:l,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.updatePersistedSession(d,{approvalPromptRequiredVersion:l,approvalPromptVersion:l,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},shouldDispatch:()=>this.isCurrentPendingPlanDecision(d,l),onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(this.buildRoutingProxy({id:d,name:a.name,sessionId:s?.sessionId,harnessSessionId:i?.harnessSessionId??s?.harnessSessionId,backendRef:i?.backendRef??s?.backendRef,route:i?.route??s?.route}),l,o),wakeMessageOnNotifySuccess:St({id:d,name:a.name},l)}),[`Canonical plan approval prompt sent for session ${a.name} [${d}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ")}requestWorktreeDecisionFromUser(e,n){let r=n.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 l=N(o??i??{id:e})??e,u=o?.worktreePath??i?.worktreePath,p=o?.worktreeBranch??i?.worktreeBranch,c=this.resolveWorktreeRepoDir(o?.originalWorkdir??i?.workdir,u);if(!u)return`Error: Session "${e}" has no managed worktree path.`;if(!p)return`Error: Session "${e}" has no managed worktree branch.`;if(!c)return`Error: Session "${e}" has no resolvable repository root for worktree ${u}.`;let f=o?.worktreeBaseBranch??i?.worktreeBaseBranch??Pe(c),g=Ie(c,p,f);if(!g)return`Error: Could not compute worktree diff summary for session "${e}".`;let h=this.getWorktreeDecisionButtons(l,{allowDelegate:!0});if(!h||h.length===0)return`Error: Could not create worktree decision buttons for session "${e}".`;let y=r.split(/\r?\n/).map(k=>k.replace(/^[-*]\s+/,"").trim()).filter(k=>k.length>0);return this.notifications.dispatch(this.buildRoutingProxy({id:l,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:l,name:s.name,worktreePrTargetRepo:o?.worktreePrTargetRepo??i?.worktreePrTargetRepo},branchName:p,baseBranch:f,diffSummary:g,summaryLines:y,buttons:h})),[`Canonical worktree decision prompt sent for session ${s.name} [${l}].`,"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:N(e)??T(e)??e.harnessSessionId??"unknown-session",name:e.name,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef?{...e.backendRef}:void 0,route:e.route}}resolveWorktreeRepoDir(e,n){return e&&(!n||!vr(e,n))||!n?e:Dn(n)??e}formatLaunchWorkdirLabel(e){if(!e.worktreePath)return e.workdir;let n=this.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath);return!n||n===e.worktreePath?e.worktreePath:`${e.worktreePath} (worktree of ${n})`}async dismissWorktree(e){return this.worktreeDecisions.dismissWorktree(e)}snoozeWorktreeDecision(e,n){return this.worktreeDecisions.snoozeWorktreeDecision(e,n)}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.lastWaitingEventTimestamps.delete(e.id),this.wakeDispatcher.clearRetryTimersForSession(e.id);let n=e.autoMergeParentSessionId;if(!n)return;let r=this.resolve(n),o=this.getPersistedSession(n),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}${n}`;return}if(e.status==="completed"&&r){this.updatePersistedSession(n,{autoMergeResolverSessionId:void 0}),await this.handleWorktreeStrategy(r);return}let s=r?.worktreeBranch??o?.worktreeBranch??"unknown",a=r?.worktreePath??o?.worktreePath??"(unknown worktree)",d=r?.worktreeBaseBranch??o?.worktreeBaseBranch,l=r?.worktreePrTargetRepo??o?.worktreePrTargetRepo,u=r?.worktreePushRemote??o?.worktreePushRemote;this.updatePersistedSession(n,ir({worktreeBaseBranch:d,worktreePrTargetRepo:l,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:${n}:${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(`
|
|
242
|
+
`),buttons:[[this.makeActionButton(n,"worktree-create-pr","Open PR")]]})}persistSession(e,n={}){let r=n.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()}getMetrics(){return this.metrics.getMetrics()}notifySession(e,n,r="notification"){this.dispatchSessionNotification(e,{label:r,idempotencyKey:r==="agent-respond"?void 0:`notify:${e.id}:${r}:${n}`,userMessage:n,notifyUser:"always"})}sendPlanOffer(e){let n=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:n})}emitGoalTaskUpdate(e,n,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(l=>!!l).join(`
|
|
243
|
+
`),d=l=>pi({sessionId:o,sessionName:e.sessionName,taskName:e.name,summary:n,originThreadLine:vt(i),canonicalStatusDelivered:l});this.dispatchSessionNotification(i,{label:r,idempotencyKey:`goal:${e.id}:${r}:${s?"success":n}`,userMessage:s?a:n,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?d(!0):void 0,wakeMessageOnNotifyFailed:s?d(!1):void 0})}launchPlanOffer(e){let n=e.route??{provider:"system",target:"system"};return this.spawn({prompt:e.prompt,workdir:e.workdir,name:e.name,harness:se(),permissionMode:"plan",planApproval:"ask",worktreeStrategy:e.worktreeStrategy??"off",multiTurn:!0,route:n,originChannel:this.originChannelFromRoute(n),originThreadId:n.threadId,originSessionKey:n.sessionKey})}dispatchSessionNotification(e,n){this.notifications.dispatch(e,n)}originChannelFromRoute(e){return e.accountId?`${e.provider}|${e.accountId}|${e.target}`:`${e.provider}|${e.target}`}debounceWaitingEvent(e){let n=Date.now(),r=this.lastWaitingEventTimestamps.get(e);return r&&n-r<vg?!1:(this.lastWaitingEventTimestamps.set(e,n),!0)}originThreadLine(e){return vt(e)}extractLastOutputLine(e){return e.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(e,n=1e3){return Gd(e,n)}resolvePlanApprovalMode(e){return e.planApproval??E.planApproval??"delegate"}shouldEmitTurnCompleteWake(e){let n=`${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(e.id)===n?(`${e.id}${n}`,!1):(this.lastTurnCompleteMarkers.set(e.id,n),!0)}shouldEmitTerminalWake(e){let n=`${e.status}|${e.completedAt??0}|${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.killReason}`;return this.lastTerminalWakeMarkers.get(e.id)===n?!1:(this.lastTerminalWakeMarkers.set(e.id,n),!0)}resolve(e){return this.references.resolveActive(e)}get(e){return this.registry.get(e)}list(e){let n=this.registry.list();return e&&e!=="all"&&(n=n.filter(r=>r.status===e)),n.sort((r,o)=>o.startedAt-r.startedAt)}kill(e,n){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(n??"user"),!0}killAll(e="user"){for(let n of this.sessions.values())kg.has(n.status)&&this.kill(n.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 n=this.store.getPersistedSession(e);return n?.worktreeMerged===!0||n?.worktreeLifecycle?.state==="merged"||n?.worktreeLifecycle?.state==="released"}async enqueueMerge(e,n,r){return this.mergeQueue.enqueue(e,n,r)}updatePersistedSession(e,n){let r=this.stateSync.applySessionPatch(e,n);return r&&this.onPersistedSessionChanged(this.store.getPersistedSession(e)),r}listPersistedSessions(){return this.store.listPersistedSessions()}async handleAskUserQuestion(e,n){let r=this.sessions.get(e);if(!r)throw new Error(`Session "${e}" not found for AskUserQuestion intercept`);return this.questions.handleAskUserQuestion(r,n)}resolveAskUserQuestion(e,n){this.questions.resolveAskUserQuestion(e,n)}async resolvePendingInputOption(e,n){let r=this.sessions.get(e);return r&&await r.submitPendingInputOption(n)?(this.lastWaitingEventTimestamps.delete(e),!0):(this.questions.resolveAskUserQuestion(e,n),!0)}dispose(){this.disposeMaintenance(),this.questions.dispose(),this.notifications.dispose()}};O();te();import{definePluginEntry as Jd}from"openclaw/plugin-sdk/plugin-entry";function Rg(t){let e=parseInt(process.env.OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS??"168",10)||168,n=e*60*60*1e3,r=Date.now()-n,o=new Set(t.listPersistedSessions().map(d=>d.worktreePath).filter(d=>typeof d=="string"&&d.length>0)),i=new Set,s=process.env.OPENCLAW_WORKTREE_DIR??E.worktreeDir;if(s)i.add(s);else for(let d of t.listPersistedSessions())if(d.workdir)try{let l=Ag("git",["rev-parse","--show-toplevel"],{cwd:d.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();l&&i.add(Yd(l,".worktrees"))}catch{}if(i.size===0)return;let a=0;for(let d of i)try{let l=wg(d);for(let u of l){if(!u.startsWith("openclaw-worktree-"))continue;let p=Yd(d,u);try{let c=Pg(p);if(!c.isDirectory()||c.mtimeMs>r||o.has(p))continue;bg(p,{recursive:!0,force:!0}),a++}catch(c){`${p}${c instanceof Error?c.message:String(c)}`}}}catch{}a>0&&`${a}${e}`}function Ig(t){let e=null,n=null,r=!1,o=!1,i=t.registerTool;ot(t.runtime);let s=p=>{if(r){p&&!o&&(ot(t.runtime,p.config),o=!0);return}let c=t.pluginConfig??{};Wi(c),p?(ot(t.runtime,p.config),o=!0):(ot(t.runtime),o=!1),e=new ro(E.maxSessions,E.maxPersistedSessions,{worktreeSummaryProvider:yd()}),n=new kr(e),ao(e),lo(n),n.start(),Rg(e),e.bootstrapMaintenanceSchedules(),r=!0},a=()=>{n&&n.stop(),e&&e.killAll("shutdown"),e&&e.dispose(),n=null,e=null,r=!1,o=!1,ot(void 0),lo(null),ao(null)},d=(p,c)=>{i(f=>(s(),p(f)),c)},l={...t,registerCommand(p){t.registerCommand({...p,handler:c=>(s(),p.handler(c))})}},u=p=>{let c=Ea(p);t.registerInteractiveHandler({...c,handler:async f=>(s(),c.handler(f))})};d(p=>Rs(p),{optional:!1,name:"agent_launch"}),d(p=>Zs(p),{optional:!1,name:"agent_sessions"}),d(p=>Xs(p),{optional:!1,name:"agent_kill"}),d(p=>Hn(p),{optional:!1,name:"agent_output"}),d(p=>ia(p),{optional:!1,name:"agent_respond"}),d(p=>sa(p),{optional:!1,name:"agent_request_plan_approval"}),d(p=>aa(p),{optional:!1,name:"agent_request_worktree_decision"}),d(p=>la(p),{optional:!1,name:"agent_send_plan_offer"}),d(p=>ua(p),{optional:!1,name:"agent_stats"}),d(p=>er(p),{optional:!1,name:"agent_merge"}),d(p=>Vt(p),{optional:!1,name:"agent_pr"}),d(p=>ka(p),{optional:!1,name:"agent_worktree_cleanup"}),d(p=>va(p),{optional:!1,name:"agent_worktree_status"}),d(p=>wa(p),{optional:!1,name:"goal_launch"}),d(p=>ba(p),{optional:!1,name:"goal_status"}),d(p=>Aa(p),{optional:!1,name:"goal_stop"}),d(p=>Ra(p),{optional:!1,name:"goal_edit"}),u("telegram"),u("discord"),Da(l),Oa(l),Na(l),Wa(l),La(l),Ba(l),qa(l),Ka(l),Ua(l),Ga(l),t.registerService({id:"openclaw-code-agent",start:s,stop:a})}var BA=Jd({id:"openclaw-code-agent",name:"OpenClaw Code Agent",description:"Multi-session coding-agent orchestration from OpenClaw chat",register:Ig});export{BA as default,Ig as register};
|