openclaw-code-agent 4.3.5 → 4.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,35 +1,35 @@
1
- var tw=Object.defineProperty;var Be=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ct=(t,e)=>{for(var r in e)tw(t,r,{get:e[r],enumerable:!0})};function Po(t,e){return e?{...e,...t}:t}function rw(t){return{...t,[qu]:!0}}function nw(t){return{const:t,type:typeof t}}var qu,f,tt=Be(()=>{qu=Symbol("optionalSchema");f={Object(t,e){let r=Object.entries(t).filter(([,o])=>!o[qu]).map(([o])=>o),n=Object.fromEntries(Object.entries(t).map(([o,i])=>{let{[qu]:a,...u}=i;return[o,u]}));return{...e,type:"object",...r.length>0?{required:r}:{},properties:n}},String(t){return Po({type:"string"},t)},Number(t){return Po({type:"number"},t)},Boolean(t){return Po({type:"boolean"},t)},Array(t,e){return Po({type:"array",items:t},e)},Literal:nw,Union(t,e){return Po({anyOf:t},e)},Optional:rw}});function Bu(t){k=t}function Uu(t){Ce=t}var k,Ce,le=Be(()=>{k=null,Ce=null});function Sm(t){let e=t.chatId.trim(),r=t.topicId.trim();return!/^-?\d+$/.test(e)||!/^\d+$/.test(r)?null:`${e}:topic:${r}`}function uw(t){let e=t.conversationId.trim(),r=e.match(/^(-?\d+):topic:(\d+)$/i);if(r?.[1]&&r[2]){let i=Sm({chatId:r[1],topicId:r[2]});return i?{chatId:r[1],topicId:r[2],canonicalConversationId:i}:null}if(!/^\d+$/.test(e))return null;let n=t.parentConversationId?.trim();if(!n||!/^-?\d+$/.test(n))return null;let o=Sm({chatId:n,topicId:e});return o?{chatId:n,topicId:e,canonicalConversationId:o}:null}function pw(t){if(!t)return;let e=t.match(/^agent:[^:]+:discord:(direct|dm|channel|group):/i);if(!e?.[1])return;let r=e[1].toLowerCase();return r==="direct"||r==="dm"?"user":"channel"}function dw(t,e){if(!/^\d+$/.test(t))return t;let r=pw(e);return r?`${r}:${t}`:`channel:${t}`}function lw(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 mw(t){let e=t.toLowerCase(),r=[":thread:",":topic:"];for(let n of r){let o=e.lastIndexOf(n);if(o===-1)continue;let i=t.slice(0,o).trim(),a=t.slice(o+n.length).trim()||void 0;return{id:i||t,threadId:a}}return{id:t}}function cw(t){let e=t?.trim();if(!e)return;let r=e.split(":").filter(Boolean);if(r[0]?.trim().toLowerCase()==="agent")for(let n=2;n<=r.length-3;n+=1){let o=r[n]?.trim().toLowerCase();if(!o||!aw.has(o))continue;let i=r[n+1]?.trim().toLowerCase(),a=r.slice(n+2).join(":").trim();if(!(!i||!a))return{provider:o,kind:i,rawId:a}}}function fw(t,e=uw){try{return e({conversationId:t})}catch{return null}}function Wu(t){return{provider:"system",target:"system",sessionKey:t?.trim()||void 0}}function Ku(t,e){return{...t,threadId:e??t.threadId}}function hw(t,e,r){return t==="telegram"&&r?.provider==="telegram"&&!!r.target&&e!==r.target}function yw(t){let e=t?.trim();if(!e)return;let r=cw(e);if(!r)return;let{provider:n,kind:o,rawId:i}=r,a=mw(i),u=null;if(n==="telegram")try{u=gw.safeParseTelegramTopicConversation(i)}catch{u=null}let p=u?.chatId??a.id,d=u?.topicId??a.threadId,l=n==="discord"?o==="direct"||o==="dm"?`user:${p}`:`channel:${p}`:p;return{provider:n,target:l,threadId:d,sessionKey:e}}function ju(t){let e=t?.match(/:topic:(\d+)$/);return e?parseInt(e[1],10):void 0}function km(t){return!!(t?.provider&&t.target&&t.provider!=="system"&&t.target!=="system")}function wo(t,e,r){let n=yw(r),o=e!=null?String(e):void 0,i=t?.trim();if(!i||i.toLowerCase()==="unknown")return n?Ku(n,o):Wu(r);let a=i.split("|").map(y=>y.trim());if(a.length<2)return n?Ku(n,o):Wu(r);let[u,p,d]=a,l=a.length>=3?d:p,m=a.length>=3?p:void 0,c=u?.toLowerCase();if(!c||!l)return n?Ku(n,o):Wu(r);let h=c==="discord"?dw(l,r):l;return hw(c,h,n)?{provider:c,accountId:m,target:n.target,threadId:o??n.threadId,sessionKey:r?.trim()||void 0}:{provider:c,accountId:m,target:h,threadId:o??(n?.provider===c?n.threadId:void 0),sessionKey:r?.trim()||void 0}}function en(t){return wo(lw(t.route)??t.originChannel,t.route?.threadId??t.originThreadId,t.route?.sessionKey??t.originSessionKey)??t.route}function $i(t){let e=en(t);return km(e)?e:void 0}function Sw(t){return Object.fromEntries(Object.entries(t).filter(e=>!!e[1]))}function Mi(t){let e=en(t);if(!km(e))return"";let r=Sw({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(r).length===0?"":["Session origin route (authoritative for human follow-ups):",`originRoute: ${JSON.stringify(r)}`,"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 aw,gw,ir=Be(()=>{aw=new Set(["telegram","discord","slack","system","mattermost","feishu","line","whatsapp","signal","matrix","googlechat","bluebubbles","imessage","msteams"]);gw={safeParseTelegramTopicConversation:fw}});import{readFileSync as kw}from"fs";import{homedir as Iw}from"os";import{join as xw}from"path";function xm(){if(vo!==void 0)return vo;try{let t=kw(xw(Iw(),".claude.json"),"utf-8");vo=JSON.parse(t).mcpServers??{}}catch{vo={}}return vo}function Pm(t){let e=t.defaultHarness??Im,r={};for(let[n,o]of Object.entries(Oi))r[n]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[n,o]of Object.entries(t.harnesses??{})){let i=r[n]??{},a={...i,defaultModel:o.defaultModel??i.defaultModel,reasoningEffort:o.reasoningEffort??i.reasoningEffort,fastMode:o.fastMode??i.fastMode};o.allowedModels!==void 0?a.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(a.allowedModels=void 0),r[n]=a}if(t.defaultModel!==void 0){let n=r[e]??{};r[e]={...n,defaultModel:t.harnesses?.[e]?.defaultModel??t.defaultModel,allowedModels:t.harnesses?.[e]?.allowedModels!==void 0?n.allowedModels:t.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${e}.defaultModel instead.`)}if(t.model!==void 0){let n=r.codex??{};r.codex={...n,defaultModel:t.harnesses?.codex?.defaultModel??t.model,allowedModels:t.harnesses?.codex?.allowedModels!==void 0?n.allowedModels:t.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(t.reasoningEffort!==void 0){let n=r.codex??{};r.codex={...n,reasoningEffort:t.harnesses?.codex?.reasoningEffort??t.reasoningEffort},console.warn("[openclaw-code-agent] config.reasoningEffort is deprecated; use harnesses.codex.reasoningEffort instead.")}if(t.allowedModels!==void 0){console.warn("[openclaw-code-agent] config.allowedModels is deprecated; use harnesses.<name>.allowedModels instead.");for(let[n,o]of Object.entries(r))t.harnesses?.[n]?.allowedModels===void 0&&(r[n]={...o,allowedModels:void 0})}K={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:r,allowedModels:t.allowedModels,defaultWorktreeStrategy:t.defaultWorktreeStrategy??"delegate",worktreeDir:t.worktreeDir}}function dt(){return K.defaultHarness??Im}function Hu(t){let e=Oi[t],r=K.harnesses[t];return{...e,...r,allowedModels:r?.allowedModels??e?.allowedModels}}function $n(t){return Hu(t).defaultModel}function _i(t){return K.harnesses[t]?.allowedModels??K.allowedModels}function Ir(t){return Hu(t).reasoningEffort}function Mn(t){return t==="codex"?Hu(t).fastMode:void 0}function zt(t){return t==null?void 0:String(t).trim()||void 0}function zu(t){return{channel:zt(t?.deliveryContext?.channel),to:zt(t?.deliveryContext?.to),accountId:zt(t?.deliveryContext?.accountId),threadId:zt(t?.deliveryContext?.threadId)}}function wm(t,e,r){if(!(!t||!e))return r?`${t}|${r}|${e}`:`${t}|${e}`}function Gu(t){return zt(t?.requesterSenderId??t?.senderId)}function Vu(t){return(zt(t.deliveryContext?.channel)??t.messageChannel??t.channel)?.toLowerCase()!=="telegram"?!1:!!ju(t.sessionKey)}function Di(t){let e=zu(t),r=wm(e.channel,e.to,e.accountId);if(r)return r;if(t.messageChannel){let n=t.messageChannel.split("|");if(n.length>=3)return t.messageChannel;if(t.agentAccountId&&n.length>=2)return`${n[0]}|${t.agentAccountId}|${n.slice(1).join("|")}`;let o=zt(t.chatId);if(n.length===1&&o)return`${n[0]}|${o}`;let i=Gu(t);if(n.length===1&&i&&!Vu(t))return`${n[0]}|${i}`}if(t.workspaceDir){let n=Ao(t.workspaceDir);if(n)return n}if(t.messageChannel&&t.messageChannel.includes("|"))return t.messageChannel}function bo(t,e){if(e&&String(e).includes("|"))return String(e);let r=zu(t),n=wm(r.channel,r.to,r.accountId);if(n)return n;if(t?.channelId&&String(t.channelId).includes("|"))return String(t.channelId);if(t?.messageChannel){let u=String(t.messageChannel);if(u.includes("|"))return u;let p=zt(t.chatId);if(p)return`${u}|${p}`;let d=Gu(t);if(d&&!Vu(t))return`${u}|${d}`}let o=zt(t?.channel),i=zt(t?.chatId);if(o&&i)return`${o}|${i}`;let a=Gu(t);return o&&a&&!Vu(t)?`${o}|${a}`:t?.id&&/^-?\d+$/.test(String(t.id))?`telegram|${t.id}`:K.fallbackChannel??"unknown"}function Ju(t){return zu(t).threadId??t?.messageThreadId??void 0}function On(t,e,r){return wo(bo(t,e),Ju(t),r??t?.sessionKey)}function Ao(t){let e=K.agentChannels;if(!e)return;let r=i=>i.replace(/\/+$/,""),n=r(t),o=Object.entries(e).sort((i,a)=>a[0].length-i[0].length);for(let[i,a]of o)if(n===r(i)||n.startsWith(r(i)+"/"))return a}function vm(t){return ju(t)}var vo,Im,Oi,K,ze=Be(()=>{ir();Im="claude-code",Oi={"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"}};K={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"delegate",defaultWorktreeStrategy:"delegate",harnesses:{"claude-code":{...Oi["claude-code"]},codex:{...Oi.codex}}}});function Li(t){return{type:"backend_ref",ref:t}}function Fi(t){return{type:"run_started",...t?{runId:t}:{}}}function To(t){return{type:"text_delta",text:t}}function bm(t,e){return{type:"tool_call",name:t,input:e}}function Ni(t){return{type:"pending_input",state:t}}function Ln(t){return t?{type:"pending_input_resolved",requestId:t}:{type:"pending_input_resolved"}}function qi(t,e){return{type:"plan_artifact",artifact:t,finalized:e}}function Bi(t){return t?{type:"settings_changed",permissionMode:t}:{type:"settings_changed"}}function tn(t){return{type:"run_completed",data:t}}var Dn,Qu=Be(()=>{Dn=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(r=>{e.resolvePending=r})}})()}}});import*as Wi from"@anthropic-ai/claude-agent-sdk";function Pw(t){if(typeof t.result=="string"&&t.result.length>0)return t.result;if(Array.isArray(t.errors)){let e=t.errors.filter(r=>typeof r=="string"&&r.length>0);if(e.length>0)return e.join(`
3
- `)}}function ww(t,e,r){let o=(Array.isArray(r.questions)?r.questions:[])[0]??{},i=typeof o.question=="string"?o.question:void 0,a=Array.isArray(o.options)?o.options.map(u=>{if(!u||typeof u!="object")return"";let p=u.label;return typeof p=="string"?p:""}).filter(Boolean):[];return{requestId:`${t||"claude"}-ask-${e}`,kind:"question",promptText:i,options:a,allowsFreeText:a.length===0||o.multiSelect===!0}}var Ui,Am=Be(()=>{Qu();Ui=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 r=new Dn,n=!1,o="",i=!1,a=0,u=e.resumeSessionId??"",p=e.canUseTool,d={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,...p?{canUseTool:async(y,S)=>{if(y!=="AskUserQuestion")return{behavior:"allow"};let I=ww(u,++a,S);r.enqueue(Ni(I));try{let x=await p(y,S);return r.enqueue(Ln(I.requestId)),x}catch(x){throw r.enqueue(Ln(I.requestId)),x}}}:{}};e.resumeSessionId&&(d.resume=e.resumeSessionId,d.forkSession=e.forkSession??!1);let l=e.prompt,m=this.deps.query??Wi.query,c=this.deps.startup??Wi.startup,h=(async()=>{if(typeof c!="function")return m({prompt:l,options:d});let y=await c({options:d});try{return y.query(l)}catch(S){throw await y.close?.(),S}})();return(async()=>{try{let y=await h;for await(let S of y){let I=S;if(I.type==="system"&&I.subtype==="init"){u=I.session_id??u,r.enqueue(Li({kind:"claude-code",conversationId:u}));continue}if(I.type==="system"&&I.subtype==="status"&&I.permissionMode){r.enqueue(Bi(I.permissionMode));continue}if(I.type==="assistant"){n||(n=!0,r.enqueue(Fi()));for(let x of I.message?.content??[]){if(x.type==="text"){o+=o?`
4
- ${x.text}`:x.text,r.enqueue(To(x.text));continue}x.type==="tool_use"&&((x.name==="ExitPlanMode"||x.name==="set_permission_mode")&&(i=!0),x.name!=="AskUserQuestion"&&r.enqueue(bm(x.name,x.input)))}continue}if(I.type==="result"){let x=o.trim();if(x&&(e.permissionMode==="plan"||i)){let R={explanation:void 0,steps:[],markdown:x};r.enqueue(qi(R,!0))}r.enqueue(tn({success:I.subtype==="success",duration_ms:I.duration_ms??0,total_cost_usd:I.total_cost_usd??0,num_turns:I.num_turns??0,result:Pw(I),session_id:I.session_id??u})),o="",i=!1,n=!1}}}finally{r.close()}})().catch(y=>{r.enqueue(tn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,result:y instanceof Error?y.message:String(y),session_id:u})),r.close()}),{messages:r.messages(),async setPermissionMode(y){let S=await h;typeof S.setPermissionMode=="function"&&await S.setPermissionMode(y)},async streamInput(y){let S=await h;typeof S.streamInput=="function"&&await S.streamInput(y)},async interrupt(){let y=await h;typeof y.interrupt=="function"&&await y.interrupt()}}}buildUserMessage(e,r){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:r}}}});import{spawn as vw}from"node:child_process";import bw from"node:readline";function Aw(t){return t instanceof Error?t.message:String(t)}function Tw(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}async function Rw(t,e){if(t.id!=null&&(Object.hasOwn(t,"result")||Object.hasOwn(t,"error"))){let n=String(t.id),o=e.pending.get(n);if(!o)return;if(clearTimeout(o.timer),e.pending.delete(n),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 r=t.method?.trim();if(r){if(t.id==null){await e.onNotification(r,t.params);return}try{let n=await e.onRequest(r,t.params);e.respond({jsonrpc:"2.0",id:t.id,result:n??{}})}catch(n){e.respond({jsonrpc:"2.0",id:t.id,error:{code:-32603,message:Aw(n)}})}}}var Ki,Tm=Be(()=>{Ki=class{constructor(e,r,n){this.command=e;this.args=r;this.requestTimeoutMs=n}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=vw(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,bw.createInterface({input:e.stdout}).on("line",n=>{this.handleLine(n)}),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,r){this.write({jsonrpc:"2.0",method:e,params:r??{}})}async request(e,r,n){let o=`rpc-${++this.counter}`,i=new Promise((a,u)=>{let p=setTimeout(()=>{this.pending.delete(o),u(new Error(`codex app server timeout: ${e}`))},Math.max(100,n??this.requestTimeoutMs));p.unref?.(),this.pending.set(o,{resolve:a,reject:u,timer:p})});return this.write({jsonrpc:"2.0",id:o,method:e,params:r??{}}),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 r=Tw(e);r&&await Rw(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 me(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function we(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 Cw(t){return t instanceof Error?t.message:String(t)}function Rm(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=me(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 Ro(t){let e=me(t);if(!e)return{};let r=me(e.thread)??me(e.session),n=me(e.turn)??me(e.run),o=me(e.item),i=me(e.serverRequest);return{threadId:we(e,["threadId","thread_id","conversationId","conversation_id"])??we(r,["id","threadId","thread_id","conversationId"]),runId:we(e,["turnId","turn_id","runId","run_id"])??we(n,["id","turnId","turn_id","runId","run_id"]),requestId:we(e,["requestId","request_id","serverRequestId"])??we(i,["id","requestId","request_id"]),itemId:we(e,["itemId","item_id"])??we(o,["id","itemId","item_id"])}}function ji(t,e,r=0){if(r>6)return;if(Array.isArray(t)){for(let i of t){let a=ji(i,e,r+1);if(a)return a}return}let n=me(t);if(!n)return;let o=we(n,e);if(o)return o;for(let i of Object.values(n)){let a=ji(i,e,r+1);if(a)return a}}function Co(t){return{threadId:Ro(t).threadId,cwd:ji(t,["cwd","workdir","directory"])}}function Cm(t){let e=t?.trim();return!!(e&&/[/\\]worktrees[/\\][^/\\]+[/\\][^/\\]+/.test(e))}function Em(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 Gi(t){let e=me(t);if(!e)return;let r=me(e.item)??e;return we(r,["id","itemId","item_id","messageId","message_id"])}function Ew(t,e=!1){let r=me(t);if(!r)return"";let n=me(r.item)??r;return we(n,["type"])?.toLowerCase()!=="agentmessage"?"":e?xr(n):we(n,["text"],{trim:!1})??xr(n)}function $m(t,e){let r=t.trim().toLowerCase();return r==="item/agentmessage/delta"?{mode:"delta",text:xr(e),itemId:Gi(e)}:r==="item/completed"?{mode:"snapshot",text:Ew(e),itemId:Gi(e)}:{mode:"ignore",text:""}}function Mm(t){return{itemId:Gi(t),delta:xr(t)}}function Om(t){let e=me(t),r=me(e?.plan),o=(Array.isArray(e?.plan)?e.plan:Array.isArray(r?.steps)?r.steps:[]).map(i=>{let a=me(i),u=we(a,["step","title","text"]);if(!u)return null;let p=we(a,["status"])?.toLowerCase()??"pending";return{step:u,status:p==="inprogress"||p==="in_progress"?"inProgress":p==="completed"?"completed":"pending"}}).filter(Boolean);return{explanation:we(r,["explanation"])??we(e,["explanation"]),steps:o}}function _m(t){let e=me(t);if(!e)return{};let r=me(e.item)??e;return we(r,["type"])?.toLowerCase()!=="plan"?{}:{itemId:Gi(r),text:we(r,["text"],{trim:!1})??xr(r)}}function Dm(t,e){let r=t.trim().toLowerCase();if(r==="turn/failed")return"failed";if(r==="turn/cancelled")return"interrupted";let n=me(e)??{},o=me(n.turn)??n,i=we(o,["status"])?.toLowerCase();return i==="failed"?"failed":i==="interrupted"||i==="cancelled"?"interrupted":"completed"}function Lm(t,e){let r=me(e)??{},n=me(r.turn)??r,o=me(n.error)??me(r.error);if(o)return we(o,["message","text","summary","reason"])}function $w(t,e){let r=Cw(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 Ow(t){return Mw.has(t.trim().toLowerCase())}function _w(t){let e=me(t);return e?!!we(e,["threadId","thread_id"]):!1}async function Eo(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(Ow(r)&&!_w(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,!$w(o,r))continue}}throw e instanceof Error?e:new Error(String(e))}function Fm(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 Nm(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 Dw(t){return[{type:"text",text:t}]}function Lw(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 qm(t){let e={threadId:t.threadId,input:Dw(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=Lw(t.permissionMode??"default",t.model,t.reasoningEffort,t.systemPrompt);return r?[{...e,collaborationMode:r}]:[e]}function Bm(t){return[{threadId:t.threadId,turnId:t.turnId}]}function Fw(t){let e=me(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():we(me(n),["label","title","text","value","name","id"])??"").filter(Boolean):[]}function Nw(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 Um(t,e,r){let n=t.trim().toLowerCase(),o=Fw(r),i=ji(r,["question","prompt","message","text","summary","reason"])??void 0,a=n.includes("requestapproval"),u=a?o.map(p=>({kind:"approval",label:p,decision:Nw(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 Wm(t){let e=t.trim().toLowerCase();return e.includes("requestuserinput")||e.includes("requestapproval")}function Yu(t,e){let r=t==="bypassPermissions"?"never":e?.trim()||"never";return{approvalPolicy:r,sandbox:r==="never"?"danger-full-access":void 0}}var Mw,Km=Be(()=>{Mw=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function jm(t){return t instanceof Error?t.message:String(t)}function Kw(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 qw,rn,Bw,Uw,Ww,Vi,Gm=Be(()=>{Tm();Qu();Km();qw="1.0",rn=6e4,Bw="OPENCLAW_CODEX_APP_SERVER_COMMAND",Uw="OPENCLAW_CODEX_APP_SERVER_ARGS",Ww="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";Vi=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[Bw]?.trim()||"codex",args:Rm(process.env[Uw]),requestTimeoutMs:Number.parseInt(process.env[Ww]??String(rn),10)||rn},n=this.deps.createClient?.(r)??new Ki(r.command,r.args,r.requestTimeoutMs),o=new Dn,i=e.resumeSessionId,a,u=e.backendRef?.worktreePath,p=e.backendRef?.worktreeId,d=e.permissionMode??"default",l,m=0,c="",h=[],y,S=new Map,I=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&&Cm(j)&&(u=j,p=Em(j))},R=()=>{i&&o.enqueue(Li({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(),Re=Ro(j),Lt=Co(j);if(Re.threadId&&i&&Re.threadId!==i)return;if(Re.threadId&&(i=Re.threadId),Re.runId&&(a=Re.runId),x(Lt.cwd),(Re.threadId||Re.runId||Lt.cwd)&&R(),H==="serverrequest/resolved"){l&&(o.enqueue(Ln(l.requestId)),l=void 0);return}if(H==="turn/plan/updated"){let et=Om(j);c=et.explanation??c,et.steps.length>0&&(h=et.steps);return}if(H==="item/plan/delta"){let et=Mm(j);if(et.itemId&&et.delta){let kr=S.get(et.itemId)??"";S.set(et.itemId,`${kr}${et.delta}`)}return}if(H==="item/completed"){let et=_m(j);if(et.text?.trim()){let kr={explanation:c||void 0,steps:h,markdown:et.text.trim()};o.enqueue(qi(kr,!0));return}}let Pe=$m(H,j);if(Pe.mode==="delta"&&Pe.text){Pe.itemId&&I.add(Pe.itemId),o.enqueue(To(Pe.text));return}Pe.mode==="snapshot"&&Pe.text&&(!Pe.itemId||!I.has(Pe.itemId))&&o.enqueue(To(Pe.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(!Wm(ne))return{};let H=Ro(j),Re=Co(j);if(H.threadId&&i&&H.threadId!==i)return{};H.threadId&&(i=H.threadId),H.runId&&(a=H.runId),x(Re.cwd),(H.threadId||H.runId||Re.cwd)&&R();let Lt=H.requestId??`${i??"codex"}-${Date.now().toString(36)}`,Pe=Um(ne,Lt,j),et=ne.trim().toLowerCase(),kr=Pe.options,Ci=Pe.actions??[],XP=await new Promise(ew=>{l={requestId:Lt,methodLower:et,state:Pe,options:kr,actions:Ci,resolveResponse:ew},o.enqueue(Ni(Pe))});return l=void 0,o.enqueue(Ln(Lt)),XP});let $=async()=>{await n.connect(),await n.request("initialize",{protocolVersion:qw,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},rn),await n.notify("initialized",{})},C=async()=>{let ne=Yu(d,e.codexApprovalPolicy);if(i){let Re=await Eo({client:n,methods:["thread/resume"],payloads:Nm({threadId:i,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,approvalPolicy:ne.approvalPolicy,sandbox:ne.sandbox}),timeoutMs:rn}),Lt=Co(Re);i=Lt.threadId??i,x(Lt.cwd),R();return}let j=await Eo({client:n,methods:["thread/start","thread/new"],payloads:Fm({cwd:e.cwd,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,approvalPolicy:ne.approvalPolicy,sandbox:ne.sandbox}),timeoutMs:rn}),H=Co(j);if(i=H.threadId,!i)throw new Error("Codex App Server did not return a thread id.");x(H.cwd),R()},Ie=async ne=>{await C(),o.enqueue(Fi()),m+=1,c="",h=[],S.clear(),I.clear();let j="",H,Re,Lt=new Promise(Pe=>{Re=Pe});y={resolve:Re};try{let Pe=Yu(d,e.codexApprovalPolicy),et=await Eo({client:n,methods:["turn/start"],payloads:qm({threadId:i,prompt:ne,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,systemPrompt:e.systemPrompt,permissionMode:d,approvalPolicy:Pe.approvalPolicy,sandbox:Pe.sandbox}),timeoutMs:rn}),kr=Ro(et);kr.runId&&(a=kr.runId,R()),await Lt,j=y?.method??"turn/failed",H=y?.params;let Ci=Dm(j,H);o.enqueue(tn({success:Ci==="completed",outcome:Ci,duration_ms:0,total_cost_usd:0,num_turns:m,result:Lm(j,H),session_id:i}))}catch(Pe){o.enqueue(tn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:m,result:jm(Pe),session_id:i??""}))}finally{y=void 0}},Sr=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 Re=j.options[ne];return Re?(j.methodLower.includes("requestapproval")?j.resolveResponse({decision:Re}):j.resolveResponse({option:Re,index:ne}),!0):!1},ym=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 ym){let j=Kw(ne).trim();!j||await Sr(j)||await Ie(j)}}catch(ne){o.enqueue(tn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:m,result:jm(ne),session_id:i??e.resumeSessionId??""}))}finally{await n.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(ne){d=ne,o.enqueue(Bi(ne))},async submitPendingInputOption(ne){return or(ne)},async submitPendingInputText(ne){return Sr(ne)},async interrupt(){!i||!a||await Eo({client:n,methods:["turn/interrupt"],payloads:Bm({threadId:i,turnId:a}),timeoutMs:rn}).catch(()=>{})}}}buildUserMessage(e,r){return{type:"user",text:e,session_id:r}}}});function Vm(t){Zu.set(t.name,t)}function $o(t){let e=Zu.get(t);if(!e)throw new Error(`Unknown agent harness: "${t}". Available: ${[...Zu.keys()].join(", ")}`);return e}function Hm(){return $o(dt())}var Zu,Xu=Be(()=>{Am();Gm();ze();Zu=new Map;Vm(new Ui);Vm(new Vi)});function q(t){return t.backendRef?.conversationId??t.harnessSessionId}function ye(t){return t.id??t.sessionId??t.name??q(t)??t.harnessSessionId}function jw(t){return t.harnessSessionId}function ct(t){let e=[ye(t),q(t),jw(t)].filter(r=>!!r);return[...new Set(e)]}function ep(t){return t.harnessName??t.persistedHarness??dt()}function Mo(t){if(t.backendRef?.kind==="codex-app-server")return"native-restore";try{return $o(ep(t)).capabilities.worktrees}catch{return"plugin-managed"}}function tp(t){return t==="native-execution"}function Hi(t){return t==="native-restore"}function Gw(t){return!!(t.backendRef?.worktreePath||t.backendRef?.worktreeId)}function lt(t){let e=Mo(t);return(tp(e)||Hi(e))&&Gw(t)}var Ee=Be(()=>{ze();Xu()});import{execFileSync as je}from"child_process";import*as ps from"fs";import{tmpdir as yv}from"os";import{dirname as hc,join as Sv}from"path";function kv(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 ds(t){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(K.worktreeDir)return K.worktreeDir;if(t){let e=kv(t);if(e)return Sv(e,".worktrees")}return yv()}function yc(t){return t.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function ls(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")?hc(e):void 0}catch{return}}function Iv(){if(as!==void 0)return as;try{return je("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),as=!0,!0}catch{return as=!1,!1}}function Pr(){if(us!==void 0)return us;try{return je("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),us=!0,!0}catch{return us=!1,!1}}function sp(t){if(!Iv())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 Sc(t){try{let e=Pv(t);if(!e)return console.warn(`[worktree] Failed to resolve free-space probe path for ${ds(t)}`),!0;let r=ps.statfsSync(e),n=r.bavail*r.bsize;return wv(n)}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function Lo(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 xv(t){let e=t;for(;;){if(ps.existsSync(e))return e;let r=hc(e);if(r===e)return;e=r}}function Pv(t){return xv(ds(t))}function wv(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 ms(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 Fo(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 kc(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 Ic(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 xc(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 Pc(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 as,us,No=Be(()=>{ze()});import{execFileSync as Un}from"child_process";import{appendFileSync as vv,existsSync as bc,mkdirSync as wc,readFileSync as bv,rmSync as ap}from"fs";import{relative as Av,sep as vc}from"path";function Tv(t,e){return!!(t&&typeof t=="object"&&"code"in t&&t.code===e)}function Rv(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 Cv(t,e){let r=Rv(t);if(!r)return;let n=Av(r,e);if(!n||n.startsWith("..")||n.includes(`..${vc}`))return;let o=`${r}/.git/info/exclude`,i=`${n.split(vc).join("/").replace(/\/$/,"")}/`;try{let a=bc(o)?bv(o,"utf-8"):"";a.split(/\r?\n/).map(p=>p.trim()).some(p=>p===i||p===`/${i}`)||vv(o,`${a.endsWith(`
1
+ var cw=Object.defineProperty;var De=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ct=(t,e)=>{for(var r in e)cw(t,r,{get:e[r],enumerable:!0})};function Po(t,e){return e?{...e,...t}:t}function fw(t){return{...t,[Vu]:!0}}function gw(t){return{const:t,type:typeof t}}var Vu,f,tt=De(()=>{Vu=Symbol("optionalSchema");f={Object(t,e){let r=Object.entries(t).filter(([,o])=>!o[Vu]).map(([o])=>o),n=Object.fromEntries(Object.entries(t).map(([o,i])=>{let{[Vu]:a,...u}=i;return[o,u]}));return{...e,type:"object",...r.length>0?{required:r}:{},properties:n}},String(t){return Po({type:"string"},t)},Number(t){return Po({type:"number"},t)},Boolean(t){return Po({type:"boolean"},t)},Array(t,e){return Po({type:"array",items:t},e)},Literal:gw,Union(t,e){return Po({anyOf:t},e)},Optional:fw}});function Hu(t){I=t}function zu(t){Ce=t}var I,Ce,le=De(()=>{I=null,Ce=null});function bm(t){let e=t.chatId.trim(),r=t.topicId.trim();return!/^-?\d+$/.test(e)||!/^\d+$/.test(r)?null:`${e}:topic:${r}`}function Iw(t){let e=t.conversationId.trim(),r=e.match(/^(-?\d+):topic:(\d+)$/i);if(r?.[1]&&r[2]){let i=bm({chatId:r[1],topicId:r[2]});return i?{chatId:r[1],topicId:r[2],canonicalConversationId:i}:null}if(!/^\d+$/.test(e))return null;let n=t.parentConversationId?.trim();if(!n||!/^-?\d+$/.test(n))return null;let o=bm({chatId:n,topicId:e});return o?{chatId:n,topicId:e,canonicalConversationId:o}:null}function xw(t){if(!t)return;let e=t.match(/^agent:[^:]+:discord:(direct|dm|channel|group):/i);if(!e?.[1])return;let r=e[1].toLowerCase();return r==="direct"||r==="dm"?"user":"channel"}function Pw(t,e){if(!/^\d+$/.test(t))return t;let r=xw(e);return r?`${r}:${t}`:`channel:${t}`}function ww(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 vw(t){let e=t.toLowerCase(),r=[":thread:",":topic:"];for(let n of r){let o=e.lastIndexOf(n);if(o===-1)continue;let i=t.slice(0,o).trim(),a=t.slice(o+n.length).trim()||void 0;return{id:i||t,threadId:a}}return{id:t}}function bw(t){let e=t?.trim();if(!e)return;let r=e.split(":").filter(Boolean);if(r[0]?.trim().toLowerCase()==="agent")for(let n=2;n<=r.length-3;n+=1){let o=r[n]?.trim().toLowerCase();if(!o||!Sw.has(o))continue;let i=r[n+1]?.trim().toLowerCase(),a=r.slice(n+2).join(":").trim();if(!(!i||!a))return{provider:o,kind:i,rawId:a}}}function Aw(t,e=Iw){try{return e({conversationId:t})}catch{return null}}function Ju(t){return{provider:"system",target:"system",sessionKey:t?.trim()||void 0}}function Qu(t,e){return{...t,threadId:e??t.threadId}}function Rw(t,e,r){return t==="telegram"&&r?.provider==="telegram"&&!!r.target&&e!==r.target}function Cw(t){let e=t?.trim();if(!e)return;let r=bw(e);if(!r)return;let{provider:n,kind:o,rawId:i}=r,a=vw(i),u=null;if(n==="telegram")try{u=Tw.safeParseTelegramTopicConversation(i)}catch{u=null}let p=u?.chatId??a.id,d=u?.topicId??a.threadId,l=n==="discord"?o==="direct"||o==="dm"?`user:${p}`:`channel:${p}`:p;return{provider:n,target:l,threadId:d,sessionKey:e}}function Yu(t){let e=t?.match(/:topic:(\d+)$/);return e?parseInt(e[1],10):void 0}function Am(t){return!!(t?.provider&&t.target&&t.provider!=="system"&&t.target!=="system")}function wo(t,e,r){let n=Cw(r),o=e!=null?String(e):void 0,i=t?.trim();if(!i||i.toLowerCase()==="unknown")return n?Qu(n,o):Ju(r);let a=i.split("|").map(y=>y.trim());if(a.length<2)return n?Qu(n,o):Ju(r);let[u,p,d]=a,l=a.length>=3?d:p,m=a.length>=3?p:void 0,c=u?.toLowerCase();if(!c||!l)return n?Qu(n,o):Ju(r);let h=c==="discord"?Pw(l,r):l;return Rw(c,h,n)?{provider:c,accountId:m,target:n.target,threadId:o??n.threadId,sessionKey:r?.trim()||void 0}:{provider:c,accountId:m,target:h,threadId:o??(n?.provider===c?n.threadId:void 0),sessionKey:r?.trim()||void 0}}function en(t){return wo(ww(t.route)??t.originChannel,t.route?.threadId??t.originThreadId,t.route?.sessionKey??t.originSessionKey)??t.route}function _i(t){let e=en(t);return Am(e)?e:void 0}function Ew(t){return Object.fromEntries(Object.entries(t).filter(e=>!!e[1]))}function vo(t){let e=en(t);if(!Am(e))return"";let r=Ew({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(r).length===0?"":["Session origin route (authoritative for human follow-ups):",`originRoute: ${JSON.stringify(r)}`,"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 Sw,Tw,ir=De(()=>{Sw=new Set(["telegram","discord","slack","system","mattermost","feishu","line","whatsapp","signal","matrix","googlechat","bluebubbles","imessage","msteams"]);Tw={safeParseTelegramTopicConversation:Aw}});import{readFileSync as $w}from"fs";import{homedir as Mw}from"os";import{join as Ow}from"path";function Rm(){if(bo!==void 0)return bo;try{let t=$w(Ow(Mw(),".claude.json"),"utf-8");bo=JSON.parse(t).mcpServers??{}}catch{bo={}}return bo}function Cm(t){let e=t.defaultHarness??Tm,r={};for(let[n,o]of Object.entries(Di))r[n]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[n,o]of Object.entries(t.harnesses??{})){let i=r[n]??{},a={...i,defaultModel:o.defaultModel??i.defaultModel,reasoningEffort:o.reasoningEffort??i.reasoningEffort,fastMode:o.fastMode??i.fastMode};o.allowedModels!==void 0?a.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(a.allowedModels=void 0),r[n]=a}if(t.defaultModel!==void 0){let n=r[e]??{};r[e]={...n,defaultModel:t.harnesses?.[e]?.defaultModel??t.defaultModel,allowedModels:t.harnesses?.[e]?.allowedModels!==void 0?n.allowedModels:t.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${e}.defaultModel instead.`)}if(t.model!==void 0){let n=r.codex??{};r.codex={...n,defaultModel:t.harnesses?.codex?.defaultModel??t.model,allowedModels:t.harnesses?.codex?.allowedModels!==void 0?n.allowedModels:t.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(t.reasoningEffort!==void 0){let n=r.codex??{};r.codex={...n,reasoningEffort:t.harnesses?.codex?.reasoningEffort??t.reasoningEffort},console.warn("[openclaw-code-agent] config.reasoningEffort is deprecated; use harnesses.codex.reasoningEffort instead.")}if(t.allowedModels!==void 0){console.warn("[openclaw-code-agent] config.allowedModels is deprecated; use harnesses.<name>.allowedModels instead.");for(let[n,o]of Object.entries(r))t.harnesses?.[n]?.allowedModels===void 0&&(r[n]={...o,allowedModels:void 0})}K={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:r,allowedModels:t.allowedModels,defaultWorktreeStrategy:t.defaultWorktreeStrategy??"delegate",worktreeDir:t.worktreeDir}}function dt(){return K.defaultHarness??Tm}function ep(t){let e=Di[t],r=K.harnesses[t];return{...e,...r,allowedModels:r?.allowedModels??e?.allowedModels}}function $n(t){return ep(t).defaultModel}function Li(t){return K.harnesses[t]?.allowedModels??K.allowedModels}function Ir(t){return ep(t).reasoningEffort}function Mn(t){return t==="codex"?ep(t).fastMode:void 0}function zt(t){return t==null?void 0:String(t).trim()||void 0}function tp(t){return{channel:zt(t?.deliveryContext?.channel),to:zt(t?.deliveryContext?.to),accountId:zt(t?.deliveryContext?.accountId),threadId:zt(t?.deliveryContext?.threadId)}}function Em(t,e,r){if(!(!t||!e))return r?`${t}|${r}|${e}`:`${t}|${e}`}function Zu(t){return zt(t?.requesterSenderId??t?.senderId)}function Xu(t){return(zt(t.deliveryContext?.channel)??t.messageChannel??t.channel)?.toLowerCase()!=="telegram"?!1:!!Yu(t.sessionKey)}function Fi(t){let e=tp(t),r=Em(e.channel,e.to,e.accountId);if(r)return r;if(t.messageChannel){let n=t.messageChannel.split("|");if(n.length>=3)return t.messageChannel;if(t.agentAccountId&&n.length>=2)return`${n[0]}|${t.agentAccountId}|${n.slice(1).join("|")}`;let o=zt(t.chatId);if(n.length===1&&o)return`${n[0]}|${o}`;let i=Zu(t);if(n.length===1&&i&&!Xu(t))return`${n[0]}|${i}`}if(t.workspaceDir){let n=To(t.workspaceDir);if(n)return n}if(t.messageChannel&&t.messageChannel.includes("|"))return t.messageChannel}function Ao(t,e){if(e&&String(e).includes("|"))return String(e);let r=tp(t),n=Em(r.channel,r.to,r.accountId);if(n)return n;if(t?.channelId&&String(t.channelId).includes("|"))return String(t.channelId);if(t?.messageChannel){let u=String(t.messageChannel);if(u.includes("|"))return u;let p=zt(t.chatId);if(p)return`${u}|${p}`;let d=Zu(t);if(d&&!Xu(t))return`${u}|${d}`}let o=zt(t?.channel),i=zt(t?.chatId);if(o&&i)return`${o}|${i}`;let a=Zu(t);return o&&a&&!Xu(t)?`${o}|${a}`:t?.id&&/^-?\d+$/.test(String(t.id))?`telegram|${t.id}`:K.fallbackChannel??"unknown"}function rp(t){return tp(t).threadId??t?.messageThreadId??void 0}function On(t,e,r){return wo(Ao(t,e),rp(t),r??t?.sessionKey)}function To(t){let e=K.agentChannels;if(!e)return;let r=i=>i.replace(/\/+$/,""),n=r(t),o=Object.entries(e).sort((i,a)=>a[0].length-i[0].length);for(let[i,a]of o)if(n===r(i)||n.startsWith(r(i)+"/"))return a}function $m(t){return Yu(t)}var bo,Tm,Di,K,ze=De(()=>{ir();Tm="claude-code",Di={"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"}};K={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"delegate",defaultWorktreeStrategy:"delegate",harnesses:{"claude-code":{...Di["claude-code"]},codex:{...Di.codex}}}});function Ni(t){return{type:"backend_ref",ref:t}}function qi(t){return{type:"run_started",...t?{runId:t}:{}}}function Ro(t){return{type:"text_delta",text:t}}function Mm(t,e){return{type:"tool_call",name:t,input:e}}function Bi(t){return{type:"pending_input",state:t}}function Ln(t){return t?{type:"pending_input_resolved",requestId:t}:{type:"pending_input_resolved"}}function Ui(t,e){return{type:"plan_artifact",artifact:t,finalized:e}}function Wi(t){return t?{type:"settings_changed",permissionMode:t}:{type:"settings_changed"}}function tn(t){return{type:"run_completed",data:t}}var Dn,np=De(()=>{Dn=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(r=>{e.resolvePending=r})}})()}}});import*as ji from"@anthropic-ai/claude-agent-sdk";function _w(t){if(typeof t.result=="string"&&t.result.length>0)return t.result;if(Array.isArray(t.errors)){let e=t.errors.filter(r=>typeof r=="string"&&r.length>0);if(e.length>0)return e.join(`
3
+ `)}}function Dw(t,e,r){let o=(Array.isArray(r.questions)?r.questions:[])[0]??{},i=typeof o.question=="string"?o.question:void 0,a=Array.isArray(o.options)?o.options.map(u=>{if(!u||typeof u!="object")return"";let p=u.label;return typeof p=="string"?p:""}).filter(Boolean):[];return{requestId:`${t||"claude"}-ask-${e}`,kind:"question",promptText:i,options:a,allowsFreeText:a.length===0||o.multiSelect===!0}}var Ki,Om=De(()=>{np();Ki=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 r=new Dn,n=!1,o="",i=!1,a=0,u=e.resumeSessionId??"",p=e.canUseTool,d={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,...p?{canUseTool:async(y,k)=>{if(y!=="AskUserQuestion")return{behavior:"allow"};let S=Dw(u,++a,k);r.enqueue(Bi(S));try{let x=await p(y,k);return r.enqueue(Ln(S.requestId)),x}catch(x){throw r.enqueue(Ln(S.requestId)),x}}}:{}};e.resumeSessionId&&(d.resume=e.resumeSessionId,d.forkSession=e.forkSession??!1);let l=e.prompt,m=this.deps.query??ji.query,c=this.deps.startup??ji.startup,h=(async()=>{if(typeof c!="function")return m({prompt:l,options:d});let y=await c({options:d});try{return y.query(l)}catch(k){throw await y.close?.(),k}})();return(async()=>{try{let y=await h;for await(let k of y){let S=k;if(S.type==="system"&&S.subtype==="init"){u=S.session_id??u,r.enqueue(Ni({kind:"claude-code",conversationId:u}));continue}if(S.type==="system"&&S.subtype==="status"&&S.permissionMode){r.enqueue(Wi(S.permissionMode));continue}if(S.type==="assistant"){n||(n=!0,r.enqueue(qi()));for(let x of S.message?.content??[]){if(x.type==="text"){o+=o?`
4
+ ${x.text}`:x.text,r.enqueue(Ro(x.text));continue}x.type==="tool_use"&&((x.name==="ExitPlanMode"||x.name==="set_permission_mode")&&(i=!0),x.name!=="AskUserQuestion"&&r.enqueue(Mm(x.name,x.input)))}continue}if(S.type==="result"){let x=o.trim();if(x&&(e.permissionMode==="plan"||i)){let R={explanation:void 0,steps:[],markdown:x};r.enqueue(Ui(R,!0))}r.enqueue(tn({success:S.subtype==="success",duration_ms:S.duration_ms??0,total_cost_usd:S.total_cost_usd??0,num_turns:S.num_turns??0,result:_w(S),session_id:S.session_id??u})),o="",i=!1,n=!1}}}finally{r.close()}})().catch(y=>{r.enqueue(tn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,result:y instanceof Error?y.message:String(y),session_id:u})),r.close()}),{messages:r.messages(),async setPermissionMode(y){let k=await h;typeof k.setPermissionMode=="function"&&await k.setPermissionMode(y)},async streamInput(y){let k=await h;typeof k.streamInput=="function"&&await k.streamInput(y)},async interrupt(){let y=await h;typeof y.interrupt=="function"&&await y.interrupt()}}}buildUserMessage(e,r){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:r}}}});import{spawn as Lw}from"node:child_process";import Fw from"node:readline";function Nw(t){return t instanceof Error?t.message:String(t)}function qw(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}async function Bw(t,e){if(t.id!=null&&(Object.hasOwn(t,"result")||Object.hasOwn(t,"error"))){let n=String(t.id),o=e.pending.get(n);if(!o)return;if(clearTimeout(o.timer),e.pending.delete(n),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 r=t.method?.trim();if(r){if(t.id==null){await e.onNotification(r,t.params);return}try{let n=await e.onRequest(r,t.params);e.respond({jsonrpc:"2.0",id:t.id,result:n??{}})}catch(n){e.respond({jsonrpc:"2.0",id:t.id,error:{code:-32603,message:Nw(n)}})}}}var Gi,_m=De(()=>{Gi=class{constructor(e,r,n){this.command=e;this.args=r;this.requestTimeoutMs=n}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=Lw(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,Fw.createInterface({input:e.stdout}).on("line",n=>{this.handleLine(n)}),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,r){this.write({jsonrpc:"2.0",method:e,params:r??{}})}async request(e,r,n){let o=`rpc-${++this.counter}`,i=new Promise((a,u)=>{let p=setTimeout(()=>{this.pending.delete(o),u(new Error(`codex app server timeout: ${e}`))},Math.max(100,n??this.requestTimeoutMs));p.unref?.(),this.pending.set(o,{resolve:a,reject:u,timer:p})});return this.write({jsonrpc:"2.0",id:o,method:e,params:r??{}}),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 r=qw(e);r&&await Bw(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 me(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function ve(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 Uw(t){return t instanceof Error?t.message:String(t)}function Dm(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=me(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 Co(t){let e=me(t);if(!e)return{};let r=me(e.thread)??me(e.session),n=me(e.turn)??me(e.run),o=me(e.item),i=me(e.serverRequest);return{threadId:ve(e,["threadId","thread_id","conversationId","conversation_id"])??ve(r,["id","threadId","thread_id","conversationId"]),runId:ve(e,["turnId","turn_id","runId","run_id"])??ve(n,["id","turnId","turn_id","runId","run_id"]),requestId:ve(e,["requestId","request_id","serverRequestId"])??ve(i,["id","requestId","request_id"]),itemId:ve(e,["itemId","item_id"])??ve(o,["id","itemId","item_id"])}}function Vi(t,e,r=0){if(r>6)return;if(Array.isArray(t)){for(let i of t){let a=Vi(i,e,r+1);if(a)return a}return}let n=me(t);if(!n)return;let o=ve(n,e);if(o)return o;for(let i of Object.values(n)){let a=Vi(i,e,r+1);if(a)return a}}function Eo(t){return{threadId:Co(t).threadId,cwd:Vi(t,["cwd","workdir","directory"])}}function Lm(t){let e=t?.trim();return!!(e&&/[/\\]worktrees[/\\][^/\\]+[/\\][^/\\]+/.test(e))}function Fm(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 Hi(t){let e=me(t);if(!e)return;let r=me(e.item)??e;return ve(r,["id","itemId","item_id","messageId","message_id"])}function Ww(t,e=!1){let r=me(t);if(!r)return"";let n=me(r.item)??r;return ve(n,["type"])?.toLowerCase()!=="agentmessage"?"":e?xr(n):ve(n,["text"],{trim:!1})??xr(n)}function Nm(t,e){let r=t.trim().toLowerCase();return r==="item/agentmessage/delta"?{mode:"delta",text:xr(e),itemId:Hi(e)}:r==="item/completed"?{mode:"snapshot",text:Ww(e),itemId:Hi(e)}:{mode:"ignore",text:""}}function qm(t){return{itemId:Hi(t),delta:xr(t)}}function Bm(t){let e=me(t),r=me(e?.plan),o=(Array.isArray(e?.plan)?e.plan:Array.isArray(r?.steps)?r.steps:[]).map(i=>{let a=me(i),u=ve(a,["step","title","text"]);if(!u)return null;let p=ve(a,["status"])?.toLowerCase()??"pending";return{step:u,status:p==="inprogress"||p==="in_progress"?"inProgress":p==="completed"?"completed":"pending"}}).filter(Boolean);return{explanation:ve(r,["explanation"])??ve(e,["explanation"]),steps:o}}function Um(t){let e=me(t);if(!e)return{};let r=me(e.item)??e;return ve(r,["type"])?.toLowerCase()!=="plan"?{}:{itemId:Hi(r),text:ve(r,["text"],{trim:!1})??xr(r)}}function Wm(t,e){let r=t.trim().toLowerCase();if(r==="turn/failed")return"failed";if(r==="turn/cancelled")return"interrupted";let n=me(e)??{},o=me(n.turn)??n,i=ve(o,["status"])?.toLowerCase();return i==="failed"?"failed":i==="interrupted"||i==="cancelled"?"interrupted":"completed"}function Km(t,e){let r=me(e)??{},n=me(r.turn)??r,o=me(n.error)??me(r.error);if(o)return ve(o,["message","text","summary","reason"])}function Kw(t,e){let r=Uw(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 Gw(t){return jw.has(t.trim().toLowerCase())}function Vw(t){let e=me(t);return e?!!ve(e,["threadId","thread_id"]):!1}async function $o(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(Gw(r)&&!Vw(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,!Kw(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 Gm(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 Hw(t){return[{type:"text",text:t}]}function zw(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 Vm(t){let e={threadId:t.threadId,input:Hw(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=zw(t.permissionMode??"default",t.model,t.reasoningEffort,t.systemPrompt);return r?[{...e,collaborationMode:r}]:[e]}function Hm(t){return[{threadId:t.threadId,turnId:t.turnId}]}function Jw(t){let e=me(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():ve(me(n),["label","title","text","value","name","id"])??"").filter(Boolean):[]}function Qw(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 zm(t,e,r){let n=t.trim().toLowerCase(),o=Jw(r),i=Vi(r,["question","prompt","message","text","summary","reason"])??void 0,a=n.includes("requestapproval"),u=a?o.map(p=>({kind:"approval",label:p,decision:Qw(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 Jm(t){let e=t.trim().toLowerCase();return e.includes("requestuserinput")||e.includes("requestapproval")}function op(t,e){let r=t==="bypassPermissions"?"never":e?.trim()||"never";return{approvalPolicy:r,sandbox:r==="never"?"danger-full-access":void 0}}var jw,Qm=De(()=>{jw=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function Ym(t){return t instanceof Error?t.message:String(t)}function tv(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 Yw,rn,Zw,Xw,ev,zi,Zm=De(()=>{_m();np();Qm();Yw="1.0",rn=6e4,Zw="OPENCLAW_CODEX_APP_SERVER_COMMAND",Xw="OPENCLAW_CODEX_APP_SERVER_ARGS",ev="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";zi=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[Zw]?.trim()||"codex",args:Dm(process.env[Xw]),requestTimeoutMs:Number.parseInt(process.env[ev]??String(rn),10)||rn},n=this.deps.createClient?.(r)??new Gi(r.command,r.args,r.requestTimeoutMs),o=new Dn,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&&Lm(j)&&(u=j,p=Fm(j))},R=()=>{i&&o.enqueue(Ni({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(),Re=Co(j),Lt=Eo(j);if(Re.threadId&&i&&Re.threadId!==i)return;if(Re.threadId&&(i=Re.threadId),Re.runId&&(a=Re.runId),x(Lt.cwd),(Re.threadId||Re.runId||Lt.cwd)&&R(),H==="serverrequest/resolved"){l&&(o.enqueue(Ln(l.requestId)),l=void 0);return}if(H==="turn/plan/updated"){let et=Bm(j);c=et.explanation??c,et.steps.length>0&&(h=et.steps);return}if(H==="item/plan/delta"){let et=qm(j);if(et.itemId&&et.delta){let Sr=k.get(et.itemId)??"";k.set(et.itemId,`${Sr}${et.delta}`)}return}if(H==="item/completed"){let et=Um(j);if(et.text?.trim()){let Sr={explanation:c||void 0,steps:h,markdown:et.text.trim()};o.enqueue(Ui(Sr,!0));return}}let we=Nm(H,j);if(we.mode==="delta"&&we.text){we.itemId&&S.add(we.itemId),o.enqueue(Ro(we.text));return}we.mode==="snapshot"&&we.text&&(!we.itemId||!S.has(we.itemId))&&o.enqueue(Ro(we.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(!Jm(ne))return{};let H=Co(j),Re=Eo(j);if(H.threadId&&i&&H.threadId!==i)return{};H.threadId&&(i=H.threadId),H.runId&&(a=H.runId),x(Re.cwd),(H.threadId||H.runId||Re.cwd)&&R();let Lt=H.requestId??`${i??"codex"}-${Date.now().toString(36)}`,we=zm(ne,Lt,j),et=ne.trim().toLowerCase(),Sr=we.options,Mi=we.actions??[],lw=await new Promise(mw=>{l={requestId:Lt,methodLower:et,state:we,options:Sr,actions:Mi,resolveResponse:mw},o.enqueue(Bi(we))});return l=void 0,o.enqueue(Ln(Lt)),lw});let $=async()=>{await n.connect(),await n.request("initialize",{protocolVersion:Yw,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},rn),await n.notify("initialized",{})},C=async()=>{let ne=op(d,e.codexApprovalPolicy);if(i){let Re=await $o({client:n,methods:["thread/resume"],payloads:Gm({threadId:i,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,approvalPolicy:ne.approvalPolicy,sandbox:ne.sandbox}),timeoutMs:rn}),Lt=Eo(Re);i=Lt.threadId??i,x(Lt.cwd),R();return}let j=await $o({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=Eo(j);if(i=H.threadId,!i)throw new Error("Codex App Server did not return a thread id.");x(H.cwd),R()},Ie=async ne=>{await C(),o.enqueue(qi()),m+=1,c="",h=[],k.clear(),S.clear();let j="",H,Re,Lt=new Promise(we=>{Re=we});y={resolve:Re};try{let we=op(d,e.codexApprovalPolicy),et=await $o({client:n,methods:["turn/start"],payloads:Vm({threadId:i,prompt:ne,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,systemPrompt:e.systemPrompt,permissionMode:d,approvalPolicy:we.approvalPolicy,sandbox:we.sandbox}),timeoutMs:rn}),Sr=Co(et);Sr.runId&&(a=Sr.runId,R()),await Lt,j=y?.method??"turn/failed",H=y?.params;let Mi=Wm(j,H);o.enqueue(tn({success:Mi==="completed",outcome:Mi,duration_ms:0,total_cost_usd:0,num_turns:m,result:Km(j,H),session_id:i}))}catch(we){o.enqueue(tn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:m,result:Ym(we),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 Re=j.options[ne];return Re?(j.methodLower.includes("requestapproval")?j.resolveResponse({decision:Re}):j.resolveResponse({option:Re,index:ne}),!0):!1},vm=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 vm){let j=tv(ne).trim();!j||await kr(j)||await Ie(j)}}catch(ne){o.enqueue(tn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:m,result:Ym(ne),session_id:i??e.resumeSessionId??""}))}finally{await n.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(ne){d=ne,o.enqueue(Wi(ne))},async submitPendingInputOption(ne){return or(ne)},async submitPendingInputText(ne){return kr(ne)},async interrupt(){!i||!a||await $o({client:n,methods:["turn/interrupt"],payloads:Hm({threadId:i,turnId:a}),timeoutMs:rn}).catch(()=>{})}}}buildUserMessage(e,r){return{type:"user",text:e,session_id:r}}}});function Xm(t){ip.set(t.name,t)}function Mo(t){let e=ip.get(t);if(!e)throw new Error(`Unknown agent harness: "${t}". Available: ${[...ip.keys()].join(", ")}`);return e}function ec(){return Mo(dt())}var ip,sp=De(()=>{Om();Zm();ze();ip=new Map;Xm(new Ki);Xm(new zi)});function q(t){return t.backendRef?.conversationId??t.harnessSessionId}function ye(t){return t.id??t.sessionId??t.name??q(t)??t.harnessSessionId}function rv(t){return t.harnessSessionId}function lt(t){let e=[ye(t),q(t),rv(t)].filter(r=>!!r);return[...new Set(e)]}function ap(t){return t.harnessName??t.persistedHarness??dt()}function Oo(t){if(t.backendRef?.kind==="codex-app-server")return"native-restore";try{return Mo(ap(t)).capabilities.worktrees}catch{return"plugin-managed"}}function up(t){return t==="native-execution"}function Ji(t){return t==="native-restore"}function nv(t){return!!(t.backendRef?.worktreePath||t.backendRef?.worktreeId)}function mt(t){let e=Oo(t);return(up(e)||Ji(e))&&nv(t)}var Ee=De(()=>{ze();sp()});import{execFileSync as je}from"child_process";import*as ms from"fs";import{tmpdir as Cv}from"os";import{dirname as Pc,join as Ev}from"path";function $v(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 cs(t){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(K.worktreeDir)return K.worktreeDir;if(t){let e=$v(t);if(e)return Ev(e,".worktrees")}return Cv()}function wc(t){return t.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function fs(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")?Pc(e):void 0}catch{return}}function Mv(){if(ds!==void 0)return ds;try{return je("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ds=!0,!0}catch{return ds=!1,!1}}function Pr(){if(ls!==void 0)return ls;try{return je("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ls=!0,!0}catch{return ls=!1,!1}}function cp(t){if(!Mv())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 vc(t){try{let e=_v(t);if(!e)return console.warn(`[worktree] Failed to resolve free-space probe path for ${cs(t)}`),!0;let r=ms.statfsSync(e),n=r.bavail*r.bsize;return Dv(n)}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function Fo(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 Ov(t){let e=t;for(;;){if(ms.existsSync(e))return e;let r=Pc(e);if(r===e)return;e=r}}function _v(t){return Ov(cs(t))}function Dv(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 gs(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 No(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 bc(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 Ac(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 Tc(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 Rc(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 ds,ls,qo=De(()=>{ze()});import{execFileSync as Un}from"child_process";import{appendFileSync as Lv,existsSync as $c,mkdirSync as Cc,readFileSync as Fv,rmSync as fp}from"fs";import{relative as Nv,sep as Ec}from"path";function qv(t,e){return!!(t&&typeof t=="object"&&"code"in t&&t.code===e)}function Bv(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 Uv(t,e){let r=Bv(t);if(!r)return;let n=Nv(r,e);if(!n||n.startsWith("..")||n.includes(`..${Ec}`))return;let o=`${r}/.git/info/exclude`,i=`${n.split(Ec).join("/").replace(/\/$/,"")}/`;try{let a=$c(o)?Fv(o,"utf-8"):"";a.split(/\r?\n/).map(p=>p.trim()).some(p=>p===i||p===`/${i}`)||Lv(o,`${a.endsWith(`
6
6
  `)||a.length===0?"":`
7
7
  `}${i}
8
- `,"utf-8")}catch(a){console.warn(`[worktree] Failed to add ${i} to ${o}: ${a instanceof Error?a.message:String(a)}`)}}function up(t,e,r={}){let n=yc(e),o=ds(t);Cv(t,o),wc(o,{recursive:!0});let i=r.allowExistingBranch===!0,a,u,p=10,d=!1;for(let m=0;m<p;m++){let c=m===0?"":`-${Math.random().toString(16).slice(2,6)}`,h=`${o}/openclaw-worktree-${n}${c}`,y=`agent/${n}${c}`;if(!i&&Lo(t,y))continue;let S=!1;do{S=!1;try{wc(h,{recursive:!1}),a=h,u=y;break}catch(I){if(Tv(I,"EEXIST")){if(i&&m===0&&!d)try{ap(h,{recursive:!0,force:!0}),d=!0,S=!0}catch(x){throw new Error(`Failed to recreate existing worktree branch ${y}: could not clear blocked path ${h}: ${x instanceof Error?x.message:String(x)}`)}else if(i&&m===0)throw new Error(`Failed to recreate existing worktree branch ${y}: path ${h} remains blocked after one cleanup attempt`);continue}throw I}}while(S);if(a&&u)break}if(!a||!u)throw new Error(`Failed to create unique worktree directory and branch after ${p} attempts`);let l=Lo(t,u);try{l?Un("git",["-C",t,"worktree","add",a,u],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):Un("git",["-C",t,"worktree","add","-b",u,a],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(m){try{ap(a,{recursive:!0,force:!0})}catch{}throw m}return a}function Wn(t){if(!bc(t))return[];try{let e=Un("git",["-C",t,"status","--porcelain","--untracked-files=all"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e?e.split(`
9
- `).map(r=>r.trim()).filter(Boolean):[]}catch{return[]}}function Kn(t){return Wn(t).length>0}function xt(t,e,r={}){let n=r.destructive===!0,o=Wn(e);if(o.length>0&&!n)return console.warn(`[worktree] Refusing implicit cleanup for dirty worktree ${e}: ${o[0]}`),!1;try{return Un("git",["-C",t,"worktree","remove",...n?["--force"]:[],e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(i){if(console.warn(`[worktree] git worktree remove failed for ${e}: ${i instanceof Error?i.message:String(i)}`),!n)return!1;try{return ap(e,{recursive:!0,force:!0}),console.info(`[worktree] Fallback rmSync succeeded for ${e}`),!0}catch(a){return console.error(`[worktree] Both git worktree remove and rmSync failed for ${e}: ${a instanceof Error?a.message:String(a)}`),!1}}}function cs(t){try{Un("git",["-C",t,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}var pp=Be(()=>{No()});import{execFileSync as ke}from"child_process";import{existsSync as Ev}from"fs";function sn(t,e,r){try{let n=ke("git",["-C",t,"rev-list","--count",`${r}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(n.trim(),10),a=ke("git",["-C",t,"diff","--shortstat",`${r}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),u=0,p=0,d=0,l=a.match(/(\d+)\s+files?\s+changed/);l&&(u=parseInt(l[1],10));let m=a.match(/(\d+)\s+insertions?\(/);m&&(p=parseInt(m[1],10));let c=a.match(/(\d+)\s+deletions?\(/);c&&(d=parseInt(c[1],10));let y=ke("git",["-C",t,"diff","--name-only","--diff-filter=ACMR",`${r}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
10
- `).map(x=>x.trim()).filter(Boolean),I=ke("git",["-C",t,"log",`${r}..${e}`,"--format=%h|%s|%an","-n","5"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
11
- `).filter(Boolean).map(x=>{let[R,$,C]=x.split("|");return{hash:R||"",message:$||"",author:C||""}});return{commits:o,filesChanged:u,insertions:p,deletions:d,changedFiles:y,commitMessages:I}}catch(n){console.warn(`[worktree] Failed to get diff summary: ${n instanceof Error?n.message:String(n)}`);return}}function fs(t,e,r="origin"){try{return ke("git",["-C",t,"push",r,e],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(n){return console.warn(`[worktree] Failed to push branch ${e}: ${n instanceof Error?n.message:String(n)}`),!1}}function Ac(t){try{return ke("git",["-C",t,"status","--porcelain"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).split(`
12
- `).some(r=>r.length>0&&!r.startsWith("??")&&!r.startsWith("!!"))}catch{return!1}}function gs(t,e,r,n="merge",o){let i=!1,a,u=p=>{if(i)try{ke("git",["-C",p,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(n==="squash"){if(ke("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Ac(t)){let c;try{c=ke("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(h){return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${h instanceof Error?h.message:String(h)}. Commit or stash changes manually, then retry.`}}if(!c.includes("No local changes to save")){i=!0;try{a=ke("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}ke("git",["-C",t,"merge","--squash",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ke("git",["-C",t,"commit","-m",`Squash merge ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let m=!1;if(i)try{ke("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{m=!0}return{success:!0,stashed:i||void 0,stashRef:a,stashPopConflict:m||void 0}}let p=o&&Ev(o),d=p?o:t;if(p||ke("git",["-C",t,"checkout",e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Ac(t)){let m;try{m=ke("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(c){try{ke("git",["-C",t,"checkout",r],{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(!m.includes("No local changes to save")){i=!0;try{a=ke("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{ke("git",["-C",d,"rebase",r],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{ke("git",["-C",d,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{ke("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return u(t),{success:!1,rebaseConflict:!0,stashed:i||void 0,stashRef:a,error:[`Rebase of ${e} onto ${r} hit conflicts.`,"To resolve manually:",` cd ${d}`,` git rebase ${r}`," # resolve conflicts in each file, then:"," git add <file>"," git rebase --continue"," # repeat until rebase finishes, then re-run agent_merge."].join(`
13
- `)}}ke("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ke("git",["-C",t,"merge","--ff-only",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let l=!1;if(i)try{ke("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{ke("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 Tc=Be(()=>{});import{execFileSync as hs}from"child_process";function Rc(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=hs("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:hs("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 qo(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=hs("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 Cc(t,e,r,n){if(!Pr())return!1;try{let o=["pr","comment",String(e),"--body",r];return n&&o.push("--repo",n),hs("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 dp=Be(()=>{No()});import{existsSync as lp}from"fs";function Ec(){return new Date().toISOString()}function $v(t){return t.worktreeLifecycle??{state:t.worktreePath||t.worktreeBranch?"provisioned":"none",updatedAt:Ec(),baseBranch:t.worktreeBaseBranch,targetRepo:t.worktreePrTargetRepo,pushRemote:t.worktreePushRemote}}function Mv(t){return t.worktreeLifecycle?.baseBranch??t.worktreeBaseBranch??(lp(t.workdir)?wr(t.workdir):void 0)}function un(t,e={}){let r=$v(t),n=Ec(),o=new Set,i=lp(t.workdir),a=!!(t.worktreePath&&lp(t.worktreePath)),u=t.worktreeBranch,p=Mv(t),d=!1,l=!1,m=!1,c=!1,h,y,S=t.worktreePrUrl?"open":"none",I=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=Lo(t.workdir,u),d||o.add("branch_missing")),a&&t.worktreePath&&(l=Kn(t.worktreePath),l&&o.add("dirty_worktree_entries")),i&&d&&p){let or=kc(t.workdir,u,p);h=or?.ahead,y=or?.behind,m=Ic(t.workdir,u,p),m?o.add("topology_merged"):(c=xc(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=qo(t.workdir,u,t.worktreePrTargetRepo??r.targetRepo);S=or.state,I=or.url??I,x=or.number??x}S==="open"&&o.add("pr_open"),S==="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"||S==="open"||o.has("pr_merged_not_reflected_locally"),Ie=!C&&(R==="merged"||R==="released"||r.state==="dismissed"||r.state==="no_change"),Sr={checkedAt:n,repoExists:i,branchExists:d,worktreeExists:a,activeSession:e.activeSession===!0,dirtyTracked:l,topologyMerged:m,releaseNoopMerge:c,branchAheadCount:h,baseAheadCount:y,prState:S,prUrl:I,prNumber:x,reasons:[...o]};return{lifecycle:r,evidence:Sr,derivedState:R,cleanupSafe:Ie,preserve:C,reasons:[...o]}}var Bo=Be(()=>{No();dp();pp()});var Pt=Be(()=>{No();pp();Tc();dp();Bo()});function jn(t,e){let r=t.resolve(e),n=t.getPersistedSession(e),o=r?ye(r):n?ye(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}:void 0)}}function Hc(t){return t.persistedSession?ct(t.persistedSession):[]}function hb(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 As(t,e,r={}){let{activeSession:n,persistedSession:o}=hb(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 Ts(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 Rs(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 Cs(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 Wo=Be(()=>{Ee();Bo()});var rf={};Ct(rf,{buildPrMetadata:()=>ef,buildPrOutcomeDetailLines:()=>kp,formatPrBody:()=>tf,makeAgentPrTool:()=>jo});import{existsSync as kb}from"fs";function Ib(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function kp(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 Zc(t,e={preserveBlankLines:!0}){return t?.replace(/\r\n/g,`
8
+ `,"utf-8")}catch(a){console.warn(`[worktree] Failed to add ${i} to ${o}: ${a instanceof Error?a.message:String(a)}`)}}function gp(t,e,r={}){let n=wc(e),o=cs(t);Uv(t,o),Cc(o,{recursive:!0});let i=r.allowExistingBranch===!0,a,u,p=10,d=!1;for(let m=0;m<p;m++){let c=m===0?"":`-${Math.random().toString(16).slice(2,6)}`,h=`${o}/openclaw-worktree-${n}${c}`,y=`agent/${n}${c}`;if(!i&&Fo(t,y))continue;let k=!1;do{k=!1;try{Cc(h,{recursive:!1}),a=h,u=y;break}catch(S){if(qv(S,"EEXIST")){if(i&&m===0&&!d)try{fp(h,{recursive:!0,force:!0}),d=!0,k=!0}catch(x){throw new Error(`Failed to recreate existing worktree branch ${y}: could not clear blocked path ${h}: ${x instanceof Error?x.message:String(x)}`)}else if(i&&m===0)throw new Error(`Failed to recreate existing worktree branch ${y}: path ${h} remains blocked after one cleanup attempt`);continue}throw S}}while(k);if(a&&u)break}if(!a||!u)throw new Error(`Failed to create unique worktree directory and branch after ${p} attempts`);let l=Fo(t,u);try{l?Un("git",["-C",t,"worktree","add",a,u],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):Un("git",["-C",t,"worktree","add","-b",u,a],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(m){try{fp(a,{recursive:!0,force:!0})}catch{}throw m}return a}function Wn(t){if(!$c(t))return[];try{let e=Un("git",["-C",t,"status","--porcelain","--untracked-files=all"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e?e.split(`
9
+ `).map(r=>r.trim()).filter(Boolean):[]}catch{return[]}}function Kn(t){return Wn(t).length>0}function xt(t,e,r={}){let n=r.destructive===!0,o=Wn(e);if(o.length>0&&!n)return console.warn(`[worktree] Refusing implicit cleanup for dirty worktree ${e}: ${o[0]}`),!1;try{return Un("git",["-C",t,"worktree","remove",...n?["--force"]:[],e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(i){if(console.warn(`[worktree] git worktree remove failed for ${e}: ${i instanceof Error?i.message:String(i)}`),!n)return!1;try{return fp(e,{recursive:!0,force:!0}),console.info(`[worktree] Fallback rmSync succeeded for ${e}`),!0}catch(a){return console.error(`[worktree] Both git worktree remove and rmSync failed for ${e}: ${a instanceof Error?a.message:String(a)}`),!1}}}function hs(t){try{Un("git",["-C",t,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}var hp=De(()=>{qo()});import{execFileSync as Se}from"child_process";import{existsSync as Wv}from"fs";function sn(t,e,r){try{let n=Se("git",["-C",t,"rev-list","--count",`${r}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(n.trim(),10),a=Se("git",["-C",t,"diff","--shortstat",`${r}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),u=0,p=0,d=0,l=a.match(/(\d+)\s+files?\s+changed/);l&&(u=parseInt(l[1],10));let m=a.match(/(\d+)\s+insertions?\(/);m&&(p=parseInt(m[1],10));let c=a.match(/(\d+)\s+deletions?\(/);c&&(d=parseInt(c[1],10));let y=Se("git",["-C",t,"diff","--name-only","--diff-filter=ACMR",`${r}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
10
+ `).map(x=>x.trim()).filter(Boolean),S=Se("git",["-C",t,"log",`${r}..${e}`,"--format=%h|%s|%an","-n","5"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
11
+ `).filter(Boolean).map(x=>{let[R,$,C]=x.split("|");return{hash:R||"",message:$||"",author:C||""}});return{commits:o,filesChanged:u,insertions:p,deletions:d,changedFiles:y,commitMessages:S}}catch(n){console.warn(`[worktree] Failed to get diff summary: ${n instanceof Error?n.message:String(n)}`);return}}function ys(t,e,r="origin"){try{return Se("git",["-C",t,"push",r,e],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(n){return console.warn(`[worktree] Failed to push branch ${e}: ${n instanceof Error?n.message:String(n)}`),!1}}function Mc(t){try{return Se("git",["-C",t,"status","--porcelain"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).split(`
12
+ `).some(r=>r.length>0&&!r.startsWith("??")&&!r.startsWith("!!"))}catch{return!1}}function ks(t,e,r,n="merge",o){let i=!1,a,u=p=>{if(i)try{Se("git",["-C",p,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(n==="squash"){if(Se("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Mc(t)){let c;try{c=Se("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(h){return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${h instanceof Error?h.message:String(h)}. Commit or stash changes manually, then retry.`}}if(!c.includes("No local changes to save")){i=!0;try{a=Se("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}Se("git",["-C",t,"merge","--squash",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Se("git",["-C",t,"commit","-m",`Squash merge ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let m=!1;if(i)try{Se("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{m=!0}return{success:!0,stashed:i||void 0,stashRef:a,stashPopConflict:m||void 0}}let p=o&&Wv(o),d=p?o:t;if(p||Se("git",["-C",t,"checkout",e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Mc(t)){let m;try{m=Se("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(c){try{Se("git",["-C",t,"checkout",r],{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(!m.includes("No local changes to save")){i=!0;try{a=Se("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{Se("git",["-C",d,"rebase",r],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{Se("git",["-C",d,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{Se("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return u(t),{success:!1,rebaseConflict:!0,stashed:i||void 0,stashRef:a,error:[`Rebase of ${e} onto ${r} hit conflicts.`,"To resolve manually:",` cd ${d}`,` git rebase ${r}`," # resolve conflicts in each file, then:"," git add <file>"," git rebase --continue"," # repeat until rebase finishes, then re-run agent_merge."].join(`
13
+ `)}}Se("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Se("git",["-C",t,"merge","--ff-only",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let l=!1;if(i)try{Se("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{Se("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 Oc=De(()=>{});import{execFileSync as Ss}from"child_process";function _c(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=Ss("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:Ss("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 Bo(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=Ss("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 Dc(t,e,r,n){if(!Pr())return!1;try{let o=["pr","comment",String(e),"--body",r];return n&&o.push("--repo",n),Ss("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 yp=De(()=>{qo()});import{existsSync as kp}from"fs";function Lc(){return new Date().toISOString()}function Kv(t){return t.worktreeLifecycle??{state:t.worktreePath||t.worktreeBranch?"provisioned":"none",updatedAt:Lc(),baseBranch:t.worktreeBaseBranch,targetRepo:t.worktreePrTargetRepo,pushRemote:t.worktreePushRemote}}function jv(t){return t.worktreeLifecycle?.baseBranch??t.worktreeBaseBranch??(kp(t.workdir)?wr(t.workdir):void 0)}function un(t,e={}){let r=Kv(t),n=Lc(),o=new Set,i=kp(t.workdir),a=!!(t.worktreePath&&kp(t.worktreePath)),u=t.worktreeBranch,p=jv(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=Fo(t.workdir,u),d||o.add("branch_missing")),a&&t.worktreePath&&(l=Kn(t.worktreePath),l&&o.add("dirty_worktree_entries")),i&&d&&p){let or=bc(t.workdir,u,p);h=or?.ahead,y=or?.behind,m=Ac(t.workdir,u,p),m?o.add("topology_merged"):(c=Tc(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=Bo(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"),Ie=!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:Ie,preserve:C,reasons:[...o]}}var Uo=De(()=>{qo();yp();hp()});var Pt=De(()=>{qo();hp();Oc();yp();Uo()});function jn(t,e){let r=t.resolve(e),n=t.getPersistedSession(e),o=r?ye(r):n?ye(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}:void 0)}}function Ko(t){return[...t.persistedSession?lt(t.persistedSession):[],...t.activeSession?lt(t.activeSession):[]].filter((e,r,n)=>n.indexOf(e)===r)}function Rb(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 Cs(t,e,r={}){let{activeSession:n,persistedSession:o}=Rb(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 Es(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 $s(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 Ms(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 jo=De(()=>{Ee();Uo()});function Ds(t,e){return{...e,baseBranch:e.baseBranch??t.worktreeBaseBranch,targetRepo:e.targetRepo??t.worktreePrTargetRepo,pushRemote:e.pushRemote??t.worktreePushRemote}}function Ls(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:Ds(t,{state:"pending_decision",updatedAt:r,notes:e.notes})};return e.clearResolverSessionId&&(n.autoMergeResolverSessionId=void 0),n}function Xc(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:Ds(t,{state:"merge_conflict_resolving",updatedAt:o,notes:n.notes})}}function Fs(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:Ds(t,{state:"merged",updatedAt:r,resolvedAt:n,resolutionSource:e.resolutionSource??"agent_merge"})};return e.clearResolverSessionId&&(o.autoMergeResolverSessionId=void 0),o}function ef(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:Ds(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 Ns=De(()=>{});var df={};Ct(df,{buildPrMetadata:()=>uf,buildPrOutcomeDetailLines:()=>Ap,formatPrBody:()=>pf,makeAgentPrTool:()=>Vo});import{existsSync as $b}from"fs";function Mb(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function Ap(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 sf(t,e={preserveBlankLines:!0}){return t?.replace(/\r\n/g,`
14
14
  `).split(`
15
15
  `).map(n=>n.trim()).reduce((n,o)=>o?(n.push(o),n):(e.preserveBlankLines&&n[n.length-1]!==""&&n.push(o),n),[]).join(e.preserveBlankLines?`
16
- `:" ").replace(/[ \t]+/g," ").trim()||void 0}function xb(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3)).trimEnd()}...`}function Ip(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_-]{${Yc},}\\b`,"g"),"[redacted token]")}function zc(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_-]{${Yc},}\\b`).test(t)}function Pb(t){let e=Zc(t);if(!e)return;let r=e.match(/^[^.!?]+[.!?]/)?.[0]??e,n=Ip(r).replace(/\s+/g," ").trim();return n?xb(n,180):void 0}function Xc(t){return Ip(t.trim()).replace(/\s+/g," ").trim()}function wb(t,e){return t?.commitMessages.map(r=>Xc(r.message)).filter(Boolean).slice(0,e)??[]}function vb(){return["Not recorded by agent_pr. Review CI/checks and session output before merging."]}function bb(){return["Generated PR metadata omits full task prompts and redacts sensitive-looking prompt details.","Review touched areas for behavior, security, and privacy impact."]}function Ab(t){let e=Pb(t.prompt),r=t.diffSummary;return{sessionName:t.sessionName,objective:e,stats:r?{commits:r.commits,filesChanged:r.filesChanged,insertions:r.insertions,deletions:r.deletions}:void 0,changedFiles:r?.changedFiles??[],commitSubjects:wb(r,5),validation:vb(),notes:bb()}}function Ms(t,e,r){return Array.isArray(t)&&t.length>0&&t.length<=e&&t.every(n=>typeof n=="string"&&n.trim().length>0&&n.length<=r)}function Tb(t,e){let r=Zc(t);if(!r)return[];let n=e?.toLowerCase();return r.split(/[.!?\n]/).map(o=>o.trim()).filter(o=>o.length>=24).filter(o=>!n||o.toLowerCase()!==n.replace(/[.!?]$/,"")).map(o=>o.toLowerCase())}function Jc(t,e,r){let n=t.toLowerCase();return Tb(e,r.objective).some(o=>n.includes(o))}function Qc(t){return/^(?:node|next|nuxt|vue|express|nest|three|d3|chart|ember|backbone|require)\.js$/i.test(t)}function Rb(t,e){let r=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)&&!r.has(c)))return!0;let o=new Set(e.changedFiles.filter(c=>!c.includes("/"))),i=String.raw`\.[a-z0-9][\w.-]*`,a=t.matchAll(new RegExp(`[\\\`"'](${i})[\\\`"']`,"g"));for(let c of a)if(!o.has(c[1]))return!0;let u=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 u)if(!o.has(c[1]))return!0;if(o.size===0)return!1;let p=new Set([...o].map(c=>c.match(/\.([A-Za-z0-9]+)$/)?.[1]?.toLowerCase()).filter(c=>!!c)),d=String.raw`[A-Za-z0-9][\w.-]*\.([A-Za-z0-9]+)`,l=t.matchAll(new RegExp(`[\\\`"'](${d})[\\\`"']`,"g"));for(let c of l){let h=c[1],y=c[2]?.toLowerCase();if(y!==void 0&&p.has(y)&&!o.has(h)&&!Qc(h))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+)?(${d})\b`,"gi"))].some(c=>{let h=c[1],y=c[2]?.toLowerCase();return y!==void 0&&p.has(y)&&!o.has(h)&&!Qc(h)})}function Ko(t){return Ip(t).replace(/\s+/g," ").trim()}function Cb(t,e,r){if(!t||typeof t!="object")return;let n=t;if(typeof n.title!="string"||n.title.trim().length===0||n.title.length>90||!Ms(n.summary,5,180)||!Ms(n.changes,10,160)||!Ms(n.validation,5,160)||!Ms(n.notes,5,180)||[n.title,...n.summary,...n.changes,...n.validation,...n.notes].some(u=>zc(u)||Jc(u,r,e)))return;let i={title:Ko(n.title),summary:n.summary.map(Ko),changes:n.changes.map(Ko),validation:n.validation.map(Ko),notes:n.notes.map(Ko)},a=[i.title,...i.summary,...i.changes,...i.validation,...i.notes];if(!a.some(u=>!u||zc(u)||Jc(u,r,e))&&!a.some(u=>Rb(u,e)))return i}async function ef(t){let e=Ab(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 r=await t.provider.generatePrMetadata(e),n=Cb(r,e,t.prompt);return n?{ok:!0,metadata:n,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(r){return console.warn(`[agent_pr] PR metadata provider failed: ${r instanceof Error?r.message:String(r)}`),{ok:!1,error:"PR metadata provider failed. Pass explicit title/body or retry after the provider is healthy.",evidence:e}}}function tf(t){let e=[`OpenClaw Code Agent session: ${t.sessionName}`,"","## Summary",...t.metadata.summary.map(r=>`- ${r}`),"","## Changes",...t.metadata.changes.map(r=>`- ${r}`),""];if(t.diffSummary){let r=t.diffSummary.commitMessages.slice(0,5).map(o=>`- ${o.hash} ${Xc(o.message)} (${o.author})`),n=t.diffSummary.commits>5?[`- ...and ${t.diffSummary.commits-5} more`]:[];r.length>0&&e.push("## Commits",...r,...n,"")}return e.push("## Validation",...t.metadata.validation.map(r=>`- ${r}`),"","## Notes / Risks",...t.metadata.notes.map(r=>`- ${r}`),""),e.push("---","Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"),e.join(`
17
- `)}function jo(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:f.Object({session:f.String({description:"Session name or ID to create/update PR for"}),title:f.Optional(f.String({description:"PR title (default: auto-generated from session name)"})),body:f.Optional(f.String({description:"PR body (default: auto-generated from commit summary)"})),base_branch:f.Optional(f.String({description:"Base branch for the PR (default: detected from repo)"})),force_new:f.Optional(f.Boolean({description:"Force creation of a new PR even if one exists (default: false)"})),target_repo:f.Optional(f.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex'). Auto-detected from 'upstream' remote if not set."}))}),async execute(r,n){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}],meta:{success:!1,state:"error"}};if(!Ib(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}],meta:{success:!1,state:"error"}};if(!Pr())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=jn(k,n.session),i=o.activeSession,a=o.persistedSession;if(!i&&!a)return{content:[{type:"text",text:`Error: Session "${n.session}" not found.`}],meta:{success:!1,state:"error"}};let{worktreePath:u,originalWorkdir:p,sessionName:d,branchName:l}=o;if(!u||!p)return{content:[{type:"text",text:`Error: Session "${n.session}" does not have a worktree.`}],meta:{success:!1,state:"error"}};if(!l)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree ${u}. The worktree may have been removed and no persisted branch name is available.`}],meta:{success:!1,state:"error"}};kb(u)||console.info(`[agent_pr] Worktree directory ${u} no longer exists; proceeding with branch "${l}" via originalWorkdir (${p})`);let m=n.base_branch??wr(p),c=o.persistedRef,h=Pc(p,n.target_repo??a?.worktreePrTargetRepo);if(!fs(p,l))return{content:[{type:"text",text:`\u274C Failed to push ${l} \u2014 cannot create/update PR`}],meta:{success:!1,state:"error"}};let y=qo(p,l,h);if(n.force_new&&y.exists)return{content:[{type:"text",text:`\u26A0\uFE0F Cannot create new PR: A PR already exists for ${l} (${y.state}).
16
+ `:" ").replace(/[ \t]+/g," ").trim()||void 0}function Ob(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3)).trimEnd()}...`}function Tp(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_-]{${of},}\\b`,"g"),"[redacted token]")}function tf(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_-]{${of},}\\b`).test(t)}function _b(t){let e=sf(t);if(!e)return;let r=e.match(/^[^.!?]+[.!?]/)?.[0]??e,n=Tp(r).replace(/\s+/g," ").trim();return n?Ob(n,180):void 0}function af(t){return Tp(t.trim()).replace(/\s+/g," ").trim()}function Db(t,e){return t?.commitMessages.map(r=>af(r.message)).filter(Boolean).slice(0,e)??[]}function Lb(){return["Not recorded by agent_pr. Review CI/checks and session output before merging."]}function Fb(){return["Generated PR metadata omits full task prompts and redacts sensitive-looking prompt details.","Review touched areas for behavior, security, and privacy impact."]}function Nb(t){let e=_b(t.prompt),r=t.diffSummary;return{sessionName:t.sessionName,objective:e,stats:r?{commits:r.commits,filesChanged:r.filesChanged,insertions:r.insertions,deletions:r.deletions}:void 0,changedFiles:r?.changedFiles??[],commitSubjects:Db(r,5),validation:Lb(),notes:Fb()}}function qs(t,e,r){return Array.isArray(t)&&t.length>0&&t.length<=e&&t.every(n=>typeof n=="string"&&n.trim().length>0&&n.length<=r)}function qb(t,e){let r=sf(t);if(!r)return[];let n=e?.toLowerCase();return r.split(/[.!?\n]/).map(o=>o.trim()).filter(o=>o.length>=24).filter(o=>!n||o.toLowerCase()!==n.replace(/[.!?]$/,"")).map(o=>o.toLowerCase())}function rf(t,e,r){let n=t.toLowerCase();return qb(e,r.objective).some(o=>n.includes(o))}function nf(t){return/^(?:node|next|nuxt|vue|express|nest|three|d3|chart|ember|backbone|require)\.js$/i.test(t)}function Bb(t,e){let r=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)&&!r.has(c)))return!0;let o=new Set(e.changedFiles.filter(c=>!c.includes("/"))),i=String.raw`\.[a-z0-9][\w.-]*`,a=t.matchAll(new RegExp(`[\\\`"'](${i})[\\\`"']`,"g"));for(let c of a)if(!o.has(c[1]))return!0;let u=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 u)if(!o.has(c[1]))return!0;if(o.size===0)return!1;let p=new Set([...o].map(c=>c.match(/\.([A-Za-z0-9]+)$/)?.[1]?.toLowerCase()).filter(c=>!!c)),d=String.raw`[A-Za-z0-9][\w.-]*\.([A-Za-z0-9]+)`,l=t.matchAll(new RegExp(`[\\\`"'](${d})[\\\`"']`,"g"));for(let c of l){let h=c[1],y=c[2]?.toLowerCase();if(y!==void 0&&p.has(y)&&!o.has(h)&&!nf(h))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+)?(${d})\b`,"gi"))].some(c=>{let h=c[1],y=c[2]?.toLowerCase();return y!==void 0&&p.has(y)&&!o.has(h)&&!nf(h)})}function Go(t){return Tp(t).replace(/\s+/g," ").trim()}function Ub(t,e,r){if(!t||typeof t!="object")return;let n=t;if(typeof n.title!="string"||n.title.trim().length===0||n.title.length>90||!qs(n.summary,5,180)||!qs(n.changes,10,160)||!qs(n.validation,5,160)||!qs(n.notes,5,180)||[n.title,...n.summary,...n.changes,...n.validation,...n.notes].some(u=>tf(u)||rf(u,r,e)))return;let i={title:Go(n.title),summary:n.summary.map(Go),changes:n.changes.map(Go),validation:n.validation.map(Go),notes:n.notes.map(Go)},a=[i.title,...i.summary,...i.changes,...i.validation,...i.notes];if(!a.some(u=>!u||tf(u)||rf(u,r,e))&&!a.some(u=>Bb(u,e)))return i}async function uf(t){let e=Nb(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 r=await t.provider.generatePrMetadata(e),n=Ub(r,e,t.prompt);return n?{ok:!0,metadata:n,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(r){return console.warn(`[agent_pr] PR metadata provider failed: ${r instanceof Error?r.message:String(r)}`),{ok:!1,error:"PR metadata provider failed. Pass explicit title/body or retry after the provider is healthy.",evidence:e}}}function pf(t){let e=[`OpenClaw Code Agent session: ${t.sessionName}`,"","## Summary",...t.metadata.summary.map(r=>`- ${r}`),"","## Changes",...t.metadata.changes.map(r=>`- ${r}`),""];if(t.diffSummary){let r=t.diffSummary.commitMessages.slice(0,5).map(o=>`- ${o.hash} ${af(o.message)} (${o.author})`),n=t.diffSummary.commits>5?[`- ...and ${t.diffSummary.commits-5} more`]:[];r.length>0&&e.push("## Commits",...r,...n,"")}return e.push("## Validation",...t.metadata.validation.map(r=>`- ${r}`),"","## Notes / Risks",...t.metadata.notes.map(r=>`- ${r}`),""),e.push("---","Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"),e.join(`
17
+ `)}function Vo(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:f.Object({session:f.String({description:"Session name or ID to create/update PR for"}),title:f.Optional(f.String({description:"PR title (default: auto-generated from session name)"})),body:f.Optional(f.String({description:"PR body (default: auto-generated from commit summary)"})),base_branch:f.Optional(f.String({description:"Base branch for the PR (default: detected from repo)"})),force_new:f.Optional(f.Boolean({description:"Force creation of a new PR even if one exists (default: false)"})),target_repo:f.Optional(f.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex'). Auto-detected from 'upstream' remote if not set."}))}),async execute(r,n){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}],meta:{success:!1,state:"error"}};if(!Mb(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}],meta:{success:!1,state:"error"}};if(!Pr())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=jn(I,n.session),i=o.activeSession,a=o.persistedSession;if(!i&&!a)return{content:[{type:"text",text:`Error: Session "${n.session}" not found.`}],meta:{success:!1,state:"error"}};let{worktreePath:u,originalWorkdir:p,sessionName:d,branchName:l}=o;if(!u||!p)return{content:[{type:"text",text:`Error: Session "${n.session}" does not have a worktree.`}],meta:{success:!1,state:"error"}};if(!l)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree ${u}. The worktree may have been removed and no persisted branch name is available.`}],meta:{success:!1,state:"error"}};$b(u)||console.info(`[agent_pr] Worktree directory ${u} no longer exists; proceeding with branch "${l}" via originalWorkdir (${p})`);let m=n.base_branch??wr(p),c=k=>{let S=ef({worktreeBaseBranch:a?.worktreeBaseBranch??i?.worktreeBaseBranch??m,worktreePrTargetRepo:a?.worktreePrTargetRepo??i?.worktreePrTargetRepo,worktreePushRemote:a?.worktreePushRemote??i?.worktreePushRemote},{prUrl:k.prUrl,prNumber:k.prNumber,baseBranch:m,targetRepo:k.targetRepo,disposition:k.disposition});for(let x of Ko(o))I.updatePersistedSession(x,S)},h=Rc(p,n.target_repo??a?.worktreePrTargetRepo);if(!ys(p,l))return{content:[{type:"text",text:`\u274C Failed to push ${l} \u2014 cannot create/update PR`}],meta:{success:!1,state:"error"}};let y=Bo(p,l,h);if(n.force_new&&y.exists)return{content:[{type:"text",text:`\u26A0\uFE0F Cannot create new PR: A PR already exists for ${l} (${y.state}).
18
18
 
19
19
  Existing PR: ${y.url}
20
20
 
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(y.exists&&y.state==="open"){let S=sn(p,l,m);if(S&&S.commits>0){let I=S.commitMessages.slice(0,5).map(C=>`\u2022 ${C.hash} ${C.message} (${C.author})`).join(`
22
- `),x=S.commits>5?`
23
- ...and ${S.commits-5} more commits`:"",R=["\u{1F504} **New commits pushed**","",`${S.commits} new commits (+${S.insertions} / -${S.deletions})`,"","### Latest commits:",I+x,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
24
- `);if(Cc(p,y.number,R,h)){c&&k.updatePersistedSession(c,{worktreePrUrl:y.url,worktreePrNumber:y.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:m,targetRepo:h,pushRemote:a?.worktreePushRemote}});let C=an({kind:"pr-updated",branch:l,prUrl:y.url});return k.notifyWorktreeOutcome(o.notificationTarget,C,{detailLines:kp({action:"updated",branchName:l,baseBranch:m,prUrl:y.url,prNumber:y.number,targetRepo:h,commits:S.commits,insertions:S.insertions,deletions:S.deletions})}),{content:[{type:"text",text:`${C}
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(y.exists&&y.state==="open"){let k=sn(p,l,m);if(k&&k.commits>0){let S=k.commitMessages.slice(0,5).map(C=>`\u2022 ${C.hash} ${C.message} (${C.author})`).join(`
22
+ `),x=k.commits>5?`
23
+ ...and ${k.commits-5} more commits`:"",R=["\u{1F504} **New commits pushed**","",`${k.commits} new commits (+${k.insertions} / -${k.deletions})`,"","### Latest commits:",S+x,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
24
+ `);if(Dc(p,y.number,R,h)){c({prUrl:y.url,prNumber:y.number,targetRepo:h});let C=an({kind:"pr-updated",branch:l,prUrl:y.url});return I.notifyWorktreeOutcome(o.notificationTarget,C,{detailLines:Ap({action:"updated",branchName:l,baseBranch:m,prUrl:y.url,prNumber:y.number,targetRepo:h,commits:k.commits,insertions:k.insertions,deletions:k.deletions})}),{content:[{type:"text",text:`${C}
25
25
 
26
- \u{1F4DD} Added comment detailing ${S.commits} new commits (+${S.insertions} / -${S.deletions})`}],meta:{success:!0,state:"pr_updated"}}}else return{content:[{type:"text",text:`\u26A0\uFE0F Pushed to ${y.url} but failed to add comment.
26
+ \u{1F4DD} Added comment detailing ${k.commits} new commits (+${k.insertions} / -${k.deletions})`}],meta:{success:!0,state:"pr_updated"}}}else return{content:[{type:"text",text:`\u26A0\uFE0F Pushed to ${y.url} but failed to add comment.
27
27
 
28
- ${S.commits} new commits (+${S.insertions} / -${S.deletions})`}],meta:{success:!0,state:"pr_open"}}}else return c&&k.updatePersistedSession(c,{worktreePrUrl:y.url,worktreePrNumber:y.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:m,targetRepo:h,pushRemote:a?.worktreePushRemote}}),{content:[{type:"text",text:`\u2139\uFE0F PR already exists and is up to date: ${y.url}
28
+ ${k.commits} new commits (+${k.insertions} / -${k.deletions})`}],meta:{success:!0,state:"pr_open"}}}else return c({prUrl:y.url,prNumber:y.number,targetRepo:h}),{content:[{type:"text",text:`\u2139\uFE0F PR already exists and is up to date: ${y.url}
29
29
 
30
- No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else{if(y.exists&&y.state==="merged")return c&&k.updatePersistedSession(c,{worktreePrUrl:y.url,worktreePrNumber:y.number,worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDisposition:"merged",worktreeLifecycle:{state:"merged",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"agent_pr",baseBranch:m,targetRepo:h,pushRemote:a?.worktreePushRemote}}),{content:[{type:"text",text:`\u2705 PR was already merged: ${y.url}
30
+ No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else if(y.exists&&y.state==="merged"){let k={...Fs({worktreeBaseBranch:a?.worktreeBaseBranch??i?.worktreeBaseBranch??m,worktreePrTargetRepo:a?.worktreePrTargetRepo??i?.worktreePrTargetRepo,worktreePushRemote:a?.worktreePushRemote??i?.worktreePushRemote},{resolutionSource:"agent_pr",clearResolverSessionId:!0}),worktreePrUrl:y.url,worktreePrNumber:y.number,worktreeDisposition:"merged",worktreeDecisionSnoozedUntil:void 0};for(let S of Ko(o))I.updatePersistedSession(S,k);return{content:[{type:"text",text:`\u2705 PR was already merged: ${y.url}
31
31
 
32
- The worktree branch ${l} can be cleaned up with agent_merge(delete_branch=true).`}],meta:{success:!0,state:"merged"}};if(y.exists&&y.state==="closed")return{content:[{type:"text",text:`\u26A0\uFE0F A PR exists but was closed without merging: ${y.url}
32
+ The worktree branch ${l} can be cleaned up with agent_merge(delete_branch=true).`}],meta:{success:!0,state:"merged"}}}else{if(y.exists&&y.state==="closed")return{content:[{type:"text",text:`\u26A0\uFE0F A PR exists but was closed without merging: ${y.url}
33
33
 
34
34
  What would you like to do?
35
35
 
@@ -37,191 +37,198 @@ What would you like to do?
37
37
  2. Close and delete the branch with agent_merge(delete_branch=true), then start a new session/worktree
38
38
  3. Manually delete the closed PR on GitHub, then call agent_pr(force_new=true) to create a fresh PR
39
39
 
40
- (This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}],meta:{success:!1,state:"closed"}};{let S=!n.title||!n.body?sn(p,l,m):void 0,I;if(!n.title||!n.body){let C=await ef({sessionName:d,prompt:o.prompt,diffSummary:S,provider:e.metadataProvider});if(C.ok===!1)return{content:[{type:"text",text:`\u274C ${C.error}`}],meta:{success:!1,state:"error"}};I=C.metadata}let x=n.title??I.title,R=n.body;R||(R=tf({sessionName:d,metadata:I,diffSummary:S}));let $=Rc(p,l,m,x,R,h);if($.success&&$.prUrl){let C=qo(p,l,h);c&&k.updatePersistedSession(c,{worktreePrUrl:$.prUrl,worktreePrNumber:C.number,lifecycle:"terminal",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeState:"pr_open",worktreeDisposition:"pr-opened",worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:m,targetRepo:h,pushRemote:a?.worktreePushRemote}});let Ie=an({kind:"pr-opened",branch:l,targetRepo:h,prUrl:$.prUrl});return k.notifyWorktreeOutcome(o.notificationTarget,Ie,{detailLines:kp({action:"opened",branchName:l,baseBranch:m,prUrl:$.prUrl,prNumber:C.number,targetRepo:h})}),{content:[{type:"text",text:Ie}],meta:{success:!0,state:"created"}}}else return{content:[{type:"text",text:`\u274C Failed to create PR: ${$.error??"unknown error"}`}],meta:{success:!1,state:"error"}}}}}}}var Yc,Os=Be(()=>{tt();le();Pt();Wo();Yc=32});import{readdirSync as p0,statSync as d0,rmSync as l0}from"fs";import{execFileSync as m0}from"child_process";import{join as ZP}from"path";tt();le();function ow(t){return t.length>80?`${t.slice(0,80)}...`:t}function iw(t){return t.worktreePath?!t.originalWorkdir||t.originalWorkdir===t.worktreePath?`${t.worktreePath} (worktree)`:`${t.worktreePath} (worktree of ${t.originalWorkdir})`:t.workdir}function sw(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: ${iw(t)}`,` Model: ${t.model??"default"}`,` Prompt: "${ow(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(`
41
- `)}function Ei(t,e){return sw({...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})}ze();function _n(t){let{requestedResumeSessionId:e,activeSession:r,persistedSession:n}=t;return e?r?{resumeSessionId:e,clearedPersistedCodexResume:!1}:n?.harness==="codex"&&n.backendRef?.kind!=="codex-app-server"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:e,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}Ee();function zi(t){return"id"in t?t.id:t.sessionId}function Oo(t){return t.status==="completed"||t.killReason==="done"}function Vw(t){return Oo(t)&&t.backendRef?.kind==="codex-app-server"&&!!q(t)}function Hw(t){return(t.killReason==="shutdown"||t.killReason==="startup-timeout")&&!q(t)}function _o(t){if(t.status==="running")return{kind:"direct",reason:"already_running"};let e=zi(t);if(Oo(t)&&!Vw(t))return{kind:"unavailable",reason:"completed",stableSessionId:e};let r=q(t);if(r){let n="harnessName"in t?void 0:t,{resumeSessionId:o,clearedPersistedCodexResume:i}=_n({requestedResumeSessionId:r,activeSession:"harnessName"in t?{harnessSessionId:r}:void 0,persistedSession:n?{harness:n.harness,backendRef:n.backendRef}:void 0});return o?{kind:"resume",resumeSessionId:o,stableSessionId:e,clearedPersistedCodexResume:i}:{kind:"unavailable",reason:"legacy_non_resumable",stableSessionId:e,clearedPersistedCodexResume:i}}return Hw(t)?{kind:"relaunch",stableSessionId:e}:{kind:"unavailable",reason:"missing_backend_state",stableSessionId:e}}ze();import{existsSync as Ym}from"fs";function Ji(t,e){if(!e||e.length===0)return!0;if(!t)return!1;let r=t.toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}Ee();function zm(t){return t==null?void 0:String(t).trim()||void 0}function zw(t){return t.trim().replace(/^['"`](.*)['"`]$/s,"$1").trim()}function Jw(t){let e=t.split(/\n\s*\n/,1)[0]?.split(`
42
- `).map(r=>r.trim()).filter(Boolean)??[];if(e.length!==0)for(let r of e){let n=r.match(/^(Workdir|Repo):\s*(.+)$/),o=zw(n?.[2]??"");if(o.startsWith("/")&&Ym(o))return o}}function Jm(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&&zm(t.originThreadId)===zm(e.originThreadId)}function Qm(t){return t.slice(0,3).map(e=>` - ${e.name} [${e.ref}] | status=${e.status}${e.lifecycle?` | lifecycle=${e.lifecycle}`:""}`).join(`
43
- `)}function Qw(t,e){let r=[],n=[],o=new Set;for(let i of t.list?.("all")??[]){if(!Jm(i,e))continue;let a=i.id;if(!o.has(a)){if(o.add(a),i.isExplicitlyResumable){r.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0});continue}(i.status==="starting"||i.status==="running")&&n.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!1})}}for(let i of t.listPersistedSessions?.()??[]){if(!i.resumable||!Jm(i,e))continue;let a=ye(i)??i.harnessSessionId,u=i.sessionId??q(i)??i.harnessSessionId;!a||!u||o.has(u)||(o.add(u),r.push({ref:a,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0}))}return{resumable:r,active:n}}function Qi(t,e,r){let n=t.workdir||Jw(t.prompt)||e.workspaceDir||K.defaultWorkdir||process.cwd();if(!Ym(n))return{kind:"error",text:`Error: Working directory does not exist: ${n}`};let o=t.harness??dt(),i=$n(o),a=t.model??i,u=t.model!==void 0;if(!a)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.`};let p=_i(o);if(p&&p.length>0&&!Ji(a,p))return{kind:"error",text:u?`Error: Model "${a}" is not allowed. Permitted models: ${p.join(", ")}`:`Error: Default model "${a||"undefined"}" is not in allowedModels (${p.join(", ")}). Update your plugin config to set a compatible defaultModel.`};let d=Di(e),l=bo(e,d||Ao(n)),m=e.sessionKey||void 0,c=vm(m)??Ju(e);if(!t.resume_session_id&&!t.force_new_session){let C=Qw(r,{workdir:n,originSessionKey:m,originChannel:l,originThreadId:c});if(C.resumable.length>0||C.active.length>0){let Ie=C.resumable.length>0?["Linked resumable session(s) already exist for this thread/workdir:",Qm(C.resumable),"","Resume the latest one with:",` agent_respond(session='${C.resumable[0].ref}', message='<next instruction>')`,"Fork from it with:",` agent_launch(prompt='<new task>', resume_session_id='${C.resumable[0].ref}', fork_session=true)`].join(`
44
- `):"",Sr=C.active.length>0?[C.resumable.length>0?"Linked active session(s):":"Linked active session(s) already exist for this thread/workdir:",Qm(C.active),"","Send a follow-up instead of launching a duplicate:",` agent_respond(session='${C.active[0].ref}', message='<next instruction>')`].join(`
45
- `):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",Ie,Sr,["If you intentionally want a brand-new independent session here, call:"," agent_launch(prompt='<new task>', force_new_session=true)"].join(`
40
+ (This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}],meta:{success:!1,state:"closed"}};{let k=!n.title||!n.body?sn(p,l,m):void 0,S;if(!n.title||!n.body){let C=await uf({sessionName:d,prompt:o.prompt,diffSummary:k,provider:e.metadataProvider});if(C.ok===!1)return{content:[{type:"text",text:`\u274C ${C.error}`}],meta:{success:!1,state:"error"}};S=C.metadata}let x=n.title??S.title,R=n.body;R||(R=pf({sessionName:d,metadata:S,diffSummary:k}));let $=_c(p,l,m,x,R,h);if($.success&&$.prUrl){let C=Bo(p,l,h);c({prUrl:$.prUrl,prNumber:C.number,targetRepo:h,disposition:"pr-opened"});let Ie=an({kind:"pr-opened",branch:l,targetRepo:h,prUrl:$.prUrl});return I.notifyWorktreeOutcome(o.notificationTarget,Ie,{detailLines:Ap({action:"opened",branchName:l,baseBranch:m,prUrl:$.prUrl,prNumber:C.number,targetRepo:h})}),{content:[{type:"text",text:Ie}],meta:{success:!0,state:"created"}}}else return{content:[{type:"text",text:`\u274C Failed to create PR: ${$.error??"unknown error"}`}],meta:{success:!1,state:"error"}}}}}}}var of,Bs=De(()=>{tt();le();Pt();Ns();jo();of=32});import{readdirSync as D0,statSync as L0,rmSync as F0}from"fs";import{execFileSync as N0}from"child_process";import{join as dw}from"path";tt();le();function hw(t){return t.length>80?`${t.slice(0,80)}...`:t}function yw(t){return t.worktreePath?!t.originalWorkdir||t.originalWorkdir===t.worktreePath?`${t.worktreePath} (worktree)`:`${t.worktreePath} (worktree of ${t.originalWorkdir})`:t.workdir}function kw(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: ${yw(t)}`,` Model: ${t.model??"default"}`,` Prompt: "${hw(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(`
41
+ `)}function Oi(t,e){return kw({...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})}ze();function _n(t){let{requestedResumeSessionId:e,activeSession:r,persistedSession:n}=t;return e?r?{resumeSessionId:e,clearedPersistedCodexResume:!1}:n?.harness==="codex"&&n.backendRef?.kind!=="codex-app-server"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:e,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}Ee();function Qi(t){return"id"in t?t.id:t.sessionId}function _o(t){return t.status==="completed"||t.killReason==="done"}function ov(t){return _o(t)&&t.backendRef?.kind==="codex-app-server"&&!!q(t)}function iv(t){return(t.killReason==="shutdown"||t.killReason==="startup-timeout")&&!q(t)}function Do(t){if(t.status==="running")return{kind:"direct",reason:"already_running"};let e=Qi(t);if(_o(t)&&!ov(t))return{kind:"unavailable",reason:"completed",stableSessionId:e};let r=q(t);if(r){let n="harnessName"in t?void 0:t,{resumeSessionId:o,clearedPersistedCodexResume:i}=_n({requestedResumeSessionId:r,activeSession:"harnessName"in t?{harnessSessionId:r}:void 0,persistedSession:n?{harness:n.harness,backendRef:n.backendRef}:void 0});return o?{kind:"resume",resumeSessionId:o,stableSessionId:e,clearedPersistedCodexResume:i}:{kind:"unavailable",reason:"legacy_non_resumable",stableSessionId:e,clearedPersistedCodexResume:i}}return iv(t)?{kind:"relaunch",stableSessionId:e}:{kind:"unavailable",reason:"missing_backend_state",stableSessionId:e}}ze();import{existsSync as oc}from"fs";function Yi(t,e){if(!e||e.length===0)return!0;if(!t)return!1;let r=t.toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}Ee();function tc(t){return t==null?void 0:String(t).trim()||void 0}function sv(t){return t.trim().replace(/^['"`](.*)['"`]$/s,"$1").trim()}function av(t){let e=t.split(/\n\s*\n/,1)[0]?.split(`
42
+ `).map(r=>r.trim()).filter(Boolean)??[];if(e.length!==0)for(let r of e){let n=r.match(/^(Workdir|Repo):\s*(.+)$/),o=sv(n?.[2]??"");if(o.startsWith("/")&&oc(o))return o}}function rc(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&&tc(t.originThreadId)===tc(e.originThreadId)}function nc(t){return t.slice(0,3).map(e=>` - ${e.name} [${e.ref}] | status=${e.status}${e.lifecycle?` | lifecycle=${e.lifecycle}`:""}`).join(`
43
+ `)}function uv(t,e){let r=[],n=[],o=new Set;for(let i of t.list?.("all")??[]){if(!rc(i,e))continue;let a=i.id;if(!o.has(a)){if(o.add(a),i.isExplicitlyResumable){r.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0});continue}(i.status==="starting"||i.status==="running")&&n.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!1})}}for(let i of t.listPersistedSessions?.()??[]){if(!i.resumable||!rc(i,e))continue;let a=ye(i)??i.harnessSessionId,u=i.sessionId??q(i)??i.harnessSessionId;!a||!u||o.has(u)||(o.add(u),r.push({ref:a,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0}))}return{resumable:r,active:n}}function Zi(t,e,r){let n=t.workdir||av(t.prompt)||e.workspaceDir||K.defaultWorkdir||process.cwd();if(!oc(n))return{kind:"error",text:`Error: Working directory does not exist: ${n}`};let o=t.harness??dt(),i=$n(o),a=t.model??i,u=t.model!==void 0;if(!a)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.`};let p=Li(o);if(p&&p.length>0&&!Yi(a,p))return{kind:"error",text:u?`Error: Model "${a}" is not allowed. Permitted models: ${p.join(", ")}`:`Error: Default model "${a||"undefined"}" is not in allowedModels (${p.join(", ")}). Update your plugin config to set a compatible defaultModel.`};let d=Fi(e),l=Ao(e,d||To(n)),m=e.sessionKey||void 0,c=$m(m)??rp(e);if(!t.resume_session_id&&!t.force_new_session){let C=uv(r,{workdir:n,originSessionKey:m,originChannel:l,originThreadId:c});if(C.resumable.length>0||C.active.length>0){let Ie=C.resumable.length>0?["Linked resumable session(s) already exist for this thread/workdir:",nc(C.resumable),"","Resume the latest one with:",` agent_respond(session='${C.resumable[0].ref}', message='<next instruction>')`,"Fork from it with:",` agent_launch(prompt='<new task>', resume_session_id='${C.resumable[0].ref}', fork_session=true)`].join(`
44
+ `):"",kr=C.active.length>0?[C.resumable.length>0?"Linked active session(s):":"Linked active session(s) already exist for this thread/workdir:",nc(C.active),"","Send a follow-up instead of launching a duplicate:",` agent_respond(session='${C.active[0].ref}', message='<next instruction>')`].join(`
45
+ `):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",Ie,kr,["If you intentionally want a brand-new independent session here, call:"," agent_launch(prompt='<new task>', force_new_session=true)"].join(`
46
46
  `)].filter(Boolean).join(`
47
47
 
48
- `)}}}let h=t.resume_session_id,y=h?r.resolve?.(h):void 0,S=h?r.getPersistedSession?.(h):void 0;if(h){let C=r.resolveBackendConversationId?.(h)??r.resolveHarnessSessionId?.(h);if(!C)return{kind:"error",text:`Error: Could not resolve resume_session_id "${h}" to a session ID. Use agent_sessions to list available sessions.`};h=C}let{resumeSessionId:I,clearedPersistedCodexResume:x}=_n({requestedResumeSessionId:h,activeSession:y?{harnessSessionId:y.backendConversationId??y.harnessSessionId}:void 0,persistedSession:S?{harness:S.harness,backendRef:S.backendRef}:void 0}),R=t.permission_mode??K.permissionMode,$=t.plan_approval??K.planApproval;return{kind:"resolved",workdir:n,harness:o,resolvedModel:a,permissionMode:R,planApproval:$,originChannel:l,originThreadId:c,originSessionKey:m,route:On(e,l,m),resumeSessionId:I,resolvedResumeId:h,clearedPersistedCodexResume:x,reasoningEffort:Ir(o),fastMode:Mn(o)}}Ee();function Ft(t){let e=Math.floor(t/1e3),r=Math.floor(e/60),n=e%60;return r>0?`${r}m${n}s`:`${n}s`}var Yw=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 Xm(t){let r=t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>1&&!Yw.has(n)).slice(0,3);return r.length===0?"session":r.join("-")}var Zm={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4",awaiting_plan_decision:"\u{1F4CB}",awaiting_user_input:"\u2753",awaiting_worktree_decision:"\u{1F33F}",suspended:"\u23F8\uFE0F",terminal:"\u{1F3C1}"};function Zw(t){let e=t.worktreeLifecycle?.state??t.worktreeState;return t.worktreeMerged||e==="merged"?"[merged \u2713]":e==="released"?"[released]":t.worktreePrUrl?`[PR: ${t.worktreePrUrl}]`:e==="pr_open"?"[PR open]":e==="dismissed"?"[dismissed]":e==="no_change"?"[no change]":"[not merged]"}function ec(t){let e=Zm[t.phase]??Zm[t.status]??"\u2753",r=Ft(t.duration),n=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)}`:"",a=[`${e} ${t.name} [${t.id}] (${r}${i}) \u2014 ${n}`,` \u{1F4C1} ${t.workdir}`,` \u{1F4DD} "${o}"`];t.worktreePath&&t.worktreeBranch&&a.push(` \u{1F33F} Worktree: ${t.worktreeBranch} ${Zw(t)}`),t.phase!==t.status&&a.push(` \u2699\uFE0F Phase: ${t.phase}`),t.lifecycle&&t.lifecycle!==t.phase&&a.push(` \u{1F504} Lifecycle: ${t.lifecycle}`),(t.requestedPermissionMode||t.currentPermissionMode||t.approvalExecutionState)&&a.push(` \u{1F510} Approval: ${t.approvalExecutionState??"unknown"} (requested=${t.requestedPermissionMode??"unknown"}, effective=${t.currentPermissionMode??"unknown"})`),t.resumable&&a.push(" \u21A9\uFE0F Resumable: yes"),t.harness&&a.push(` \u{1F9F0} Harness: ${t.harness}`);let u=q(t);return u&&a.push(` \u{1F517} Backend ID: ${u}`),t.resumeSessionId&&a.push(` \u21A9\uFE0F Resumed from: ${t.resumeSessionId}${t.forkSession?" (forked)":""}`),a.join(`
49
- `)}function Yi(t,e){let r=t.sessionsWithDuration>0?t.totalDurationMs/t.sessionsWithDuration:0,{completed:n,failed:o,killed:i}=t.sessionsByStatus,a=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${t.totalLaunched}`,` Running: ${e}`,` Completed: ${n}`,` Failed: ${o}`,` Killed: ${i}`,"",`\u23F1\uFE0F Average duration: ${r>0?Ft(r):"n/a"}`];if(t.mostExpensive){let u=t.mostExpensive;a.push("","\u{1F3C6} Notable session",` ${u.name} [${u.id}]`,` \u{1F4DD} "${u.prompt}"`)}return a.join(`
50
- `)}function Je(t,e){return e<=0?"":t.length<=e?t:e<=3?".".repeat(e):t.slice(0,e-3)+"..."}function Zi(t,e){let r=t.split(`
48
+ `)}}}let h=t.resume_session_id,y=h?r.resolve?.(h):void 0,k=h?r.getPersistedSession?.(h):void 0;if(h){let C=r.resolveBackendConversationId?.(h)??r.resolveHarnessSessionId?.(h);if(!C)return{kind:"error",text:`Error: Could not resolve resume_session_id "${h}" to a session ID. Use agent_sessions to list available sessions.`};h=C}let{resumeSessionId:S,clearedPersistedCodexResume:x}=_n({requestedResumeSessionId:h,activeSession:y?{harnessSessionId:y.backendConversationId??y.harnessSessionId}:void 0,persistedSession:k?{harness:k.harness,backendRef:k.backendRef}:void 0}),R=t.permission_mode??K.permissionMode,$=t.plan_approval??K.planApproval;return{kind:"resolved",workdir:n,harness:o,resolvedModel:a,permissionMode:R,planApproval:$,originChannel:l,originThreadId:c,originSessionKey:m,route:On(e,l,m),resumeSessionId:S,resolvedResumeId:h,clearedPersistedCodexResume:x,reasoningEffort:Ir(o),fastMode:Mn(o)}}Ee();function Ft(t){let e=Math.floor(t/1e3),r=Math.floor(e/60),n=e%60;return r>0?`${r}m${n}s`:`${n}s`}var pv=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 sc(t){let r=t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>1&&!pv.has(n)).slice(0,3);return r.length===0?"session":r.join("-")}var ic={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4",awaiting_plan_decision:"\u{1F4CB}",awaiting_user_input:"\u2753",awaiting_worktree_decision:"\u{1F33F}",suspended:"\u23F8\uFE0F",terminal:"\u{1F3C1}"};function dv(t){let e=t.worktreeLifecycle?.state??t.worktreeState;return t.worktreeMerged||e==="merged"?"[merged \u2713]":e==="released"?"[released]":t.worktreePrUrl?`[PR: ${t.worktreePrUrl}]`:e==="pr_open"?"[PR open]":e==="dismissed"?"[dismissed]":e==="no_change"?"[no change]":"[not merged]"}function ac(t){let e=ic[t.phase]??ic[t.status]??"\u2753",r=Ft(t.duration),n=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)}`:"",a=[`${e} ${t.name} [${t.id}] (${r}${i}) \u2014 ${n}`,` \u{1F4C1} ${t.workdir}`,` \u{1F4DD} "${o}"`];t.worktreePath&&t.worktreeBranch&&a.push(` \u{1F33F} Worktree: ${t.worktreeBranch} ${dv(t)}`),t.phase!==t.status&&a.push(` \u2699\uFE0F Phase: ${t.phase}`),t.lifecycle&&t.lifecycle!==t.phase&&a.push(` \u{1F504} Lifecycle: ${t.lifecycle}`),(t.requestedPermissionMode||t.currentPermissionMode||t.approvalExecutionState)&&a.push(` \u{1F510} Approval: ${t.approvalExecutionState??"unknown"} (requested=${t.requestedPermissionMode??"unknown"}, effective=${t.currentPermissionMode??"unknown"})`),t.resumable&&a.push(" \u21A9\uFE0F Resumable: yes"),t.harness&&a.push(` \u{1F9F0} Harness: ${t.harness}`);let u=q(t);return u&&a.push(` \u{1F517} Backend ID: ${u}`),t.resumeSessionId&&a.push(` \u21A9\uFE0F Resumed from: ${t.resumeSessionId}${t.forkSession?" (forked)":""}`),a.join(`
49
+ `)}function Xi(t,e){let r=t.sessionsWithDuration>0?t.totalDurationMs/t.sessionsWithDuration:0,{completed:n,failed:o,killed:i}=t.sessionsByStatus,a=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${t.totalLaunched}`,` Running: ${e}`,` Completed: ${n}`,` Failed: ${o}`,` Killed: ${i}`,"",`\u23F1\uFE0F Average duration: ${r>0?Ft(r):"n/a"}`];if(t.mostExpensive){let u=t.mostExpensive;a.push("","\u{1F3C6} Notable session",` ${u.name} [${u.id}]`,` \u{1F4DD} "${u.prompt}"`)}return a.join(`
50
+ `)}function Je(t,e){return e<=0?"":t.length<=e?t:e<=3?".".repeat(e):t.slice(0,e-3)+"..."}function es(t,e){let r=t.split(`
51
51
  `),n=[],o=0;for(let i=r.length-1;i>=0;i--){let a=r[i].length+(n.length>0?1:0);if(o+a>e&&n.length>0)break;n.unshift(r[i]),o+=a}return n.join(`
52
- `)}function tc(t,e){let r=t.split(`
52
+ `)}function uc(t,e){let r=t.split(`
53
53
  `),n=[],o=0;for(let i=0;i<r.length;i++){let a=r[i].length+(n.length>0?1:0);if(o+a>e&&n.length>0)break;n.push(r[i]),o+=a}return n.join(`
54
- `)}var nn,Do,Fn=!1;function rc(t){try{return t?.config?.current?.()}catch{return}}function Nn(t,e){if(t&&typeof t=="object"){nn=t,arguments.length>=2?(Do=e,Fn=!0):Fn||(Do=rc(nn),Fn=!0);return}nn=void 0,Do=void 0,Fn=!1}function nc(){return nn}function oc(){return nn?.tasks?.managedFlows??nn?.taskFlow}function ic(){return Fn||(Do=rc(nn),Fn=!0),Do}var Xw="openclaw-code-agent",ev=160,Xi={create(){},progress(){},finalize(){}};function es(t,e){let r=e instanceof Error?e.message:String(e);console.warn(`[SessionTaskLifecycle] ${t} failed: ${r}`)}function tv(t,e){if(e.applied===!1){let r=e.code?` (${e.code})`:"";console.warn(`[SessionTaskLifecycle] ${t} mutation was not applied${r}`)}}function rv(t){let e=t.prompt.trim().replace(/\s+/g," ");return Je(e||t.name,ev)}function nv(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 ov(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 rp(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 iv(t){return t.lifecycle==="awaiting_plan_decision"||t.lifecycle==="awaiting_user_input"||t.lifecycle==="awaiting_worktree_decision"||t.lifecycle==="suspended"}function np(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 sv(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 sc(t,e){if(e.applied)return e.flow;let r=e.current;return r?.flowId&&typeof r.revision=="number"?r:t}var op=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:Xw,goal:rv(e),status:"running",notifyPolicy:"silent",currentStep:r,stateJson:np(e,"created",r),createdAt:e.startedAt,updatedAt:n}),this.lastProgressKey=this.progressKey(e,r)}catch(o){es("create",o)}}progress(e){if(!this.flow||this.finalized)return;let r=nv(e);if(!r)return;let n=this.progressKey(e,r);if(n!==this.lastProgressKey)try{let o=np(e,"progress",r),i=Date.now(),a=iv(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=sc(this.flow,a),this.lastProgressKey=n}catch(o){es("progress",o)}}finalize(e){if(!this.flow||this.finalized)return;let r=ov(e);if(!r)return;let n=r==="succeeded"?"Completed":r==="failed"?"Failed":rp(e.status,e.killReason);try{let o=e.completedAt??Date.now(),i={...np(e,"terminal",n),terminalStatus:r,terminalSummary:rp(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:rp(e.status,e.killReason),updatedAt:o,endedAt:o});tv("finalize",a),this.flow=sc(this.flow,a),this.finalized=!0}catch(o){es("finalize",o)}}progressKey(e,r){return`${e.status}:${e.lifecycle}:${r}`}};function ts(t){if(!t.sessionKey?.trim())return Xi;try{let e=oc()?.fromToolContext;if(typeof e!="function")return Xi;let r=e(t);return sv(r)?new op(r):Xi}catch(e){return es("resolve",e),Xi}}function av(t){return t instanceof Error?t.message:String(t)}function ac(t,e){return t?("id"in t?t.id:t.sessionId)??e??"unknown-session":e??"unknown-session"}function uv(t){return!t||typeof t!="object"?!1:typeof t.prompt=="string"}function pv(t){return!!t&&typeof t=="object"&&typeof t.formatLaunchResult=="function"}function uc(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(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!uv(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=Qi(r,t,k);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:S,reasoningEffort:I,fastMode:x}=n,R=r.resume_session_id?k.resolve(r.resume_session_id)??k.getPersistedSession(r.resume_session_id):void 0,$=!r.fork_session&&R?_o(R):void 0;if($?.kind==="direct")return{content:[{type:"text",text:`Session ${R.name} [${ac(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} [${ac(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=k.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:I,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:ts(t),worktreeStrategy:r.worktree_strategy,worktreeBaseBranch:r.worktree_base_branch,worktreePrTargetRepo:r.worktree_pr_target_repo});return{content:[{type:"text",text:pv(k)?k.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:S},C):Ei({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:S},{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=av(n),i=o.includes("Max sessions")?"":`
54
+ `)}var nn,Lo,Fn=!1;function pc(t){try{return t?.config?.current?.()}catch{return}}function Nn(t,e){if(t&&typeof t=="object"){nn=t,arguments.length>=2?(Lo=e,Fn=!0):Fn||(Lo=pc(nn),Fn=!0);return}nn=void 0,Lo=void 0,Fn=!1}function ts(){return nn}function dc(){return nn?.tasks?.managedFlows??nn?.taskFlow}function lc(){return Fn||(Lo=pc(nn),Fn=!0),Lo}var lv="openclaw-code-agent",mv=160,rs={create(){},progress(){},finalize(){}};function ns(t,e){let r=e instanceof Error?e.message:String(e);console.warn(`[SessionTaskLifecycle] ${t} failed: ${r}`)}function cv(t,e){if(e.applied===!1){let r=e.code?` (${e.code})`:"";console.warn(`[SessionTaskLifecycle] ${t} mutation was not applied${r}`)}}function fv(t){let e=t.prompt.trim().replace(/\s+/g," ");return Je(e||t.name,mv)}function gv(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 hv(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 pp(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 yv(t){return t.lifecycle==="awaiting_plan_decision"||t.lifecycle==="awaiting_user_input"||t.lifecycle==="awaiting_worktree_decision"||t.lifecycle==="suspended"}function dp(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 kv(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 mc(t,e){if(e.applied)return e.flow;let r=e.current;return r?.flowId&&typeof r.revision=="number"?r:t}var lp=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:lv,goal:fv(e),status:"running",notifyPolicy:"silent",currentStep:r,stateJson:dp(e,"created",r),createdAt:e.startedAt,updatedAt:n}),this.lastProgressKey=this.progressKey(e,r)}catch(o){ns("create",o)}}progress(e){if(!this.flow||this.finalized)return;let r=gv(e);if(!r)return;let n=this.progressKey(e,r);if(n!==this.lastProgressKey)try{let o=dp(e,"progress",r),i=Date.now(),a=yv(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=mc(this.flow,a),this.lastProgressKey=n}catch(o){ns("progress",o)}}finalize(e){if(!this.flow||this.finalized)return;let r=hv(e);if(!r)return;let n=r==="succeeded"?"Completed":r==="failed"?"Failed":pp(e.status,e.killReason);try{let o=e.completedAt??Date.now(),i={...dp(e,"terminal",n),terminalStatus:r,terminalSummary:pp(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:pp(e.status,e.killReason),updatedAt:o,endedAt:o});cv("finalize",a),this.flow=mc(this.flow,a),this.finalized=!0}catch(o){ns("finalize",o)}}progressKey(e,r){return`${e.status}:${e.lifecycle}:${r}`}};function os(t){if(!t.sessionKey?.trim())return rs;try{let e=dc()?.fromToolContext;if(typeof e!="function")return rs;let r=e(t);return kv(r)?new lp(r):rs}catch(e){return ns("resolve",e),rs}}function Sv(t){return t instanceof Error?t.message:String(t)}function cc(t,e){return t?("id"in t?t.id:t.sessionId)??e??"unknown-session":e??"unknown-session"}function Iv(t){return!t||typeof t!="object"?!1:typeof t.prompt=="string"}function xv(t){return!!t&&typeof t=="object"&&typeof t.formatLaunchResult=="function"}function fc(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(!Iv(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=Zi(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?Do(R):void 0;if($?.kind==="direct")return{content:[{type:"text",text:`Session ${R.name} [${cc(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} [${cc(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:os(t),worktreeStrategy:r.worktree_strategy,worktreeBaseBranch:r.worktree_base_branch,worktreePrTargetRepo:r.worktree_pr_target_repo});return{content:[{type:"text",text:xv(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):Oi({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=Sv(n),i=o.includes("Max sessions")?"":`
55
55
 
56
- Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}tt();le();ze();import{existsSync as mp,readFileSync as Mc}from"fs";import{EventEmitter as Ov}from"events";import{webcrypto as dc}from"node:crypto";var pc="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var dv=128,on,qn;function lv(t){if(t<0||t>1024)throw new RangeError("Wrong ID size");!on||on.length<t?(on=Buffer.allocUnsafe(t*dv),dc.getRandomValues(on),qn=0):qn+t>on.length&&(dc.getRandomValues(on),qn=0),qn+=t}function rs(t=21){lv(t|=0);let e="";for(let r=qn-t;r<qn;r++)e+=pc[on[r]&63];return e}Xu();ze();Ee();var lc={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},mc=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]);function mv(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 rt(t){return{...t,approvalExecutionState:mv(t)}}function ip(t,e){switch(e.type){case"initialize":return rt({...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"?rt({...t,status:e.status,lifecycle:"starting",runtimeState:"live"}):e.status==="running"?rt({...t,status:e.status,lifecycle:t.lifecycle==="starting"||t.lifecycle==="suspended"?"active":t.lifecycle,runtimeState:"live"}):rt({...t,status:e.status,runtimeState:"stopped",lifecycle:t.lifecycle==="suspended"?"suspended":"terminal"});case"permission.mode_changed":return rt({...t,currentPermissionMode:e.currentPermissionMode});case"turn.started":return rt({...t,lifecycle:"active",runtimeState:"live"});case"input.requested":return rt({...t,lifecycle:t.pendingPlanApproval?"awaiting_plan_decision":"awaiting_user_input"});case"plan.requested":if(t.planModeApproved)return t;{let r=t.pendingPlanApproval&&t.approvalState==="pending"&&t.planApprovalContext===e.context,n=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=r||n||o?t.planDecisionVersion:t.planDecisionVersion+1;return rt({...t,pendingPlanApproval:!0,planApprovalContext:e.context,approvalState:"pending",planDecisionVersion:i,actionablePlanDecisionVersion:i,canonicalPlanPromptVersion:r?t.canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:r?t.approvalPromptRequiredVersion:void 0,approvalPromptVersion:r?t.approvalPromptVersion:void 0,approvalPromptStatus:r?t.approvalPromptStatus:"not_sent",approvalPromptTransport:r?t.approvalPromptTransport:"none",approvalPromptMessageKind:r?t.approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:r?t.approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:r?t.approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:r?t.approvalPromptFailedAt:void 0,lifecycle:"awaiting_plan_decision"})}case"plan.cleared":return rt({...t,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,approvalState:t.approvalState==="pending"?"not_required":t.approvalState});case"plan.approved":return rt({...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 rt({...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 rt({...t,lifecycle:e.suspended?"suspended":"terminal",runtimeState:"stopped"});case"worktree.decision_requested":return rt({...t,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"});case"worktree.state_set":return rt({...t,worktreeState:e.worktreeState,lifecycle:e.worktreeState==="pending_decision"?"awaiting_worktree_decision":mc.has(e.worktreeState)?"terminal":t.lifecycle});case"delivery.state_set":return rt({...t,deliveryState:e.deliveryState})}}function cc(t,e){let r={...t,...e.lifecycle!==void 0?{lifecycle:e.lifecycle}:{},...e.approvalState!==void 0?{approvalState:e.approvalState}:{},...e.approvalExecutionState!==void 0?{approvalExecutionState:e.approvalExecutionState}:{},...e.worktreeState!==void 0?{worktreeState:e.worktreeState}:{},...e.runtimeState!==void 0?{runtimeState:e.runtimeState}:{},...e.deliveryState!==void 0?{deliveryState:e.deliveryState}:{},...e.requestedPermissionMode!==void 0?{requestedPermissionMode:e.requestedPermissionMode}:{},...e.currentPermissionMode!==void 0?{currentPermissionMode:e.currentPermissionMode}:{},...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}:{},...e.planModeApproved!==void 0?{planModeApproved:e.planModeApproved}:{}};return e.approvalState==="changes_requested"&&e.pendingPlanApproval===void 0&&(r={...r,pendingPlanApproval:!1}),r.pendingPlanApproval?r={...r,approvalState:"pending",actionablePlanDecisionVersion:r.actionablePlanDecisionVersion??r.planDecisionVersion,lifecycle:"awaiting_plan_decision"}:r.approvalState==="changes_requested"&&(r={...r,actionablePlanDecisionVersion:void 0,lifecycle:"awaiting_user_input"}),e.pendingWorktreeDecisionSince!==void 0||r.worktreeState==="pending_decision"?r=ip(r,{type:"worktree.decision_requested"}):mc.has(r.worktreeState)&&(r={...r,lifecycle:"terminal"}),rt(r)}var ns=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 cv}from"fs";import{tmpdir as fv}from"os";import{join as gv}from"path";var fc=2e3;function Bn(t){return gv(fv(),`openclaw-agent-${t}.txt`)}function hv(t,e){if(!e)return;let r=e.split(`
57
- `),[n="",...o]=r;t.length===0?t.push(n):t[t.length-1]+=n;for(let i of o)t.push(i)}function gc(t,e,r){hv(t,r),t.length>fc&&t.splice(0,t.length-fc);try{cv(Bn(e),r,"utf-8")}catch{}return t}var os=class{timers=new Map;get size(){return this.timers.size}set(e,r,n){this.clear(e);let o=setTimeout(n,r);o.unref?.(),this.timers.set(e,o)}clear(e){let r=this.timers.get(e);r&&(clearTimeout(r),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var is=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,r){this.waitingForInputFired=!1,r||(this.lastTurnHadQuestion=!1),this.deps.appendOutput(e),this.currentTurnText+=this.currentTurnText?`
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 ss=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 _v=120*1e3;function ys(t){return t instanceof Error?t.message:String(t)}var Ss=class extends Ov{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 os;constructor(e,r){super(),this.id=e.sessionIdOverride??rs(8),this.name=r,this.harness=e.harness?$o(e.harness):Hm(),this.prompt=e.prompt,this.workdir=e.workdir,this.model=e.model??$n(this.harness.name),this.reasoningEffort=e.reasoningEffort??Ir(this.harness.name),this.fastMode=this.harness.name==="codex"?e.fastMode??Mn(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 is({appendOutput:n=>gc(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 ss({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??=ms(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(!lc[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=Wn(this.worktreePath);if(e.length===0)return!1;this.worktreeFinalizationPromptIssued=!0;let r=e.slice(0,20).map(i=>`- ${i}`).join(`
56
+ Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}tt();le();ze();import{existsSync as Sp,readFileSync as Nc}from"fs";import{EventEmitter as Gv}from"events";import{webcrypto as hc}from"node:crypto";var gc="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Pv=128,on,qn;function wv(t){if(t<0||t>1024)throw new RangeError("Wrong ID size");!on||on.length<t?(on=Buffer.allocUnsafe(t*Pv),hc.getRandomValues(on),qn=0):qn+t>on.length&&(hc.getRandomValues(on),qn=0),qn+=t}function is(t=21){wv(t|=0);let e="";for(let r=qn-t;r<qn;r++)e+=gc[on[r]&63];return e}sp();ze();Ee();var yc={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},kc=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]);function vv(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 rt(t){return{...t,approvalExecutionState:vv(t)}}function mp(t,e){switch(e.type){case"initialize":return rt({...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"?rt({...t,status:e.status,lifecycle:"starting",runtimeState:"live"}):e.status==="running"?rt({...t,status:e.status,lifecycle:t.lifecycle==="starting"||t.lifecycle==="suspended"?"active":t.lifecycle,runtimeState:"live"}):rt({...t,status:e.status,runtimeState:"stopped",lifecycle:t.lifecycle==="suspended"?"suspended":"terminal"});case"permission.mode_changed":return rt({...t,currentPermissionMode:e.currentPermissionMode});case"turn.started":return rt({...t,lifecycle:"active",runtimeState:"live"});case"input.requested":return rt({...t,lifecycle:t.pendingPlanApproval?"awaiting_plan_decision":"awaiting_user_input"});case"plan.requested":if(t.planModeApproved)return t;{let r=t.pendingPlanApproval&&t.approvalState==="pending"&&t.planApprovalContext===e.context,n=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=r||n||o?t.planDecisionVersion:t.planDecisionVersion+1;return rt({...t,pendingPlanApproval:!0,planApprovalContext:e.context,approvalState:"pending",planDecisionVersion:i,actionablePlanDecisionVersion:i,canonicalPlanPromptVersion:r?t.canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:r?t.approvalPromptRequiredVersion:void 0,approvalPromptVersion:r?t.approvalPromptVersion:void 0,approvalPromptStatus:r?t.approvalPromptStatus:"not_sent",approvalPromptTransport:r?t.approvalPromptTransport:"none",approvalPromptMessageKind:r?t.approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:r?t.approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:r?t.approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:r?t.approvalPromptFailedAt:void 0,lifecycle:"awaiting_plan_decision"})}case"plan.cleared":return rt({...t,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,approvalState:t.approvalState==="pending"?"not_required":t.approvalState});case"plan.approved":return rt({...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 rt({...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 rt({...t,lifecycle:e.suspended?"suspended":"terminal",runtimeState:"stopped"});case"worktree.decision_requested":return rt({...t,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"});case"worktree.state_set":return rt({...t,worktreeState:e.worktreeState,lifecycle:e.worktreeState==="pending_decision"?"awaiting_worktree_decision":kc.has(e.worktreeState)?"terminal":t.lifecycle});case"delivery.state_set":return rt({...t,deliveryState:e.deliveryState})}}function Sc(t,e){let r={...t,...e.lifecycle!==void 0?{lifecycle:e.lifecycle}:{},...e.approvalState!==void 0?{approvalState:e.approvalState}:{},...e.approvalExecutionState!==void 0?{approvalExecutionState:e.approvalExecutionState}:{},...e.worktreeState!==void 0?{worktreeState:e.worktreeState}:{},...e.runtimeState!==void 0?{runtimeState:e.runtimeState}:{},...e.deliveryState!==void 0?{deliveryState:e.deliveryState}:{},...e.requestedPermissionMode!==void 0?{requestedPermissionMode:e.requestedPermissionMode}:{},...e.currentPermissionMode!==void 0?{currentPermissionMode:e.currentPermissionMode}:{},...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}:{},...e.planModeApproved!==void 0?{planModeApproved:e.planModeApproved}:{}};return e.approvalState==="changes_requested"&&e.pendingPlanApproval===void 0&&(r={...r,pendingPlanApproval:!1}),r.pendingPlanApproval?r={...r,approvalState:"pending",actionablePlanDecisionVersion:r.actionablePlanDecisionVersion??r.planDecisionVersion,lifecycle:"awaiting_plan_decision"}:r.approvalState==="changes_requested"&&(r={...r,actionablePlanDecisionVersion:void 0,lifecycle:"awaiting_user_input"}),e.pendingWorktreeDecisionSince!==void 0||r.worktreeState==="pending_decision"?r=mp(r,{type:"worktree.decision_requested"}):kc.has(r.worktreeState)&&(r={...r,lifecycle:"terminal"}),rt(r)}var ss=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 bv}from"fs";import{tmpdir as Av}from"os";import{join as Tv}from"path";var Ic=2e3;function Bn(t){return Tv(Av(),`openclaw-agent-${t}.txt`)}function Rv(t,e){if(!e)return;let r=e.split(`
57
+ `),[n="",...o]=r;t.length===0?t.push(n):t[t.length-1]+=n;for(let i of o)t.push(i)}function xc(t,e,r){Rv(t,r),t.length>Ic&&t.splice(0,t.length-Ic);try{bv(Bn(e),r,"utf-8")}catch{}return t}var as=class{timers=new Map;get size(){return this.timers.size}set(e,r,n){this.clear(e);let o=setTimeout(n,r);o.unref?.(),this.timers.set(e,o)}clear(e){let r=this.timers.get(e);r&&(clearTimeout(r),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var us=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,r){this.waitingForInputFired=!1,r||(this.lastTurnHadQuestion=!1),this.deps.appendOutput(e),this.currentTurnText+=this.currentTurnText?`
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 ps=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 Vv=120*1e3;function Is(t){return t instanceof Error?t.message:String(t)}var xs=class extends Gv{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 as;constructor(e,r){super(),this.id=e.sessionIdOverride??is(8),this.name=r,this.harness=e.harness?Mo(e.harness):ec(),this.prompt=e.prompt,this.workdir=e.workdir,this.model=e.model??$n(this.harness.name),this.reasoningEffort=e.reasoningEffort??Ir(this.harness.name),this.fastMode=this.harness.name==="codex"?e.fastMode??Mn(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 us({appendOutput:n=>xc(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 ps({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??=gs(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(!yc[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=Wn(this.worktreePath);if(e.length===0)return!1;this.worktreeFinalizationPromptIssued=!0;let r=e.slice(0,20).map(i=>`- ${i}`).join(`
59
59
  `),n=e.length>20?`
60
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:",`${r}${n}`,"","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(`
61
- `);return this.messageStream.push(this.harness.buildUserMessage(o,this.backendConversationId??"")),!0}async start(){try{let e;this.multiTurn?(this.messageStream=new ns,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),e=this.messageStream):e=this.prompt;let r=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:xm(),canUseTool:this.canUseTool});this.harnessHandle=r,this.setTimer("startup",_v,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(e){let r=e instanceof Error?e.message:String(e);this.transitionToTerminal("failed",{error:r});return}this.consumeMessages(this.harnessHandle.messages).catch(e=>{let r=e instanceof Error?e.message:String(e),n=e instanceof Error?e.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${r}`,n),this.isActive&&this.transitionToTerminal("failed",{error:r})})}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 r=e;if(this.pendingModeSwitch){let n=this.pendingModeSwitch,o=!1,i=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(n),this.currentPermissionMode=n,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:n}),this.pendingModeSwitch=void 0,i=!0,o=!0}catch(a){throw console.error(`[Session ${this.id}] setPermissionMode(${n}) FAILED: ${ys(a)}`),this.markPendingPlanApproval(this.planApprovalContext??"plan-mode"),new Error(`Failed to switch permission mode to ${n}: ${ys(a)}`)}else this.pendingModeSwitch=void 0,i=!0,o=!0,console.warn(`[Session ${this.id}] Cannot call setPermissionMode \u2014 falling back to text prefix only (currentPermissionMode remains ${this.currentPermissionMode})`);i&&(this.clearPendingPlanApproval(),n!=="plan"&&this.applyControlEvent({type:"plan.approved"})),o&&(r=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
61
+ `);return this.messageStream.push(this.harness.buildUserMessage(o,this.backendConversationId??"")),!0}async start(){try{let e;this.multiTurn?(this.messageStream=new ss,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),e=this.messageStream):e=this.prompt;let r=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:Rm(),canUseTool:this.canUseTool});this.harnessHandle=r,this.setTimer("startup",Vv,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(e){let r=e instanceof Error?e.message:String(e);this.transitionToTerminal("failed",{error:r});return}this.consumeMessages(this.harnessHandle.messages).catch(e=>{let r=e instanceof Error?e.message:String(e),n=e instanceof Error?e.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${r}`,n),this.isActive&&this.transitionToTerminal("failed",{error:r})})}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 r=e;if(this.pendingModeSwitch){let n=this.pendingModeSwitch,o=!1,i=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(n),this.currentPermissionMode=n,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:n}),this.pendingModeSwitch=void 0,i=!0,o=!0}catch(a){throw console.error(`[Session ${this.id}] setPermissionMode(${n}) FAILED: ${Is(a)}`),this.markPendingPlanApproval(this.planApprovalContext??"plan-mode"),new Error(`Failed to switch permission mode to ${n}: ${Is(a)}`)}else this.pendingModeSwitch=void 0,i=!0,o=!0,console.warn(`[Session ${this.id}] Cannot call setPermissionMode \u2014 falling back to text prefix only (currentPermissionMode remains ${this.currentPermissionMode})`);i&&(this.clearPendingPlanApproval(),n!=="plan"&&this.applyControlEvent({type:"plan.approved"})),o&&(r=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
62
62
 
63
63
  ${e}`)}else if((this.pendingPlanApproval||this.approvalState==="changes_requested")&&!this.planModeApproved&&(this.approvalState!=="changes_requested"&&this.applyControlEvent({type:"plan.changes_requested"}),r=`[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.]
64
64
 
65
- ${e}`,this.harnessHandle?.setPermissionMode))try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan",this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:"plan"})}catch(n){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${ys(n)}`)}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(r,this.backendConversationId??""));else if(this.harnessHandle?.streamInput){let n=this.harness.buildUserMessage(r,this.backendConversationId??"");async function*o(){yield n}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 r=await this.harnessHandle.submitPendingInputOption(e);return r&&(this.waitingForInputFired=!1),r}async submitPendingInputText(e){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputText)return!1;let r=await this.harnessHandle.submitPendingInputText(e);return r&&(this.waitingForInputFired=!1),r}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=(K.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=>{console.warn(`[Session ${this.id}] interrupt during teardown failed: ${ys(e)}`)}),this.abortController.abort(),this.applyControlEvent({type:"terminal.entered",suspended:this.lifecycle==="suspended"})}transitionToTerminal(e,r={}){this.isActive&&(this.turnInProgress=!1,r.reason&&(this.killReason=r.reason),r.error!==void 0&&(this.error=r.error),this.completedAt=Date.now(),this.applyControlEvent({type:"terminal.entered",suspended:e==="killed"&&r.reason==="idle-timeout"}),this.transition(e),this.teardown())}async consumeMessages(e){for await(let r of e){if(!this.isActive)break;this.resetIdleTimer(),this.harnessEvents.applyMessage(r,{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 r=ip(this.controlStateSnapshot(),e);this.applyControlState(r)}applyControlPatch(e){let r=cc(this.controlStateSnapshot(),e);this.applyControlState(r)}setControlField(e,r){this.applyControlPatch({[e]:r})}applyControlState(e){let r=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,r!==this.lifecycle&&this.emit("lifecycleChange",this,this.lifecycle,r)}};var Dv=50,Lv=1,Fv=new Set(["starting","running","completed","failed","killed"]),Nv=5,qv=1440*60*1e3,ks=new Set(["merged","released","dismissed","no_change"]);function Bv(t){let e=Number(t);return!Number.isFinite(e)||e<Lv?Dv:Math.floor(e)}function Uv(t){return typeof t=="string"&&Fv.has(t)}function Wv(t){let e=t.split(`
66
- `);return e.at(-1)===""&&e.pop(),e}function cp(t){return t.backendRef?.conversationId??t.harnessSessionId}function Kv(t,e){return e&&ks.has(e)&&(!t||!ks.has(t))?e:t??e}function jv(t,e){return e&&ks.has(e.state)&&(!t||!ks.has(t.state))?e:t??e}function Oc(t,e,r){let n=Mc(t,"utf-8"),o=Wv(n);return e.full?o:o.slice(-r)}function Gv(t,e,r){if(t.status!=="starting"&&t.status!=="running")return null;let n=Bn(t.id);if(!mp(n))return null;try{return Oc(n,e,r)}catch{return null}}function Vv(t){let e=Ft(t.duration),r=` | Cost: $${t.costUsd.toFixed(4)}`,n=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()}${n}${o}${r} | Duration: ${e}`,`${"\u2500".repeat(60)}`].join(`
67
- `)}function _c(t,e){let r=t.name||t.sessionId||cp(t)||"unknown",n=t.lifecycle?` | Phase: ${t.lifecycle}`:"";return[`Session: ${r} | Status: ${t.status.toUpperCase()}${n} | Cost: $${t.costUsd.toFixed(4)}`,e,`${"\u2500".repeat(60)}`].join(`
68
- `)}function Hv(t){return`(retrieved from ${t.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`}function zv(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 $c(t,e){let r=_c(t,zv(t)),n=cp(t),o=n?`
65
+ ${e}`,this.harnessHandle?.setPermissionMode))try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan",this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:"plan"})}catch(n){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${Is(n)}`)}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(r,this.backendConversationId??""));else if(this.harnessHandle?.streamInput){let n=this.harness.buildUserMessage(r,this.backendConversationId??"");async function*o(){yield n}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 r=await this.harnessHandle.submitPendingInputOption(e);return r&&(this.waitingForInputFired=!1),r}async submitPendingInputText(e){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputText)return!1;let r=await this.harnessHandle.submitPendingInputText(e);return r&&(this.waitingForInputFired=!1),r}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=(K.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=>{console.warn(`[Session ${this.id}] interrupt during teardown failed: ${Is(e)}`)}),this.abortController.abort(),this.applyControlEvent({type:"terminal.entered",suspended:this.lifecycle==="suspended"})}transitionToTerminal(e,r={}){this.isActive&&(this.turnInProgress=!1,r.reason&&(this.killReason=r.reason),r.error!==void 0&&(this.error=r.error),this.completedAt=Date.now(),this.applyControlEvent({type:"terminal.entered",suspended:e==="killed"&&r.reason==="idle-timeout"}),this.transition(e),this.teardown())}async consumeMessages(e){for await(let r of e){if(!this.isActive)break;this.resetIdleTimer(),this.harnessEvents.applyMessage(r,{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 r=mp(this.controlStateSnapshot(),e);this.applyControlState(r)}applyControlPatch(e){let r=Sc(this.controlStateSnapshot(),e);this.applyControlState(r)}setControlField(e,r){this.applyControlPatch({[e]:r})}applyControlState(e){let r=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,r!==this.lifecycle&&this.emit("lifecycleChange",this,this.lifecycle,r)}};var Hv=50,zv=1,Jv=new Set(["starting","running","completed","failed","killed"]),Qv=5,Yv=1440*60*1e3,Ps=new Set(["merged","released","dismissed","no_change"]);function Zv(t){let e=Number(t);return!Number.isFinite(e)||e<zv?Hv:Math.floor(e)}function Xv(t){return typeof t=="string"&&Jv.has(t)}function eb(t){let e=t.split(`
66
+ `);return e.at(-1)===""&&e.pop(),e}function Ip(t){return t.backendRef?.conversationId??t.harnessSessionId}function tb(t,e){return e&&Ps.has(e)&&(!t||!Ps.has(t))?e:t??e}function rb(t,e){return e&&Ps.has(e.state)&&(!t||!Ps.has(t.state))?e:t??e}function qc(t,e,r){let n=Nc(t,"utf-8"),o=eb(n);return e.full?o:o.slice(-r)}function nb(t,e,r){if(t.status!=="starting"&&t.status!=="running")return null;let n=Bn(t.id);if(!Sp(n))return null;try{return qc(n,e,r)}catch{return null}}function ob(t){let e=Ft(t.duration),r=` | Cost: $${t.costUsd.toFixed(4)}`,n=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()}${n}${o}${r} | Duration: ${e}`,`${"\u2500".repeat(60)}`].join(`
67
+ `)}function Bc(t,e){let r=t.name||t.sessionId||Ip(t)||"unknown",n=t.lifecycle?` | Phase: ${t.lifecycle}`:"";return[`Session: ${r} | Status: ${t.status.toUpperCase()}${n} | Cost: $${t.costUsd.toFixed(4)}`,e,`${"\u2500".repeat(60)}`].join(`
68
+ `)}function ib(t){return`(retrieved from ${t.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`}function sb(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 Fc(t,e){let r=Bc(t,sb(t)),n=Ip(t),o=n?`
69
69
  Backend session: ${n}`:"";return`${r}
70
- (no persisted output available: ${e})${o}`}function Jv(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?`
70
+ (no persisted output available: ${e})${o}`}function ab(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
71
  (no output yet)
72
72
  ${e.join(`
73
73
  `)}`:`
74
- (no output yet)`}function Is(t,e,r={}){let n=Bv(r.lines),o=t.resolve(e);if(!o){let d=t.getPersistedSession(e);if(d?.outputPath&&mp(d.outputPath))try{let l=Oc(d.outputPath,r,n).join(`
75
- `),m=_c(d,Hv(d));return l?`${m}
74
+ (no output yet)`}function ws(t,e,r={}){let n=Zv(r.lines),o=t.resolve(e);if(!o){let d=t.getPersistedSession(e);if(d?.outputPath&&Sp(d.outputPath))try{let l=qc(d.outputPath,r,n).join(`
75
+ `),m=Bc(d,ib(d));return l?`${m}
76
76
  ${l}`:`${m}
77
- (output file was empty)`}catch(l){let m=l instanceof Error?l.message:String(l);return`Error: Session "${e}" was cleaned up (expired) and output file could not be read: ${m}`}return d?.outputPath?$c(d,`output file is missing at ${d.outputPath}`):d?$c(d,"no outputPath is stored for this recovered session"):`Error: Session "${e}" not found.`}let i=Gv(o,r,n),a=i&&i.length>0?i:r.full?o.getOutput():o.getOutput(n),u=Vv(o),p=a.length===0?`${u}${Jv(o)}`:`${u}
77
+ (output file was empty)`}catch(l){let m=l instanceof Error?l.message:String(l);return`Error: Session "${e}" was cleaned up (expired) and output file could not be read: ${m}`}return d?.outputPath?Fc(d,`output file is missing at ${d.outputPath}`):d?Fc(d,"no outputPath is stored for this recovered session"):`Error: Session "${e}" not found.`}let i=nb(o,r,n),a=i&&i.length>0?i:r.full?o.getOutput():o.getOutput(n),u=ob(o),p=a.length===0?`${u}${ab(o)}`:`${u}
78
78
  ${a.join(`
79
- `)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(mp(o.planFilePath)){let d=Mc(o.planFilePath,"utf-8"),l="\u2500".repeat(60);return`${p}
79
+ `)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(Sp(o.planFilePath)){let d=Nc(o.planFilePath,"utf-8"),l="\u2500".repeat(60);return`${p}
80
80
  ${l}
81
81
  Plan file: ${o.planFilePath}
82
82
  ${l}
83
- ${d}`}}catch{}return p}function xs(t,e="all",r,n={}){let o=t.listPersistedSessions()??[],a=Qv(t.list("all"),o);if(e!=="all"&&(a=a.filter(u=>u.status===e)),r&&(a=a.filter(u=>u.originChannel===r)),n.full){let u=Date.now()-qv;a=a.filter(p=>(p.startedAt??0)>=u)}else a=a.slice(0,Nv);return a.length===0?"No sessions found.":a.map(u=>ec(u)).join(`
83
+ ${d}`}}catch{}return p}function vs(t,e="all",r,n={}){let o=t.listPersistedSessions()??[],a=ub(t.list("all"),o);if(e!=="all"&&(a=a.filter(u=>u.status===e)),r&&(a=a.filter(u=>u.originChannel===r)),n.full){let u=Date.now()-Yv;a=a.filter(p=>(p.startedAt??0)>=u)}else a=a.slice(0,Qv);return a.length===0?"No sessions found.":a.map(u=>ac(u)).join(`
84
84
 
85
- `)}function Qv(t,e){let r=new Map;for(let n of e){if(!Uv(n.status))continue;let o=n.completedAt??Date.now(),i=n.createdAt??o,a=cp(n),u=n.sessionId??`persisted:${a??n.harnessSessionId}`;r.set(u,{id:n.sessionId??a??n.harnessSessionId,name:n.name||n.sessionId||a||n.harnessSessionId,status:n.status,startedAt:n.createdAt??0,completedAt:n.completedAt,duration:Math.max(0,o-i),prompt:n.prompt??"",workdir:n.workdir??"(unknown)",costUsd:n.costUsd??0,multiTurn:!0,phase:n.lifecycle??n.status,lifecycle:n.lifecycle,resumable:n.resumable,harness:n.harness,backendRef:n.backendRef,harnessSessionId:n.harnessSessionId,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,worktreeStrategy:n.worktreeStrategy,worktreeState:n.worktreeState,worktreeLifecycle:n.worktreeLifecycle,worktreeMerged:n.worktreeMerged,worktreeMergedAt:n.worktreeMergedAt,worktreePrUrl:n.worktreePrUrl})}for(let n of t){let o=r.get(n.id);r.set(n.id,{id:n.id,name:n.name,status:n.status,startedAt:n.startedAt,completedAt:n.completedAt,duration:n.duration,prompt:n.prompt,workdir:n.originalWorkdir??n.workdir,costUsd:n.costUsd,multiTurn:n.multiTurn,phase:n.phase,lifecycle:n.lifecycle,resumable:n.isExplicitlyResumable,harness:n.harnessName,backendRef:n.backendRef,harnessSessionId:n.harnessSessionId,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,worktreeStrategy:n.worktreeStrategy,worktreeState:Kv(n.worktreeState,o?.worktreeState),worktreeLifecycle:jv(n.worktreeLifecycle,o?.worktreeLifecycle),worktreeMerged:n.worktreeMerged??o?.worktreeMerged,worktreeMergedAt:n.worktreeMergedAt??o?.worktreeMergedAt,worktreePrUrl:n.worktreePrUrl??o?.worktreePrUrl})}return[...r.values()].sort((n,o)=>(o.startedAt??0)-(n.startedAt??0))}function Yv(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 Dc(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:f.Object({status:f.Optional(f.Union([f.Literal("all"),f.Literal("running"),f.Literal("completed"),f.Literal("failed"),f.Literal("killed")],{description:'Filter by status (default "all")'})),full:f.Optional(f.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=Yv(r),o=t?.workspaceDir?Ao(t.workspaceDir):void 0,i=!!(r&&typeof r=="object"&&r.full===!0);return{content:[{type:"text",text:xs(k,n,o,{full:i})}]}}}}tt();le();function Ps(t,e,r){let n=t.resolve(e);return n?n.status==="completed"||n.status==="failed"||n.status==="killed"?`Session ${n.name} [${n.id}] is already ${n.status}. No action needed.`:r==="completed"?(n.complete(),`Session ${n.name} [${n.id}] marked as completed.`):(t.kill(n.id),`Session ${n.name} [${n.id}] has been terminated.`):`Error: Session "${e}" not found.`}function Zv(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 Lc(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:f.Object({session:f.String({description:"Session name or ID to terminate"}),reason:f.Optional(f.Union([f.Literal("completed"),f.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(e,r){return k?Zv(r)?{content:[{type:"text",text:Ps(k,r.session,r.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."}]}}}}tt();le();function Xv(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function ws(t){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:f.Object({session:f.String({description:"Session name or ID to get output from"}),lines:f.Optional(f.Number({description:"Number of recent lines to show (default 50)"})),full:f.Optional(f.Boolean({description:"Show all available output"}))}),async execute(e,r){return k?Xv(r)?{content:[{type:"text",text:Is(k,r.session,{full:r.full,lines:r.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."}]}}}}tt();le();ze();Ee();var eb=10;function gp(t){return t instanceof Error?t.message:String(t)}function pn(t){return ye(t)??t.harnessSessionId??"unknown-session"}function tb(t){if(!(!t.worktreeStrategy||t.worktreeStrategy==="off"))return zi(t)??ye(t)??q(t)}function Fc(t){return t.status!=="running"&&!!t.pendingPlanApproval&&!!q(t)}function rb(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 Uo(t,e,r){let n=e==="completed"?`This session is closed by default. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${pn(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='${pn(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='${pn(t)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${pn(t)}', message='<next instruction>') to continue the running session.`,o=r?` ${r}`:"";return{text:`Resume unavailable for session ${t.name} [${pn(t)}] (${e}).${o} ${n}`,isError:!0}}async function Nc(t,e,r){try{let n={prompt:e.prompt,sessionIdOverride:zi(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(n,{notifyLaunch:!1});return t.notifySession(o,`\u25B6\uFE0F [${o.name}] Relaunched fresh`),{text:`Session ${e.name} was relaunched fresh \u2014 it was killed during startup before the harness initialized. New session: ${o.name} [${o.id}].`}}catch(n){return{text:`Error relaunching session ${e.name} [${pn(e)}]: ${gp(n)}`,isError:!0}}}var nb=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
85
+ `)}function ub(t,e){let r=new Map;for(let n of e){if(!Xv(n.status))continue;let o=n.completedAt??Date.now(),i=n.createdAt??o,a=Ip(n),u=n.sessionId??`persisted:${a??n.harnessSessionId}`;r.set(u,{id:n.sessionId??a??n.harnessSessionId,name:n.name||n.sessionId||a||n.harnessSessionId,status:n.status,startedAt:n.createdAt??0,completedAt:n.completedAt,duration:Math.max(0,o-i),prompt:n.prompt??"",workdir:n.workdir??"(unknown)",costUsd:n.costUsd??0,multiTurn:!0,phase:n.lifecycle??n.status,lifecycle:n.lifecycle,resumable:n.resumable,harness:n.harness,backendRef:n.backendRef,harnessSessionId:n.harnessSessionId,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,worktreeStrategy:n.worktreeStrategy,worktreeState:n.worktreeState,worktreeLifecycle:n.worktreeLifecycle,worktreeMerged:n.worktreeMerged,worktreeMergedAt:n.worktreeMergedAt,worktreePrUrl:n.worktreePrUrl})}for(let n of t){let o=r.get(n.id);r.set(n.id,{id:n.id,name:n.name,status:n.status,startedAt:n.startedAt,completedAt:n.completedAt,duration:n.duration,prompt:n.prompt,workdir:n.originalWorkdir??n.workdir,costUsd:n.costUsd,multiTurn:n.multiTurn,phase:n.phase,lifecycle:n.lifecycle,resumable:n.isExplicitlyResumable,harness:n.harnessName,backendRef:n.backendRef,harnessSessionId:n.harnessSessionId,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,worktreeStrategy:n.worktreeStrategy,worktreeState:tb(n.worktreeState,o?.worktreeState),worktreeLifecycle:rb(n.worktreeLifecycle,o?.worktreeLifecycle),worktreeMerged:n.worktreeMerged??o?.worktreeMerged,worktreeMergedAt:n.worktreeMergedAt??o?.worktreeMergedAt,worktreePrUrl:n.worktreePrUrl??o?.worktreePrUrl})}return[...r.values()].sort((n,o)=>(o.startedAt??0)-(n.startedAt??0))}function pb(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 Uc(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:f.Object({status:f.Optional(f.Union([f.Literal("all"),f.Literal("running"),f.Literal("completed"),f.Literal("failed"),f.Literal("killed")],{description:'Filter by status (default "all")'})),full:f.Optional(f.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(e,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=pb(r),o=t?.workspaceDir?To(t.workspaceDir):void 0,i=!!(r&&typeof r=="object"&&r.full===!0);return{content:[{type:"text",text:vs(I,n,o,{full:i})}]}}}}tt();le();function bs(t,e,r){let n=t.resolve(e);return n?n.status==="completed"||n.status==="failed"||n.status==="killed"?`Session ${n.name} [${n.id}] is already ${n.status}. No action needed.`:r==="completed"?(n.complete(),`Session ${n.name} [${n.id}] marked as completed.`):(t.kill(n.id),`Session ${n.name} [${n.id}] has been terminated.`):`Error: Session "${e}" not found.`}function db(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 Wc(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:f.Object({session:f.String({description:"Session name or ID to terminate"}),reason:f.Optional(f.Union([f.Literal("completed"),f.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(e,r){return I?db(r)?{content:[{type:"text",text:bs(I,r.session,r.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."}]}}}}tt();le();function lb(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function As(t){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:f.Object({session:f.String({description:"Session name or ID to get output from"}),lines:f.Optional(f.Number({description:"Number of recent lines to show (default 50)"})),full:f.Optional(f.Boolean({description:"Show all available output"}))}),async execute(e,r){return I?lb(r)?{content:[{type:"text",text:ws(I,r.session,{full:r.full,lines:r.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."}]}}}}tt();le();ze();Ee();var mb=10;function Pp(t){return t instanceof Error?t.message:String(t)}function pn(t){return ye(t)??t.harnessSessionId??"unknown-session"}function cb(t){if(!(!t.worktreeStrategy||t.worktreeStrategy==="off"))return Qi(t)??ye(t)??q(t)}function Kc(t){return t.status!=="running"&&!!t.pendingPlanApproval&&!!q(t)}function fb(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 Wo(t,e,r){let n=e==="completed"?`This session is closed by default. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${pn(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='${pn(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='${pn(t)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${pn(t)}', message='<next instruction>') to continue the running session.`,o=r?` ${r}`:"";return{text:`Resume unavailable for session ${t.name} [${pn(t)}] (${e}).${o} ${n}`,isError:!0}}async function jc(t,e,r){try{let n={prompt:e.prompt,sessionIdOverride:Qi(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(n,{notifyLaunch:!1});return t.notifySession(o,`\u25B6\uFE0F [${o.name}] Relaunched fresh`),{text:`Session ${e.name} was relaunched fresh \u2014 it was killed during startup before the harness initialized. New session: ${o.name} [${o.id}].`}}catch(n){return{text:`Error relaunching session ${e.name} [${pn(e)}]: ${Pp(n)}`,isError:!0}}}var gb=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
86
86
 
87
- `;function qc(t){let e=t?.replace(/\s+/g," ").trim();if(e)return Je(e,240)}function fp(t){if(t.approvalState==="changes_requested"&&!vs(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 vs(t){return t.pendingPlanApproval?(t.approvalState==="changes_requested"?t.actionablePlanDecisionVersion:t.actionablePlanDecisionVersion??t.planDecisionVersion)>0:!1}function ob(t){return fp(t)?!1:vs(t)||t.currentPermissionMode==="plan"}function ib(t,e){let r=t.updatePersistedSession;if(typeof r!="function")return;let n=e.controlStateSnapshot();r.call(t,e.id,{lifecycle:n.lifecycle,approvalState:n.approvalState,approvalExecutionState:n.approvalExecutionState,runtimeState:n.runtimeState,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,pendingPlanApproval:n.pendingPlanApproval,planApprovalContext:n.planApprovalContext,planDecisionVersion:n.planDecisionVersion,actionablePlanDecisionVersion:n.actionablePlanDecisionVersion,planModeApproved:n.planModeApproved,approvalRationale:e.approvalRationale})}function sb(t){return(t.planDecisionVersion??0)+1}function Bc(t,e){let r={approvalState:e,lifecycle:e==="rejected"?"terminal":"awaiting_user_input",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:sb(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"&&(r.runtimeState="stopped"),r}function Uc(t,e){let r=t;typeof r.applyControlPatch=="function"&&r.applyControlPatch(e),Object.assign(t,e)}function hp(t,e){let r=t.resolve(e),n=r?void 0:t.getPersistedSession(e),o=r??n,i=o?.name??e;if(t.clearPlanDecisionTokens?.(e),!o)return{text:`Plan rejected for [${i}].`,isError:!1};let a=Bc(o,"rejected");return r?(Uc(r,a),t.updatePersistedSession?.(e,a),t.kill(r.id,"user"),{text:`Plan rejected for [${r.name}]. Session stopped.`}):(t.updatePersistedSession?.(e,a),{text:`Plan rejected for [${i}]. Session remains stopped.`})}function yp(t,e){let r=t.resolve(e),n=r?void 0:t.getPersistedSession(e),o=r??n,i=o?.name??e;if(t.clearPlanDecisionTokens?.(e),o){let a=Bc(o,"changes_requested");r&&Uc(r,a),t.updatePersistedSession?.(e,a)}return{text:`Type your revision feedback for [${i}] and I'll forward it to the agent.`}}async function ab(t,e,r,n={}){let o=_o(e);if(!(o.kind==="resume"||Fc(e)))return;let a=!!(n.approve&&ob(e)),u=a?qc(n.approvalRationale):void 0;try{if(o.kind!=="resume")return o.kind==="relaunch"?Nc(t,e,r):Uo(e,o.reason);let p={prompt:a?nb+r:r,sessionIdOverride:o.stableSessionId,workdir:e.workdir,name:e.name,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,resumeSessionId:o.resumeSessionId,resumeWorktreeFrom:tb(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:a?"bypassPermissions":e.currentPermissionMode,requestedPermissionMode:e.requestedPermissionMode??e.currentPermissionMode,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,pendingPlanApproval:a?!1:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:e.planDecisionVersion,actionablePlanDecisionVersion:a?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,...a?{approvalState:"approved",approvalExecutionState:"approved_then_implemented",approvalRationale:u,planModeApproved:!0}:{},harness:"harnessName"in e?e.harnessName:e.harness},d=await t.spawnAndAwaitRunning(p,{notifyLaunch:!1});return a?(t.notifySession(d,`\u{1F44D} [${d.name}] Plan approved (resumed)`,"plan-approved"),{text:`Plan approved for session ${d.name} [${d.id}]. Session resumed in bypassPermissions mode. Use agent_output to see the response.`}):(t.notifySession(d,`\u25B6\uFE0F [${d.name}] Auto-resumed`),{text:`Auto-resumed session ${d.name} [${d.id}]. Use agent_output to see the response.`})}catch(p){return Uo(e,"missing_backend_state",`Backend resume failed: ${gp(p)}`)}}async function Et(t,e){let r=t.resolve(e.session),n=r?void 0:t.getPersistedSession(e.session);if(!r&&!n)return{text:`Error: Session "${e.session}" not found.`,isError:!0};let o=r??n,i=o.status==="running"?{kind:"direct"}:_o(o),a=!e.approve&&o.lifecycle==="awaiting_plan_decision"&&o.pendingPlanApproval&&e.userInitiated?rb(e.message):void 0;if(a==="approve")return Et(t,{...e,message:"Approved. Go ahead.",approve:!0});if(a==="revise")return yp(t,r?.id??n?.sessionId??e.session);if(a==="reject")return hp(t,r?.id??n?.sessionId??e.session);if(e.approve){let p=fp(o);if(p)return{text:p,isError:!0}}if(i.kind==="resume"||Fc(o)){let p=await ab(t,o,e.message,{approve:e.approve,approvalRationale:e.approvalRationale});if(p)return p}else{if(i.kind==="relaunch")return Nc(t,o,e.message);if(i.kind==="unavailable")return Uo(o,i.reason)}if(!r)return Oo(n)?Uo(n,"completed"):{text:`Error: Session ${n.name} [${pn(n)}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};if(r.status!=="running")return Oo(r)?Uo(r,"completed"):{text:`Error: Session ${r.name} [${r.id}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};let u=K.maxAutoResponds??eb;if(e.userInitiated)r.resetAutoRespond();else if(r.autoRespondCount>=u)return{text:`\u26A0\uFE0F Auto-respond limit reached (${r.autoRespondCount}/${u}). Ask the user to provide the answer for session ${r.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};try{if(e.approve){let y=fp(r);if(y)return{text:y,isError:!0}}if(!e.approve&&r.pendingInputState?.allowsFreeText&&await r.submitPendingInputText?.(e.message)===!0){if(e.userInitiated){let S=Je(e.message,100);t.notifySession(r,`\u21AA\uFE0F [${r.name}] "${S}"`,"agent-respond")}e.userInitiated||r.incrementAutoRespond();let y=Je(e.message,80);return{text:[`Pending input answered for session ${r.name} [${r.id}].`,` Message: "${y}"`,"Use agent_output to see the response."].join(`
88
- `)}}let d=!1;e.interrupt&&(d=await r.interrupt());let l=!!(e.approve&&vs(r)),m=l?qc(e.approvalRationale):void 0,c="";if(e.approve&&vs(r)?(r.switchPermissionMode("bypassPermissions"),r.approvalRationale=m):e.approve&&r.currentPermissionMode==="default"?r.switchPermissionMode("bypassPermissions"):e.approve&&r.currentPermissionMode==="bypassPermissions"?c=`
87
+ `;function Gc(t){let e=t?.replace(/\s+/g," ").trim();if(e)return Je(e,240)}function xp(t){if(t.approvalState==="changes_requested"&&!Ts(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 Ts(t){return t.pendingPlanApproval?(t.approvalState==="changes_requested"?t.actionablePlanDecisionVersion:t.actionablePlanDecisionVersion??t.planDecisionVersion)>0:!1}function hb(t){return xp(t)?!1:Ts(t)||t.currentPermissionMode==="plan"}function yb(t,e){let r=t.updatePersistedSession;if(typeof r!="function")return;let n=e.controlStateSnapshot();r.call(t,e.id,{lifecycle:n.lifecycle,approvalState:n.approvalState,approvalExecutionState:n.approvalExecutionState,runtimeState:n.runtimeState,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,pendingPlanApproval:n.pendingPlanApproval,planApprovalContext:n.planApprovalContext,planDecisionVersion:n.planDecisionVersion,actionablePlanDecisionVersion:n.actionablePlanDecisionVersion,planModeApproved:n.planModeApproved,approvalRationale:e.approvalRationale})}function kb(t){return(t.planDecisionVersion??0)+1}function Vc(t,e){let r={approvalState:e,lifecycle:e==="rejected"?"terminal":"awaiting_user_input",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:kb(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"&&(r.runtimeState="stopped"),r}function Hc(t,e){let r=t;typeof r.applyControlPatch=="function"&&r.applyControlPatch(e),Object.assign(t,e)}function wp(t,e){let r=t.resolve(e),n=r?void 0:t.getPersistedSession(e),o=r??n,i=o?.name??e;if(t.clearPlanDecisionTokens?.(e),!o)return{text:`Plan rejected for [${i}].`,isError:!1};let a=Vc(o,"rejected");return r?(Hc(r,a),t.updatePersistedSession?.(e,a),t.kill(r.id,"user"),{text:`Plan rejected for [${r.name}]. Session stopped.`}):(t.updatePersistedSession?.(e,a),{text:`Plan rejected for [${i}]. Session remains stopped.`})}function vp(t,e){let r=t.resolve(e),n=r?void 0:t.getPersistedSession(e),o=r??n,i=o?.name??e;if(t.clearPlanDecisionTokens?.(e),o){let a=Vc(o,"changes_requested");r&&Hc(r,a),t.updatePersistedSession?.(e,a)}return{text:`Type your revision feedback for [${i}] and I'll forward it to the agent.`}}async function Sb(t,e,r,n={}){let o=Do(e);if(!(o.kind==="resume"||Kc(e)))return;let a=!!(n.approve&&hb(e)),u=a?Gc(n.approvalRationale):void 0;try{if(o.kind!=="resume")return o.kind==="relaunch"?jc(t,e,r):Wo(e,o.reason);let p={prompt:a?gb+r:r,sessionIdOverride:o.stableSessionId,workdir:e.workdir,name:e.name,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,resumeSessionId:o.resumeSessionId,resumeWorktreeFrom:cb(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:a?"bypassPermissions":e.currentPermissionMode,requestedPermissionMode:e.requestedPermissionMode??e.currentPermissionMode,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,pendingPlanApproval:a?!1:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:e.planDecisionVersion,actionablePlanDecisionVersion:a?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,...a?{approvalState:"approved",approvalExecutionState:"approved_then_implemented",approvalRationale:u,planModeApproved:!0}:{},harness:"harnessName"in e?e.harnessName:e.harness},d=await t.spawnAndAwaitRunning(p,{notifyLaunch:!1});return a?(t.notifySession(d,`\u{1F44D} [${d.name}] Plan approved (resumed)`,"plan-approved"),{text:`Plan approved for session ${d.name} [${d.id}]. Session resumed in bypassPermissions mode. Use agent_output to see the response.`}):(t.notifySession(d,`\u25B6\uFE0F [${d.name}] Auto-resumed`),{text:`Auto-resumed session ${d.name} [${d.id}]. Use agent_output to see the response.`})}catch(p){return Wo(e,"missing_backend_state",`Backend resume failed: ${Pp(p)}`)}}async function Et(t,e){let r=t.resolve(e.session),n=r?void 0:t.getPersistedSession(e.session);if(!r&&!n)return{text:`Error: Session "${e.session}" not found.`,isError:!0};let o=r??n,i=o.status==="running"?{kind:"direct"}:Do(o),a=!e.approve&&o.lifecycle==="awaiting_plan_decision"&&o.pendingPlanApproval&&e.userInitiated?fb(e.message):void 0;if(a==="approve")return Et(t,{...e,message:"Approved. Go ahead.",approve:!0});if(a==="revise")return vp(t,r?.id??n?.sessionId??e.session);if(a==="reject")return wp(t,r?.id??n?.sessionId??e.session);if(e.approve){let p=xp(o);if(p)return{text:p,isError:!0}}if(i.kind==="resume"||Kc(o)){let p=await Sb(t,o,e.message,{approve:e.approve,approvalRationale:e.approvalRationale});if(p)return p}else{if(i.kind==="relaunch")return jc(t,o,e.message);if(i.kind==="unavailable")return Wo(o,i.reason)}if(!r)return _o(n)?Wo(n,"completed"):{text:`Error: Session ${n.name} [${pn(n)}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};if(r.status!=="running")return _o(r)?Wo(r,"completed"):{text:`Error: Session ${r.name} [${r.id}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};let u=K.maxAutoResponds??mb;if(e.userInitiated)r.resetAutoRespond();else if(r.autoRespondCount>=u)return{text:`\u26A0\uFE0F Auto-respond limit reached (${r.autoRespondCount}/${u}). Ask the user to provide the answer for session ${r.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};try{if(e.approve){let y=xp(r);if(y)return{text:y,isError:!0}}if(!e.approve&&r.pendingInputState?.allowsFreeText&&await r.submitPendingInputText?.(e.message)===!0){if(e.userInitiated){let k=Je(e.message,100);t.notifySession(r,`\u21AA\uFE0F [${r.name}] "${k}"`,"agent-respond")}e.userInitiated||r.incrementAutoRespond();let y=Je(e.message,80);return{text:[`Pending input answered for session ${r.name} [${r.id}].`,` Message: "${y}"`,"Use agent_output to see the response."].join(`
88
+ `)}}let d=!1;e.interrupt&&(d=await r.interrupt());let l=!!(e.approve&&Ts(r)),m=l?Gc(e.approvalRationale):void 0,c="";if(e.approve&&Ts(r)?(r.switchPermissionMode("bypassPermissions"),r.approvalRationale=m):e.approve&&r.currentPermissionMode==="default"?r.switchPermissionMode("bypassPermissions"):e.approve&&r.currentPermissionMode==="bypassPermissions"?c=`
89
89
  \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:e.approve?c=`
90
90
  \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:(r.pendingPlanApproval||r.approvalState==="changes_requested")&&(c=`
91
- \u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`),await r.sendMessage(e.message),l&&ib(t,r),l)t.notifySession(r,`\u{1F44D} [${r.name}] Plan approved`,"plan-approved");else if(e.userInitiated){let y=Je(e.message,100);t.notifySession(r,`\u21AA\uFE0F [${r.name}] "${y}"`,"agent-respond")}e.userInitiated||r.incrementAutoRespond();let h=Je(e.message,80);return l?{text:`Plan approved for session ${r.name} [${r.id}]. Use agent_output to see the response.`}:{text:[`Message sent to session ${r.name} [${r.id}].`,d?" (redirected active turn first)":e.interrupt?" (no active turn to interrupt)":"",` Message: "${h}"`,c,"Use agent_output to see the response."].filter(Boolean).join(`
92
- `)}}catch(p){return{text:`Error sending message to session ${r.name} [${r.id}]: ${gp(p)}`,isError:!0}}}function ub(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 Wc(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(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!ub(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve?, approval_rationale? }."}]};let n=await Et(k,{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}]}}}}tt();le();function pb(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.summary=="string"}function Kc(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(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!pb(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, summary }."}]};let n=k.requestPlanApprovalFromUser(r.session,r.summary);return{isError:n.startsWith("Error:"),content:[{type:"text",text:n}]}}}}tt();le();ze();var Sp=["off","manual","ask","delegate","auto-merge","auto-pr"],bs=new Set(Sp),db=["low","medium","high","xhigh","max"],jc=new Set(db);function lb(t){return typeof t=="string"&&bs.has(t)}var mb=f.Union(Sp.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 cb(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||lb(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 fb(t,e){let r=On(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 gb(t,e){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=fb(t,e);return!r?.provider||!r.target?{content:[{type:"text",text:"Error: Could not resolve a direct delivery route for the plan offer."}]}:(k.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 Gc(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(mb),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 cb(r)?gb(t,r):{content:[{type:"text",text:"Error: Invalid parameters. Expected { offer_id, offer_text, plan_prompt, plan_workdir }."}]}}}}tt();le();function Vc(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(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=k.getMetrics(),o=k.list("running").length;return{content:[{type:"text",text:Yi(n,o)}]}}}}tt();ze();le();Pt();Wo();import{existsSync as Es}from"fs";function yb(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function Sb(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 $s(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(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!yb(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let n=jn(k,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.`}]};Es(a)||console.info(`[agent_merge] Worktree directory ${a} no longer exists; proceeding with merge via originalWorkdir (${u})`);let d=u;if(!Es(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(Es(a)&&!Fo(d,p,m)&&Kn(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 S={content:[{type:"text",text:"\u274C Merge did not run (internal error)"}]},I=n.persistedRef;return await k.enqueueMerge(d,async()=>{let x=k.getPersistedSession(r.session);if(x?.worktreeLifecycle?.state==="merged"||x?.worktreeMerged){S={content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" was already merged while waiting in queue.`}]};return}let R=sn(d,p,l),$=gs(d,p,m,c,a);if($.success){let C=Sb({mergeResult:$,repoDir:d,baseBranch:m});if(h&&!fs(d,m)){let H=`\u26A0\uFE0F Merged ${p} \u2192 ${m} locally, but failed to push ${m}`;k.notifyWorktreeOutcome(n.notificationTarget,H,{detailLines:[`Branch ${p} was merged into ${m} in the local repository.`,`Pushing ${m} failed; remote state may not include the merge.`,"Cleanup was skipped so the branch/worktree remains available for follow-up.",...C]}),S={content:[{type:"text",text:H}]};return}y&&Jt(d,p);let Ie=!1;if(Es(a)&&(Ie=xt(d,a),cs(d)),x)for(let H of Hc({...n,persistedSession:x}))k.updatePersistedSession(H,{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:l,targetRepo:x.worktreePrTargetRepo,pushRemote:x.worktreePushRemote}});let Sr=an({kind:"merge",branch:p,base:l,filesChanged:R?.filesChanged,insertions:R?.insertions,deletions:R?.deletions});k.notifyWorktreeOutcome(n.notificationTarget,Sr,{detailLines:[$.fastForward?"Merge type: fast-forward.":"Merge type: merge commit.",h?`Pushed ${m}.`:`Did not push ${m}; push was not requested.`,y?Ie?"Branch and worktree cleaned up.":"Branch deleted; worktree cleanup skipped.":"Branch/worktree cleanup was not requested.",...C]});let j=`\u2705 ${$.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${p} \u2192 ${m}.${h?" Pushed.":""}${y?Ie?" Branch and worktree cleaned up.":" Branch deleted; worktree cleanup skipped.":""}`;$.stashPopConflict?j+=`
91
+ \u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`),await r.sendMessage(e.message),l&&yb(t,r),l)t.notifySession(r,`\u{1F44D} [${r.name}] Plan approved`,"plan-approved");else if(e.userInitiated){let y=Je(e.message,100);t.notifySession(r,`\u21AA\uFE0F [${r.name}] "${y}"`,"agent-respond")}e.userInitiated||r.incrementAutoRespond();let h=Je(e.message,80);return l?{text:`Plan approved for session ${r.name} [${r.id}]. Use agent_output to see the response.`}:{text:[`Message sent to session ${r.name} [${r.id}].`,d?" (redirected active turn first)":e.interrupt?" (no active turn to interrupt)":"",` Message: "${h}"`,c,"Use agent_output to see the response."].filter(Boolean).join(`
92
+ `)}}catch(p){return{text:`Error sending message to session ${r.name} [${r.id}]: ${Pp(p)}`,isError:!0}}}function Ib(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 zc(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(!Ib(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}]}}}}tt();le();function xb(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.summary=="string"}function Jc(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(!xb(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}]}}}}tt();le();ze();var bp=["off","manual","ask","delegate","auto-merge","auto-pr"],Rs=new Set(bp),Pb=["low","medium","high","xhigh","max"],Qc=new Set(Pb);function wb(t){return typeof t=="string"&&Rs.has(t)}var vb=f.Union(bp.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 bb(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||wb(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 Ab(t,e){let r=On(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 Tb(t,e){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=Ab(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 Yc(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(vb),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 bb(r)?Tb(t,r):{content:[{type:"text",text:"Error: Invalid parameters. Expected { offer_id, offer_text, plan_prompt, plan_workdir }."}]}}}}tt();le();function Zc(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:Xi(n,o)}]}}}}tt();ze();le();Pt();jo();import{existsSync as Os}from"fs";function Cb(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function Eb(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 _s(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(!Cb(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let n=jn(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.`}]};Os(a)||console.info(`[agent_merge] Worktree directory ${a} no longer exists; proceeding with merge via originalWorkdir (${u})`);let d=u;if(!Os(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(Os(a)&&!No(d,p,m)&&Kn(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 k={content:[{type:"text",text:"\u274C Merge did not run (internal error)"}]},S=n.persistedRef;return await I.enqueueMerge(d,async()=>{let x=I.getPersistedSession(r.session);if(x?.worktreeLifecycle?.state==="merged"||x?.worktreeMerged){k={content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" was already merged while waiting in queue.`}]};return}let R=sn(d,p,l),$=ks(d,p,m,c,a);if($.success){let C=Eb({mergeResult:$,repoDir:d,baseBranch:m});if(h&&!ys(d,m)){let H=`\u26A0\uFE0F Merged ${p} \u2192 ${m} locally, but failed to push ${m}`;I.notifyWorktreeOutcome(n.notificationTarget,H,{detailLines:[`Branch ${p} was merged into ${m} in the local repository.`,`Pushing ${m} failed; remote state may not include the merge.`,"Cleanup was skipped so the branch/worktree remains available for follow-up.",...C]}),k={content:[{type:"text",text:H}]};return}y&&Jt(d,p);let Ie=!1;if(Os(a)&&(Ie=xt(d,a),hs(d)),x)for(let H of Ko({...n,persistedSession:x}))I.updatePersistedSession(H,{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:l,targetRepo:x.worktreePrTargetRepo,pushRemote:x.worktreePushRemote}});let kr=an({kind:"merge",branch:p,base:l,filesChanged:R?.filesChanged,insertions:R?.insertions,deletions:R?.deletions});I.notifyWorktreeOutcome(n.notificationTarget,kr,{detailLines:[$.fastForward?"Merge type: fast-forward.":"Merge type: merge commit.",h?`Pushed ${m}.`:`Did not push ${m}; push was not requested.`,y?Ie?"Branch and worktree cleaned up.":"Branch deleted; worktree cleanup skipped.":"Branch/worktree cleanup was not requested.",...C]});let j=`\u2705 ${$.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${p} \u2192 ${m}.${h?" Pushed.":""}${y?Ie?" Branch and worktree cleaned up.":" Branch deleted; worktree cleanup skipped.":""}`;$.stashPopConflict?j+=`
94
94
  \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${$.stashRef??"stash@{0}"}\` in ${d} to review stashed changes.`:$.stashed&&(j+=`
95
- (Pre-existing changes on ${m} were auto-stashed and restored.)`),S={content:[{type:"text",text:j}]}}else if($.rebaseConflict)S={content:[{type:"text",text:`\u26A0\uFE0F Rebase conflicts \u2014 manual resolution required:
95
+ (Pre-existing changes on ${m} were auto-stashed and restored.)`),k={content:[{type:"text",text:j}]}}else if($.rebaseConflict)k={content:[{type:"text",text:`\u26A0\uFE0F Rebase conflicts \u2014 manual resolution required:
96
96
 
97
97
  ${$.error}`}]};else if($.conflictFiles&&$.conflictFiles.length>0){let C=["Resolve merge conflicts in the following files and commit the resolution:","",...$.conflictFiles.map(Ie=>`- ${Ie}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${p}"`].join(`
98
- `);try{let Ie=k.spawn({prompt:C,workdir:d,name:`${r.session}-conflict-resolver`,harness:dt(),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});S={content:[{type:"text",text:`\u26A0\uFE0F Merge conflicts in ${$.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${Ie.name}`}]}}catch(Ie){S={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${Ie instanceof Error?Ie.message:String(Ie)}`}]}}}else S={content:[{type:"text",text:$.dirtyError?`\u274C Merge blocked: ${$.error}`:`\u274C Merge failed: ${$.error??"unknown error"}`}]}}),S}}}Os();tt();le();Ee();Pt();Wo();function Eb(t){return!!t&&typeof t=="object"}function nf(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:f.Object({workdir:f.Optional(f.String({description:"Restrict cleanup to sessions rooted in this repository"})),base_branch:f.Optional(f.String({description:"Override base branch for lifecycle resolution"})),mode:f.Optional(f.Union([f.Literal("preview_safe"),f.Literal("clean_safe"),f.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:f.Optional(f.Boolean({description:"Deprecated. Safe cleanup never removes live sessions."})),force:f.Optional(f.Boolean({description:"Deprecated alias for skip_session_check."})),dry_run:f.Optional(f.Boolean({description:"Show what would be cleaned without deleting anything."})),session:f.Optional(f.String({description:"Session name or ID to clean or dismiss."})),dismiss_session:f.Optional(f.Boolean({description:"When true and session is provided, permanently dismiss the worktree."}))}),async execute(e,r){if(!k)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 { workdir?, base_branch?, mode?, dry_run?, session?, dismiss_session? }."}]};let n=r.session,o=r.mode??(r.dry_run===!0?"preview_safe":"clean_safe"),i=o!=="clean_safe",a=o==="preview_all"||o==="clean_safe";if(n&&r.dismiss_session===!0)return{content:[{type:"text",text:await k.dismissWorktree(n)}]};let u=Ts(k);if(n&&(u=u.filter(h=>Rs(h,n)),u.length===0)){let h=jn(k,n);if(!h.persistedSession&&!h.activeSession)return{content:[{type:"text",text:`Error: Session "${n}" not found.`}]}}if(r.workdir&&(u=u.filter(h=>h.workdir===r.workdir)),u.length===0)return{content:[{type:"text",text:"No managed worktrees matched the requested scope."}]};let p=[],d=[],l=[],m=[];for(let h of u){let{persistedSession:y,activeSession:S,resolvedLifecycle:I}=As(k,h,{baseBranch:r.base_branch});if(!I.cleanupSafe){if(a){let x=I.reasons.length>0?I.reasons.map(Cs).join(", "):dn(I.derivedState);d.push(`${h.name} [kept: ${x}]`)}continue}if(p.push(`${h.name} (${dn(I.derivedState)})`),!i)try{let x=h.workdir;if(!((y??S)&&lt(y??S))&&h.worktreePath&&xt(x,h.worktreePath,{destructive:!1}),h.worktreeBranch&&Jt(x,h.worktreeBranch),y){let $=I.derivedState==="merged"||I.derivedState==="released"?I.derivedState:I.lifecycle.state;k.updatePersistedSession(h.id,{worktreePath:void 0,worktreeBranch:void 0,lifecycle:"terminal",worktreeState:"none",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeMerged:$==="merged"?!0:y.worktreeMerged,worktreeMergedAt:$==="merged"?y.worktreeMergedAt??new Date().toISOString():y.worktreeMergedAt,worktreeLifecycle:{...y.worktreeLifecycle??I.lifecycle,state:$,updatedAt:new Date().toISOString(),resolvedAt:y.worktreeLifecycle?.resolvedAt??new Date().toISOString(),resolutionSource:y.worktreeLifecycle?.resolutionSource??"maintenance",baseBranch:r.base_branch??I.lifecycle.baseBranch??y.worktreeBaseBranch,targetRepo:y.worktreePrTargetRepo,pushRemote:y.worktreePushRemote,notes:I.reasons}})}l.push(`${h.name} (${dn(I.derivedState)})`)}catch(x){m.push(`${h.name}: ${x instanceof Error?x.message:String(x)}`)}}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"} (${p.length}): ${p.join(", ")||"(none)"}`),a&&c.push(` KEPT (${d.length}): ${d.join(", ")||"(none)"}`),i||(c.push(` CLEANED (${l.length}): ${l.join(", ")||"(none)"}`),c.push(` FAILURES (${m.length}): ${m.join(", ")||"(none)"}`)),{content:[{type:"text",text:c.join(`
99
- `)}]}}}}tt();le();Wo();function $b(t){return!0}function of(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:f.Object({session:f.Optional(f.String({description:"Session name or ID to show status for (optional, shows all if omitted)"}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!$b(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let n=r.session,o=Ts(k);if(n&&(o=o.filter(a=>Rs(a,n)),o.length===0))return{content:[{type:"text",text:`Error: Session "${n}" not found or has no worktree.`}]};if(o.length===0)return{content:[{type:"text",text:"No sessions with worktrees found."}]};let i=[];for(let a of o){let{persistedSession:u,resolvedLifecycle:p}=As(k,a),d=p.cleanupSafe?"safe now":p.preserve?"preserve":"blocked";i.push(`Session: ${a.name} [${a.id}]`),i.push(` Branch: ${a.worktreeBranch??"(unknown)"} \u2192 ${p.lifecycle.baseBranch??u?.worktreeBaseBranch??"main"}`),i.push(` Repo: ${a.workdir}`),i.push(` Lifecycle:${dn(p.lifecycle.state)}`),p.derivedState!==p.lifecycle.state&&i.push(` Derived: ${dn(p.derivedState)}`),i.push(` Cleanup: ${d}`),p.evidence.prUrl&&i.push(` PR: ${p.evidence.prUrl} (${p.evidence.prState??"unknown"})`),(p.evidence.branchAheadCount!=null||p.evidence.baseAheadCount!=null)&&i.push(` Ahead: ${p.evidence.branchAheadCount??0} ahead / ${p.evidence.baseAheadCount??0} behind`),i.push(` Reasons: ${p.reasons.length>0?p.reasons.map(Cs).join(", "):"none"}`),i.push("")}return{content:[{type:"text",text:i.join(`
100
- `).trim()}]}}}}tt();le();ze();import{existsSync as Mb}from"fs";function Ob(t=[]){return t.map((e,r)=>({label:`check-${r+1}`,command:e.trim()})).filter(e=>e.command.length>0)}function _s(t,e){let r=t.goal.trim();if(!r)return{kind:"error",text:"Error: goal must not be empty."};let n=t.workdir||e.workspaceDir||K.defaultWorkdir||process.cwd();if(!Mb(n))return{kind:"error",text:`Error: Working directory does not exist: ${n}`};let o=Ob(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 a=t.harness??dt(),u=t.model??$n(a);if(!u)return{kind:"error",text:`Error: No default model configured for harness "${a}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${a}.defaultModel or pass model explicitly.`};let p=_i(a);if(!Ji(u,p))return{kind:"error",text:`Error: Model "${u}" is not allowed. Permitted models: ${p?.join(", ")}`};let d=e.sessionKey||void 0,l=Di(e),m=bo(e,l),c=On(e,m,d);return{kind:"resolved",goal:r,name:t.name,workdir:n,model:u,reasoningEffort:Ir(a),fastMode:Mn(a),systemPrompt:t.systemPrompt,allowedTools:t.allowedTools,maxIterations:t.maxIterations,permissionMode:t.permissionMode??"bypassPermissions",harness:a,loopMode:i,completionPromise:t.completionPromise,originChannel:m,originThreadId:c?.threadId,originAgentId:e.agentId||void 0,originSessionKey:d,route:c,verifierCommands:o}}function Ds(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}`,...e.fastMode?[" Fast mode: enabled"]:[],` Loop mode: ${t.loopMode}`,` Max 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(n=>` - ${n.command}`)],"","Use goal_status to follow progress or goal_stop to terminate the task."].join(`
101
- `)}function _b(t){return!t||typeof t!="object"?!1:typeof t.goal=="string"}function sf(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:f.Object({goal:f.String({description:"End goal for the autonomous task"}),verifier_commands:f.Optional(f.Array(f.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:f.Optional(f.String({description:"Short task name (kebab-case preferred)"})),workdir:f.Optional(f.String({description:"Working directory (defaults to cwd / configured workspace)"})),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:"Allowed tools for the underlying agent session"})),max_iterations:f.Optional(f.Number({description:"Maximum verifier-driven repair iterations",minimum:1})),goal_mode:f.Optional(f.Union([f.Literal("ralph"),f.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:f.Optional(f.String({description:"Exact completion promise for Ralph-mode loops. Defaults to 'DONE'."})),permission_mode:f.Optional(f.Union([f.Literal("default"),f.Literal("plan"),f.Literal("bypassPermissions")],{description:"Permission mode for the underlying agent session. Defaults to bypassPermissions for autonomous goal loops."})),harness:f.Optional(f.String({description:"Agent harness to use (e.g. 'codex' or 'claude-code')."}))}),async execute(e,r){if(!Ce)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!_b(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { goal }."}]};let n=_s({goal:r.goal,verifierCommands:r.verifier_commands,name:r.name,workdir:r.workdir,model:r.model,systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,maxIterations:r.max_iterations,permissionMode:r.permission_mode,harness:r.harness,goalMode:r.goal_mode,completionPromise:r.completion_promise},t);if(n.kind!=="resolved")return{content:[{type:"text",text:n.text}]};try{let o=await Ce.launchTask({goal:n.goal,name:n.name,workdir:n.workdir,model:n.model,reasoningEffort:n.reasoningEffort,fastMode:n.fastMode,systemPrompt:n.systemPrompt,allowedTools:n.allowedTools,maxIterations:n.maxIterations,permissionMode:n.permissionMode,loopMode:n.loopMode,completionPromise:n.completionPromise,originChannel:n.originChannel,originThreadId:n.originThreadId,originAgentId:n.originAgentId,originSessionKey:n.originSessionKey,route:n.route,harness:n.harness,verifierCommands:n.verifierCommands});return{content:[{type:"text",text:Ds(o,n)}]}}catch(o){return{content:[{type:"text",text:`Error launching goal task: ${o instanceof Error?o.message:String(o)}`}]}}}}}tt();function af(t,e){return t.split(`
102
- `).map(r=>`${e}${r}`)}function Db(t,e=8,r=600){let n=t.map(i=>i.trimEnd()).filter(i=>i.trim().length>0);if(n.length===0)return;let o=n.slice(-e).join(`
103
- `);return o.length<=r?o:`...${o.slice(-(r-3))}`}function vr(t){if(t)return{phase:t.phase,awaitingInput:t.isAwaitingInput??!!t.pendingInputState,latestOutput:Db(t.getOutput(20))}}function br(t,e){let r=t.loopMode??"verifier",n=[`${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&&n.push(` Completion promise: ${t.completionPromise}`),t.sessionId&&n.push(` Session: ${t.sessionName??"(unknown)"} [${t.sessionId}]`),e?.phase&&n.push(` Phase: ${e.phase}`),e?.awaitingInput!==void 0&&n.push(` Awaiting input: ${e.awaitingInput?"yes":"no"}`),t.lastVerifierSummary&&(n.push(" Last verifier:"),n.push(...af(t.lastVerifierSummary," "))),e?.latestOutput&&(n.push(" Latest activity:"),n.push(...af(e.latestOutput," "))),t.waitingForUserReason&&n.push(` Waiting on user: ${t.waitingForUserReason}`),t.failureReason&&n.push(` Failure: ${t.failureReason}`),n.join(`
104
- `)}le();function uf(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:f.Object({task:f.Optional(f.String({description:"Task name or ID. Omit to list all tasks."}))}),async execute(e,r){if(!Ce)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};let n=r&&typeof r=="object"&&typeof r.task=="string"?r.task:void 0;if(n){let i=Ce.getTask(n);if(!i)return{content:[{type:"text",text:`Error: Goal task "${n}" not found.`}]};let a=i.sessionId?k?.resolve(i.sessionId):void 0;return{content:[{type:"text",text:br(i,vr(a))}]}}let o=Ce.listTasks();return o.length===0?{content:[{type:"text",text:"No goal tasks found."}]}:{content:[{type:"text",text:o.map(i=>{let a=i.sessionId?k?.resolve(i.sessionId):void 0;return br(i,vr(a))}).join(`
98
+ `);try{let Ie=I.spawn({prompt:C,workdir:d,name:`${r.session}-conflict-resolver`,harness:dt(),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});k={content:[{type:"text",text:`\u26A0\uFE0F Merge conflicts in ${$.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${Ie.name}`}]}}catch(Ie){k={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${Ie instanceof Error?Ie.message:String(Ie)}`}]}}}else k={content:[{type:"text",text:$.dirtyError?`\u274C Merge blocked: ${$.error}`:`\u274C Merge failed: ${$.error??"unknown error"}`}]}}),k}}}Bs();tt();le();Ee();Pt();jo();function Wb(t){return!!t&&typeof t=="object"}function lf(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:f.Object({workdir:f.Optional(f.String({description:"Restrict cleanup to sessions rooted in this repository"})),base_branch:f.Optional(f.String({description:"Override base branch for lifecycle resolution"})),mode:f.Optional(f.Union([f.Literal("preview_safe"),f.Literal("clean_safe"),f.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:f.Optional(f.Boolean({description:"Deprecated. Safe cleanup never removes live sessions."})),force:f.Optional(f.Boolean({description:"Deprecated alias for skip_session_check."})),dry_run:f.Optional(f.Boolean({description:"Show what would be cleaned without deleting anything."})),session:f.Optional(f.String({description:"Session name or ID to clean or dismiss."})),dismiss_session:f.Optional(f.Boolean({description:"When true and session is provided, permanently dismiss the worktree."}))}),async execute(e,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Wb(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { workdir?, base_branch?, mode?, dry_run?, session?, dismiss_session? }."}]};let n=r.session,o=r.mode??(r.dry_run===!0?"preview_safe":"clean_safe"),i=o!=="clean_safe",a=o==="preview_all"||o==="clean_safe";if(n&&r.dismiss_session===!0)return{content:[{type:"text",text:await I.dismissWorktree(n)}]};let u=Es(I);if(n&&(u=u.filter(h=>$s(h,n)),u.length===0)){let h=jn(I,n);if(!h.persistedSession&&!h.activeSession)return{content:[{type:"text",text:`Error: Session "${n}" not found.`}]}}if(r.workdir&&(u=u.filter(h=>h.workdir===r.workdir)),u.length===0)return{content:[{type:"text",text:"No managed worktrees matched the requested scope."}]};let p=[],d=[],l=[],m=[];for(let h of u){let{persistedSession:y,activeSession:k,resolvedLifecycle:S}=Cs(I,h,{baseBranch:r.base_branch});if(!S.cleanupSafe){if(a){let x=S.reasons.length>0?S.reasons.map(Ms).join(", "):dn(S.derivedState);d.push(`${h.name} [kept: ${x}]`)}continue}if(p.push(`${h.name} (${dn(S.derivedState)})`),!i)try{let x=h.workdir;if(!((y??k)&&mt(y??k))&&h.worktreePath&&xt(x,h.worktreePath,{destructive:!1}),h.worktreeBranch&&Jt(x,h.worktreeBranch),y){let $=S.derivedState==="merged"||S.derivedState==="released"?S.derivedState:S.lifecycle.state;I.updatePersistedSession(h.id,{worktreePath:void 0,worktreeBranch:void 0,lifecycle:"terminal",worktreeState:"none",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeMerged:$==="merged"?!0:y.worktreeMerged,worktreeMergedAt:$==="merged"?y.worktreeMergedAt??new Date().toISOString():y.worktreeMergedAt,worktreeLifecycle:{...y.worktreeLifecycle??S.lifecycle,state:$,updatedAt:new Date().toISOString(),resolvedAt:y.worktreeLifecycle?.resolvedAt??new Date().toISOString(),resolutionSource:y.worktreeLifecycle?.resolutionSource??"maintenance",baseBranch:r.base_branch??S.lifecycle.baseBranch??y.worktreeBaseBranch,targetRepo:y.worktreePrTargetRepo,pushRemote:y.worktreePushRemote,notes:S.reasons}})}l.push(`${h.name} (${dn(S.derivedState)})`)}catch(x){m.push(`${h.name}: ${x instanceof Error?x.message:String(x)}`)}}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"} (${p.length}): ${p.join(", ")||"(none)"}`),a&&c.push(` KEPT (${d.length}): ${d.join(", ")||"(none)"}`),i||(c.push(` CLEANED (${l.length}): ${l.join(", ")||"(none)"}`),c.push(` FAILURES (${m.length}): ${m.join(", ")||"(none)"}`)),{content:[{type:"text",text:c.join(`
99
+ `)}]}}}}tt();le();jo();function Kb(t){return!0}function mf(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:f.Object({session:f.Optional(f.String({description:"Session name or ID to show status for (optional, shows all if omitted)"}))}),async execute(e,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Kb(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let n=r.session,o=Es(I);if(n&&(o=o.filter(a=>$s(a,n)),o.length===0))return{content:[{type:"text",text:`Error: Session "${n}" not found or has no worktree.`}]};if(o.length===0)return{content:[{type:"text",text:"No sessions with worktrees found."}]};let i=[];for(let a of o){let{persistedSession:u,resolvedLifecycle:p}=Cs(I,a),d=p.cleanupSafe?"safe now":p.preserve?"preserve":"blocked";i.push(`Session: ${a.name} [${a.id}]`),i.push(` Branch: ${a.worktreeBranch??"(unknown)"} \u2192 ${p.lifecycle.baseBranch??u?.worktreeBaseBranch??"main"}`),i.push(` Repo: ${a.workdir}`),i.push(` Lifecycle:${dn(p.lifecycle.state)}`),p.derivedState!==p.lifecycle.state&&i.push(` Derived: ${dn(p.derivedState)}`),i.push(` Cleanup: ${d}`),p.evidence.prUrl&&i.push(` PR: ${p.evidence.prUrl} (${p.evidence.prState??"unknown"})`),(p.evidence.branchAheadCount!=null||p.evidence.baseAheadCount!=null)&&i.push(` Ahead: ${p.evidence.branchAheadCount??0} ahead / ${p.evidence.baseAheadCount??0} behind`),i.push(` Reasons: ${p.reasons.length>0?p.reasons.map(Ms).join(", "):"none"}`),i.push("")}return{content:[{type:"text",text:i.join(`
100
+ `).trim()}]}}}}tt();le();ze();import{existsSync as jb}from"fs";function Gb(t=[]){return t.map((e,r)=>({label:`check-${r+1}`,command:e.trim()})).filter(e=>e.command.length>0)}function Us(t,e){let r=t.goal.trim();if(!r)return{kind:"error",text:"Error: goal must not be empty."};let n=t.workdir||e.workspaceDir||K.defaultWorkdir||process.cwd();if(!jb(n))return{kind:"error",text:`Error: Working directory does not exist: ${n}`};let o=Gb(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 a=t.harness??dt(),u=t.model??$n(a);if(!u)return{kind:"error",text:`Error: No default model configured for harness "${a}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${a}.defaultModel or pass model explicitly.`};let p=Li(a);if(!Yi(u,p))return{kind:"error",text:`Error: Model "${u}" is not allowed. Permitted models: ${p?.join(", ")}`};let d=e.sessionKey||void 0,l=Fi(e),m=Ao(e,l),c=On(e,m,d);return{kind:"resolved",goal:r,name:t.name,workdir:n,model:u,reasoningEffort:Ir(a),fastMode:Mn(a),systemPrompt:t.systemPrompt,allowedTools:t.allowedTools,maxIterations:t.maxIterations,permissionMode:t.permissionMode??"bypassPermissions",harness:a,loopMode:i,completionPromise:t.completionPromise,originChannel:m,originThreadId:c?.threadId,originAgentId:e.agentId||void 0,originSessionKey:d,route:c,verifierCommands:o}}function Ws(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}`,...e.fastMode?[" Fast mode: enabled"]:[],` Loop mode: ${t.loopMode}`,` Max 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(n=>` - ${n.command}`)],"","Use goal_status to follow progress or goal_stop to terminate the task."].join(`
101
+ `)}function Vb(t){return!t||typeof t!="object"?!1:typeof t.goal=="string"}function cf(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:f.Object({goal:f.String({description:"End goal for the autonomous task"}),verifier_commands:f.Optional(f.Array(f.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:f.Optional(f.String({description:"Short task name (kebab-case preferred)"})),workdir:f.Optional(f.String({description:"Working directory (defaults to cwd / configured workspace)"})),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:"Allowed tools for the underlying agent session"})),max_iterations:f.Optional(f.Number({description:"Maximum verifier-driven repair iterations",minimum:1})),goal_mode:f.Optional(f.Union([f.Literal("ralph"),f.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:f.Optional(f.String({description:"Exact completion promise for Ralph-mode loops. Defaults to 'DONE'."})),permission_mode:f.Optional(f.Union([f.Literal("default"),f.Literal("plan"),f.Literal("bypassPermissions")],{description:"Permission mode for the underlying agent session. Defaults to bypassPermissions for autonomous goal loops."})),harness:f.Optional(f.String({description:"Agent harness to use (e.g. 'codex' or 'claude-code')."}))}),async execute(e,r){if(!Ce)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!Vb(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { goal }."}]};let n=Us({goal:r.goal,verifierCommands:r.verifier_commands,name:r.name,workdir:r.workdir,model:r.model,systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,maxIterations:r.max_iterations,permissionMode:r.permission_mode,harness:r.harness,goalMode:r.goal_mode,completionPromise:r.completion_promise},t);if(n.kind!=="resolved")return{content:[{type:"text",text:n.text}]};try{let o=await Ce.launchTask({goal:n.goal,name:n.name,workdir:n.workdir,model:n.model,reasoningEffort:n.reasoningEffort,fastMode:n.fastMode,systemPrompt:n.systemPrompt,allowedTools:n.allowedTools,maxIterations:n.maxIterations,permissionMode:n.permissionMode,loopMode:n.loopMode,completionPromise:n.completionPromise,originChannel:n.originChannel,originThreadId:n.originThreadId,originAgentId:n.originAgentId,originSessionKey:n.originSessionKey,route:n.route,harness:n.harness,verifierCommands:n.verifierCommands});return{content:[{type:"text",text:Ws(o,n)}]}}catch(o){return{content:[{type:"text",text:`Error launching goal task: ${o instanceof Error?o.message:String(o)}`}]}}}}}tt();function ff(t,e){return t.split(`
102
+ `).map(r=>`${e}${r}`)}function Hb(t,e=8,r=600){let n=t.map(i=>i.trimEnd()).filter(i=>i.trim().length>0);if(n.length===0)return;let o=n.slice(-e).join(`
103
+ `);return o.length<=r?o:`...${o.slice(-(r-3))}`}function vr(t){if(t)return{phase:t.phase,awaitingInput:t.isAwaitingInput??!!t.pendingInputState,latestOutput:Hb(t.getOutput(20))}}function br(t,e){let r=t.loopMode??"verifier",n=[`${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&&n.push(` Completion promise: ${t.completionPromise}`),t.sessionId&&n.push(` Session: ${t.sessionName??"(unknown)"} [${t.sessionId}]`),e?.phase&&n.push(` Phase: ${e.phase}`),e?.awaitingInput!==void 0&&n.push(` Awaiting input: ${e.awaitingInput?"yes":"no"}`),t.lastVerifierSummary&&(n.push(" Last verifier:"),n.push(...ff(t.lastVerifierSummary," "))),e?.latestOutput&&(n.push(" Latest activity:"),n.push(...ff(e.latestOutput," "))),t.waitingForUserReason&&n.push(` Waiting on user: ${t.waitingForUserReason}`),t.failureReason&&n.push(` Failure: ${t.failureReason}`),n.join(`
104
+ `)}le();function gf(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:f.Object({task:f.Optional(f.String({description:"Task name or ID. Omit to list all tasks."}))}),async execute(e,r){if(!Ce)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};let n=r&&typeof r=="object"&&typeof r.task=="string"?r.task:void 0;if(n){let i=Ce.getTask(n);if(!i)return{content:[{type:"text",text:`Error: Goal task "${n}" not found.`}]};let a=i.sessionId?I?.resolve(i.sessionId):void 0;return{content:[{type:"text",text:br(i,vr(a))}]}}let o=Ce.listTasks();return o.length===0?{content:[{type:"text",text:"No goal tasks found."}]}:{content:[{type:"text",text:o.map(i=>{let a=i.sessionId?I?.resolve(i.sessionId):void 0;return br(i,vr(a))}).join(`
105
105
 
106
- `)}]}}}}tt();le();function Lb(t){return!!t&&typeof t=="object"&&typeof t.task=="string"}function pf(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(!Ce)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!Lb(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task }."}]};let n=Ce.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.`}]}}}}le();Os();import{createHash as Fb}from"crypto";var wt="code-agent";var Nb=new Set(["1","true","yes","on"]);function qb(){let t=process.env.OPENCLAW_CODE_AGENT_BUTTON_DIAGNOSTICS?.trim().toLowerCase();return!!(t&&Nb.has(t))}function Gn(t){if(!(typeof t!="string"||t.length===0))return Fb("sha256").update(t).digest("hex").slice(0,12)}function df(t){return typeof t.callbackData=="string"?t.callbackData:typeof t.value=="string"?t.value:void 0}function xe(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=df(n);return o?Buffer.byteLength(o,"utf8"):void 0}):void 0,callbackHashes:r.length>0?r.map(n=>Gn(df(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 mf(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 cf(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 Pp(t){let e=cf(t);return{presentationBlockTypes:mf(t),...xe(e)}}function wp(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:mf(r),...lf("interactive",xe(cf(r))),...lf("telegramChannelData",xe(i)),hasPresentation:!!e?.presentation,hasInteractive:!!r,hasTelegramChannelDataButtons:!!i?.some(a=>a.length>0)}}function ff(t){let e=Ar(t);return e?{sendResultKeys:Object.keys(e).sort(),messageId:xp(e.messageId),chatId:xp(e.chatId),telegramThreadId:xp(e.messageThreadId??e.threadId),channel:typeof e.channel=="string"?e.channel:void 0}:{sendResultType:typeof t}}function xp(t){return typeof t=="string"||typeof t=="number"?t:void 0}function lf(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(!qb())return;let r=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0));console.info(`[CodeAgentButtonDiagnostics] ${JSON.stringify({event:t,callbackNamespace:wt,...r})}`)}function Bb(t){let e=t.trim().replace(new RegExp(`^${wt}:`),"");return e||null}async function Ls(t,e,r=!1){try{await ft(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 vp(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 Ub(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}function Wb(t,e){if(Ub(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 Kb(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 bp(t){let e=t instanceof Error?t.message:String(t);return/message is not modified/i.test(e)}function jb(t){let e=t instanceof Error?t.message:String(t);return/empty message/i.test(e)}async function ft(t,e={}){let r=t.respond,{alreadyAcknowledged:n=!1,text:o}=e;if(t.channel==="telegram"){if(typeof o=="string"&&typeof r.editMessage=="function")try{await r.editMessage({text:o,buttons:[]});return}catch(i){if(bp(i))return;let a=i instanceof Error?i.message:String(i);console.warn(`[callback-handler] Failed to edit Telegram worktree prompt before clearing buttons: ${a}`)}typeof r.clearButtons=="function"&&await r.clearButtons();return}if(typeof r.clearComponents=="function")try{await r.clearComponents(typeof o=="string"?{text:o}:void 0);return}catch(i){if(bp(i))return;if(jb(i)){if(typeof o!="string"&&n)return;if(typeof o!="string"&&typeof r.acknowledge=="function"){await r.acknowledge();return}typeof o!="string"&&typeof r.acknowledge!="function"&&console.warn("[callback-handler] clearComponents failed with empty-message error and no acknowledge fallback available")}else{if(typeof o!="string")throw i;{let a=i instanceof Error?i.message:String(i);console.warn(`[callback-handler] clearComponents failed before text fallback: ${a}`)}}}if(typeof o=="string"&&typeof r.editMessage=="function")try{await r.editMessage({text:o})}catch(i){if(!bp(i)){let a=i instanceof Error?i.message:String(i);console.warn(`[callback-handler] Failed to edit worktree prompt before clearing interactive state: ${a}`)}}typeof r.clearButtons=="function"&&await r.clearButtons()}async function Gb(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 ve(t,e){if(t.channel==="telegram"){await t.respond.reply({text:e});return}await t.respond.reply({text:e,ephemeral:!0})}function gf(t="telegram"){return ie("callback_handler_registered",{channel:t,namespace:wt}),{channel:t,namespace:wt,handler:async e=>{let r=await Gb(e);if(!e.auth.isAuthorizedSender)return await ve(e,"\u26D4 Unauthorized."),{handled:!0};let n=Kb(e),o=Bb(n);if(ie("callback_received",{channel:e.channel,namespace:wt,payloadByteLength:Buffer.byteLength(n,"utf8"),tokenHash:Gn(o),isAuthorizedSender:e.auth.isAuthorizedSender}),!o)return await ve(e,"\u26A0\uFE0F Unrecognized callback payload."),{handled:!0};if(!k)return await ve(e,"\u26A0\uFE0F Code agent service not running."),{handled:!0};let i=k.getActionToken(o);if(ie("callback_token_lookup_completed",{channel:e.channel,namespace:wt,tokenHash:Gn(o),tokenFound:!!i,actionKind:i?.kind,sessionId:i?.sessionId,planDecisionVersion:i?.planDecisionVersion}),!i)return await ft(e,{alreadyAcknowledged:r}),e.channel!=="telegram"&&await ve(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};let a=i.sessionId,u=k.resolve?.(a)??k.getPersistedSession?.(a),p=u?.name??a,d=Wb(i,u);if(ie("callback_plan_validation_completed",{channel:e.channel,namespace:wt,tokenHash:Gn(o),actionKind:i.kind,sessionId:a,sessionName:p,planDecisionVersion:i.planDecisionVersion,valid:!d}),d)return await ft(e,{alreadyAcknowledged:r}),await ve(e,`\u26A0\uFE0F ${d}`),{handled:!0};let l=k.consumeActionToken(o);if(ie("callback_token_consume_completed",{channel:e.channel,namespace:wt,tokenHash:Gn(o),consumed:!!l,actionKind:l?.kind,sessionId:l?.sessionId,planDecisionVersion:l?.planDecisionVersion}),!l)return await ft(e,{alreadyAcknowledged:r}),e.channel!=="telegram"&&await ve(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};switch(l.kind){case"worktree-merge":{await Ls(e,`\u2705 Merge selected for [${p}]`,r);let m=await $s().execute("callback",{session:a});await ve(e,vp(m));break}case"worktree-decide-later":{await Ls(e,`\u23ED\uFE0F Deferred for [${p}]`,r);let m=k.snoozeWorktreeDecision(a);await ve(e,m.startsWith("Error")?m:"\u23ED\uFE0F Snoozed 24h");break}case"worktree-dismiss":{await Ls(e,`\u{1F5D1}\uFE0F Discarded for [${p}]`,r);let m=await k.dismissWorktree(a);await ve(e,(m.startsWith("Error"),m));break}case"worktree-create-pr":case"worktree-update-pr":{await Ls(e,i.kind==="worktree-update-pr"?`\u{1F4EC} PR update selected for [${p}]`:`\u{1F4EC} PR selected for [${p}]`,r);let m=await jo().execute("callback",{session:a});await ve(e,vp(m));break}case"worktree-view-pr":{await ft(e,{alreadyAcknowledged:r});let m=k.getPersistedSession?.(a),c=i.targetUrl??m?.worktreePrUrl;await ve(e,c?`PR: ${c}`:"\u26A0\uFE0F PR URL is no longer available.");break}case"plan-approve":{await ft(e,{alreadyAcknowledged:r}),k.clearPlanDecisionTokens(a);let m=await Et(k,{session:a,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});m.isError&&await ve(e,`\u26A0\uFE0F ${m.text}`);break}case"plan-reject":{await ft(e,{alreadyAcknowledged:r});let m=hp(k,a);await ve(e,`\u274C ${m.text}`);break}case"plan-request-changes":{await ft(e,{alreadyAcknowledged:r});let m=yp(k,a);await ve(e,`\u270F\uFE0F ${m.text}`);break}case"plan-offer-start":{if(await ft(e,{alreadyAcknowledged:r}),!l.launchPrompt||!l.launchWorkdir){await ve(e,"\u26A0\uFE0F This action is missing the plan launch context.");break}let m=k.launchPlanOffer({route:l.route,prompt:l.launchPrompt,workdir:l.launchWorkdir,name:l.launchName,worktreeStrategy:l.launchWorktreeStrategy});await ve(e,`\u25B6\uFE0F Planning session started: ${m.name} [${m.id}]`);break}case"plan-offer-dismiss":{await ft(e,{alreadyAcknowledged:r}),await ve(e,"\u2705 Dismissed.");break}case"session-restart":case"session-resume":{await ft(e,{alreadyAcknowledged:r});let m=await Et(k,{session:a,message:"Continue where you left off.",userInitiated:!0});await ve(e,m.isError?`\u26A0\uFE0F ${m.text}`:`\u25B6\uFE0F ${m.text}`);break}case"view-output":{await ft(e,{alreadyAcknowledged:r});let m=await ws().execute("callback",{session:a,lines:50});await ve(e,vp(m));break}case"question-answer":{if(await ft(e,{alreadyAcknowledged:r}),i.optionIndex==null){await ve(e,"\u26A0\uFE0F Invalid question-answer action.");break}await k.resolvePendingInputOption(a,i.optionIndex),await ve(e,"\u2705 Answer submitted.");break}default:{await ft(e,{alreadyAcknowledged:r}),await ve(e,"\u26A0\uFE0F Unknown callback action.");break}}return{handled:!0}}}}le();ze();function Vn(t){return hf(t).map(e=>e.value)}function hf(t){return Array.from(t.matchAll(/"[^"]*"|'[^']*'|\S+/g),e=>{let r=e[0],n=e.index??0;return{value:Vb(r),raw:r,start:n,end:n+r.length}})}function Ap(t){let[e]=hf(t);if(e)return{value:e.value,rest:t.slice(e.end).trimStart()}}function Vb(t){return t.length>1&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function Hb(t){return t instanceof Error?t.message:String(t)}function zb(t){let e=Vn(t),r,n=e;return e[0]==="--name"&&e[1]&&(r=e[1],n=e.slice(2)),{name:r,prompt:n.join(" ").trim()}}function yf(t){t.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /agent [--name <name>] <prompt>"};let{name:n,prompt:o}=zb(r);if(!o)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let i=Qi({prompt:o,name:n},e,k);if(i.kind!=="resolved")return{text:i.text};let a=k.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:ts(e)});return{text:k.formatLaunchResult({prompt:o,workdir:i.workdir,harness:i.harness,permissionMode:i.permissionMode??K.permissionMode,planApproval:i.planApproval},a)}}catch(i){let a=Hb(i),u=a.includes("Max sessions")?"":`
106
+ `)}]}}}}tt();le();function zb(t){return!!t&&typeof t=="object"&&typeof t.task=="string"}function hf(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(!Ce)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!zb(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task }."}]};let n=Ce.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.`}]}}}}le();Bs();import{createHash as Jb}from"crypto";var wt="code-agent";var Qb=new Set(["1","true","yes","on"]);function Yb(){let t=process.env.OPENCLAW_CODE_AGENT_BUTTON_DIAGNOSTICS?.trim().toLowerCase();return!!(t&&Qb.has(t))}function Gn(t){if(!(typeof t!="string"||t.length===0))return Jb("sha256").update(t).digest("hex").slice(0,12)}function yf(t){return typeof t.callbackData=="string"?t.callbackData:typeof t.value=="string"?t.value:void 0}function xe(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=yf(n);return o?Buffer.byteLength(o,"utf8"):void 0}):void 0,callbackHashes:r.length>0?r.map(n=>Gn(yf(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 Sf(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 If(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 Cp(t){let e=If(t);return{presentationBlockTypes:Sf(t),...xe(e)}}function Ep(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:Sf(r),...kf("interactive",xe(If(r))),...kf("telegramChannelData",xe(i)),hasPresentation:!!e?.presentation,hasInteractive:!!r,hasTelegramChannelDataButtons:!!i?.some(a=>a.length>0)}}function xf(t){let e=Ar(t);return e?{sendResultKeys:Object.keys(e).sort(),messageId:Rp(e.messageId),chatId:Rp(e.chatId),telegramThreadId:Rp(e.messageThreadId??e.threadId),channel:typeof e.channel=="string"?e.channel:void 0}:{sendResultType:typeof t}}function Rp(t){return typeof t=="string"||typeof t=="number"?t:void 0}function kf(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(!Yb())return;let r=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0));console.info(`[CodeAgentButtonDiagnostics] ${JSON.stringify({event:t,callbackNamespace:wt,...r})}`)}function Zb(t){let e=t.trim().replace(new RegExp(`^${wt}:`),"");return e||null}async function Ks(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 js(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 Pf(t){if(t&&typeof t=="object"&&"meta"in t){let e=t.meta;if(typeof e?.success=="boolean")return e.success}return $p(js(t))}function $p(t){return!/^\s*(?:Error\b:?|❌|⚠️)/.test(t)}function Xb(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}function eA(t,e){if(Xb(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 tA(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 Ho(t){let e=t instanceof Error?t.message:String(t);return/message is not modified/i.test(e)}function rA(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(Ho(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(Ho(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(Ho(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(Ho(a))return;if(rA(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(!Ho(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 nA(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 Pe(t,e){if(t.channel==="telegram"){await t.respond.reply({text:e});return}await t.respond.reply({text:e,ephemeral:!0})}function wf(t="telegram"){return ie("callback_handler_registered",{channel:t,namespace:wt}),{channel:t,namespace:wt,handler:async e=>{let r=await nA(e);if(!e.auth.isAuthorizedSender)return await Pe(e,"\u26D4 Unauthorized."),{handled:!0};let n=tA(e),o=Zb(n);if(ie("callback_received",{channel:e.channel,namespace:wt,payloadByteLength:Buffer.byteLength(n,"utf8"),tokenHash:Gn(o),isAuthorizedSender:e.auth.isAuthorizedSender}),!o)return await Pe(e,"\u26A0\uFE0F Unrecognized callback payload."),{handled:!0};if(!I)return await Pe(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:Gn(o),tokenFound:!!i,actionKind:i?.kind,sessionId:i?.sessionId,planDecisionVersion:i?.planDecisionVersion}),!i)return await ct(e,{alreadyAcknowledged:r}),e.channel!=="telegram"&&await Pe(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=eA(i,u);if(ie("callback_plan_validation_completed",{channel:e.channel,namespace:wt,tokenHash:Gn(o),actionKind:i.kind,sessionId:a,sessionName:p,planDecisionVersion:i.planDecisionVersion,valid:!d}),d)return await ct(e,{alreadyAcknowledged:r}),await Pe(e,`\u26A0\uFE0F ${d}`),{handled:!0};let l=I.consumeActionToken(o);if(ie("callback_token_consume_completed",{channel:e.channel,namespace:wt,tokenHash:Gn(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 Pe(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};switch(l.kind){case"worktree-merge":{let m=await _s().execute("callback",{session:a}),c=js(m);Pf(m)&&await Ks(e,`\u2705 Merge selected for [${p}]`,r),await Pe(e,c);break}case"worktree-decide-later":{let m=I.snoozeWorktreeDecision(a),c=$p(m);c&&await Ks(e,`\u23ED\uFE0F Deferred for [${p}]`,r),await Pe(e,c?"\u23ED\uFE0F Snoozed 24h":m);break}case"worktree-dismiss":{let m=await I.dismissWorktree(a),c=$p(m);c&&await Ks(e,`\u{1F5D1}\uFE0F Discarded for [${p}]`,r),await Pe(e,c?"\u2705 Discarded":m);break}case"worktree-create-pr":case"worktree-update-pr":{let m=await Vo().execute("callback",{session:a}),c=js(m);Pf(m)&&await Ks(e,i.kind==="worktree-update-pr"?`\u{1F4EC} PR update selected for [${p}]`:`\u{1F4EC} PR selected for [${p}]`,r),await Pe(e,c);break}case"worktree-view-pr":{await ct(e,{alreadyAcknowledged:r});let m=I.getPersistedSession?.(a),c=i.targetUrl??m?.worktreePrUrl;await Pe(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 Pe(e,`\u26A0\uFE0F ${m.text}`);break}case"plan-reject":{await ct(e,{alreadyAcknowledged:r});let m=wp(I,a);await Pe(e,`\u274C ${m.text}`);break}case"plan-request-changes":{await ct(e,{alreadyAcknowledged:r});let m=vp(I,a);await Pe(e,`\u270F\uFE0F ${m.text}`);break}case"plan-offer-start":{if(!l.launchPrompt||!l.launchWorkdir){await ct(e,{alreadyAcknowledged:r,forceTelegramMarkupEdit:!0}),await Pe(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 Pe(e,`\u26A0\uFE0F Failed to start planning session: ${h}`);break}await ct(e,{alreadyAcknowledged:r,forceTelegramMarkupEdit:!0}),await Pe(e,`\u25B6\uFE0F Planning session started: ${m.name} [${m.id}]`);break}case"plan-offer-dismiss":{await ct(e,{alreadyAcknowledged:r,forceTelegramMarkupEdit:!0}),await Pe(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 Pe(e,m.isError?`\u26A0\uFE0F ${m.text}`:`\u25B6\uFE0F ${m.text}`);break}case"view-output":{await ct(e,{alreadyAcknowledged:r});let m=await As().execute("callback",{session:a,lines:50});await Pe(e,js(m));break}case"question-answer":{if(await ct(e,{alreadyAcknowledged:r}),i.optionIndex==null){await Pe(e,"\u26A0\uFE0F Invalid question-answer action.");break}await I.resolvePendingInputOption(a,i.optionIndex),await Pe(e,"\u2705 Answer submitted.");break}default:{await ct(e,{alreadyAcknowledged:r}),await Pe(e,"\u26A0\uFE0F Unknown callback action.");break}}return{handled:!0}}}}le();ze();function Vn(t){return vf(t).map(e=>e.value)}function vf(t){return Array.from(t.matchAll(/"[^"]*"|'[^']*'|\S+/g),e=>{let r=e[0],n=e.index??0;return{value:oA(r),raw:r,start:n,end:n+r.length}})}function Mp(t){let[e]=vf(t);if(e)return{value:e.value,rest:t.slice(e.end).trimStart()}}function oA(t){return t.length>1&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function iA(t){return t instanceof Error?t.message:String(t)}function sA(t){let e=Vn(t),r,n=e;return e[0]==="--name"&&e[1]&&(r=e[1],n=e.slice(2)),{name:r,prompt:n.join(" ").trim()}}function bf(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}=sA(r);if(!o)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let i=Zi({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:os(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=iA(i),u=a.includes("Max sessions")?"":`
107
107
 
108
- Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${a}${u}`}}}})}le();function Sf(t){t.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").split(/\s+/).includes("--full");return{text:xs(k,"all",void 0,{full:r})}}})}le();function kf(t){t.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=e.args?.trim();return r?{text:Ps(k,r,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}le();function If(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(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:`Usage: /agent_respond <id-or-name> <message>
109
- /agent_respond --interrupt <id-or-name> <message>`};let n=!1,o=r,i=Ap(o);i?.value==="--interrupt"&&(n=!0,o=i.rest);let a=Ap(o);if(!a)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let u=a.value,p=a.rest;return p.trim()?{text:(await Et(k,{session:u,message:p,interrupt:n,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}le();function xf(t){t.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let e=k.getMetrics(),r=k.list("running").length;return{text:Yi(e,r)}}})}le();var Jb=50;function Pf(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(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let n=Vn(r),o="",i=!1,a=Jb;for(let p=0;p<n.length;p++)if(n[p]==="--full")i=!0;else if(n[p]==="--lines"&&p+1<n.length){let d=parseInt(n[p+1],10);!isNaN(d)&&d>0&&(a=d),p++}else o||(o=n[p]);return o?{text:Is(k,o,{full:i,lines:a})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}le();var wf="Usage: /goal [--name <name>] [--workdir <dir>] [--model <model>] [--harness <name>] [--mode <ralph|verifier>] [--completion-promise <text>] [--max-iterations N] [--verify <cmd> ...] <goal>";function vf(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(!Ce)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:wf};let n=Vn(r),o,i,a,u,p="bypassPermissions",d,l,m,c=[],h=[];for(let I=0;I<n.length;I++){let x=n[I];if(x==="--name"&&I+1<n.length)o=n[++I];else if(x==="--workdir"&&I+1<n.length)i=n[++I];else if(x==="--model"&&I+1<n.length)a=n[++I];else if(x==="--max-iterations"&&I+1<n.length){let R=parseInt(n[++I],10);!Number.isNaN(R)&&R>0&&(u=R)}else if(x==="--permission-mode"&&I+1<n.length){let R=n[++I];if(R==="default"||R==="plan"||R==="bypassPermissions")p=R;else return{text:`Error: Invalid permission mode "${R}".`}}else if(x==="--harness"&&I+1<n.length)d=n[++I];else if(x==="--mode"&&I+1<n.length){let R=n[++I];if(R==="ralph"||R==="verifier")l=R;else return{text:`Error: Invalid goal mode "${R}". Use ralph or verifier.`}}else if(x==="--completion-promise"&&I+1<n.length)m=n[++I];else if(x==="--verify"&&I+1<n.length){let R=n[++I].trim();if(!R)return{text:"Error: --verify commands must not be empty."};c.push(R)}else h.push(x)}let y=h.join(" ").trim();if(!y)return{text:wf};let S=_s({goal:y,verifierCommands:c,name:o,workdir:i,model:a,maxIterations:u,permissionMode:p,harness:d,goalMode:l,completionPromise:m},e);if(S.kind!=="resolved")return{text:S.text};try{let I=await Ce.launchTask({goal:S.goal,name:S.name,workdir:S.workdir,model:S.model,reasoningEffort:S.reasoningEffort,fastMode:S.fastMode,maxIterations:S.maxIterations,permissionMode:S.permissionMode,harness:S.harness,loopMode:S.loopMode,completionPromise:S.completionPromise,originChannel:S.originChannel,originThreadId:S.originThreadId,originAgentId:S.originAgentId,originSessionKey:S.originSessionKey,route:S.route,verifierCommands:S.verifierCommands});return{text:Ds(I,S)}}catch(I){return{text:`Error launching goal task: ${I instanceof Error?I.message:String(I)}`}}}})}le();function bf(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(!Ce)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(r){let o=Ce.getTask(r);if(!o)return{text:`Error: Goal task "${r}" not found.`};let i=o.sessionId?k?.resolve(o.sessionId):void 0;return{text:br(o,vr(i))}}let n=Ce.listTasks();return n.length===0?{text:"No goal tasks found."}:{text:n.map(o=>{let i=o.sessionId?k?.resolve(o.sessionId):void 0;return br(o,vr(i))}).join(`
108
+ Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${a}${u}`}}}})}le();function Af(t){t.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",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??"").split(/\s+/).includes("--full");return{text:vs(I,"all",void 0,{full:r})}}})}le();function Tf(t){t.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",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();return r?{text:bs(I,r,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}le();function Rf(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(!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_respond <id-or-name> <message>
109
+ /agent_respond --interrupt <id-or-name> <message>`};let n=!1,o=r,i=Mp(o);i?.value==="--interrupt"&&(n=!0,o=i.rest);let a=Mp(o);if(!a)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let u=a.value,p=a.rest;return p.trim()?{text:(await Et(I,{session:u,message:p,interrupt:n,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}le();function Cf(t){t.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let e=I.getMetrics(),r=I.list("running").length;return{text:Xi(e,r)}}})}le();var aA=50;function Ef(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(!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_output <id-or-name> [--full] [--lines N]"};let n=Vn(r),o="",i=!1,a=aA;for(let p=0;p<n.length;p++)if(n[p]==="--full")i=!0;else if(n[p]==="--lines"&&p+1<n.length){let d=parseInt(n[p+1],10);!isNaN(d)&&d>0&&(a=d),p++}else o||(o=n[p]);return o?{text:ws(I,o,{full:i,lines:a})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}le();var $f="Usage: /goal [--name <name>] [--workdir <dir>] [--model <model>] [--harness <name>] [--mode <ralph|verifier>] [--completion-promise <text>] [--max-iterations N] [--verify <cmd> ...] <goal>";function Mf(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(!Ce)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:$f};let n=Vn(r),o,i,a,u,p="bypassPermissions",d,l,m,c=[],h=[];for(let S=0;S<n.length;S++){let x=n[S];if(x==="--name"&&S+1<n.length)o=n[++S];else if(x==="--workdir"&&S+1<n.length)i=n[++S];else if(x==="--model"&&S+1<n.length)a=n[++S];else if(x==="--max-iterations"&&S+1<n.length){let R=parseInt(n[++S],10);!Number.isNaN(R)&&R>0&&(u=R)}else if(x==="--permission-mode"&&S+1<n.length){let R=n[++S];if(R==="default"||R==="plan"||R==="bypassPermissions")p=R;else return{text:`Error: Invalid permission mode "${R}".`}}else if(x==="--harness"&&S+1<n.length)d=n[++S];else if(x==="--mode"&&S+1<n.length){let R=n[++S];if(R==="ralph"||R==="verifier")l=R;else return{text:`Error: Invalid goal mode "${R}". Use ralph or verifier.`}}else if(x==="--completion-promise"&&S+1<n.length)m=n[++S];else if(x==="--verify"&&S+1<n.length){let R=n[++S].trim();if(!R)return{text:"Error: --verify commands must not be empty."};c.push(R)}else h.push(x)}let y=h.join(" ").trim();if(!y)return{text:$f};let k=Us({goal:y,verifierCommands:c,name:o,workdir:i,model:a,maxIterations:u,permissionMode:p,harness:d,goalMode:l,completionPromise:m},e);if(k.kind!=="resolved")return{text:k.text};try{let S=await Ce.launchTask({goal:k.goal,name:k.name,workdir:k.workdir,model:k.model,reasoningEffort:k.reasoningEffort,fastMode:k.fastMode,maxIterations:k.maxIterations,permissionMode:k.permissionMode,harness:k.harness,loopMode:k.loopMode,completionPromise:k.completionPromise,originChannel:k.originChannel,originThreadId:k.originThreadId,originAgentId:k.originAgentId,originSessionKey:k.originSessionKey,route:k.route,verifierCommands:k.verifierCommands});return{text:Ws(S,k)}}catch(S){return{text:`Error launching goal task: ${S instanceof Error?S.message:String(S)}`}}}})}le();function Of(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(!Ce)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(r){let o=Ce.getTask(r);if(!o)return{text:`Error: Goal task "${r}" not found.`};let i=o.sessionId?I?.resolve(o.sessionId):void 0;return{text:br(o,vr(i))}}let n=Ce.listTasks();return n.length===0?{text:"No goal tasks found."}:{text:n.map(o=>{let i=o.sessionId?I?.resolve(o.sessionId):void 0;return br(o,vr(i))}).join(`
110
110
 
111
- `)}}})}le();function Af(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(!Ce)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /goal_stop <task-id-or-name>"};let n=Ce.stopTask(r);return n?n.action==="already_terminal"?{text:`Task is already ${n.task.status}.`}:{text:`Task "${n.task.name}" (${n.task.id}) stopped.`}:{text:`Error: Goal task "${r}" not found.`}}})}import{execFile as uA}from"child_process";import{createHash as Df}from"crypto";import{existsSync as Qb,mkdirSync as Yb,readFileSync as Zb,renameSync as Xb,writeFileSync as eA}from"fs";import{homedir as tA}from"os";import{dirname as rA,join as Tf}from"path";function nA(t){let e=t.OPENCLAW_HOME?.trim();return e||Tf(tA(),".openclaw")}function oA(t){let e=t.OPENCLAW_CODE_AGENT_GOAL_TASKS_PATH?.trim();return e||Tf(nA(t),"code-agent-goal-tasks.json")}function iA(t){return t instanceof Error?t.message:String(t)}function sA(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 aA(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 r=e.status,n=r==="running"||r==="waiting_for_session"?"waiting_for_session":r;return{id:e.id,name:e.name,goal:e.goal,workdir:e.workdir,status:n,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:sA(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 Fs=class{path;tasks=new Map;constructor(e=process.env){this.path=oA(e),this.load()}load(){try{if(!Qb(this.path))return;let e=Zb(this.path,"utf8"),r=JSON.parse(e);if(!Array.isArray(r))return;for(let n of r){let o=aA(n);o&&this.tasks.set(o.id,o)}this.save()}catch{}}save(){try{Yb(rA(this.path),{recursive:!0});let e=`${this.path}.tmp`;eA(e,JSON.stringify([...this.tasks.values()],null,2),"utf8"),Xb(e,this.path)}catch(e){console.warn(`[GoalTaskStore] Failed to save ${this.path}: ${iA(e)}`)}}upsert(e){this.tasks.set(e.id,e),this.save()}get(e){let r=this.tasks.get(e);return r||[...this.tasks.values()].find(n=>n.name===e)}list(){return[...this.tasks.values()].sort((e,r)=>r.createdAt-e.createdAt)}};ir();var pA=8,Lf=600*1e3,dA=4e3,Tp=1200,lA="DONE",mA=["BASH_ENV","ENV"];function cA(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"goal-task"}function Go(t,e){return t.length<=e?t:`${t.slice(0,e-3)}...`}function Tr(t,e=20){let r=t.split(/\r?\n/).map(n=>n.trimEnd()).filter(n=>n.trim().length>0);return r.length<=e?r.join(`
111
+ `)}}})}le();function _f(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(!Ce)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /goal_stop <task-id-or-name>"};let n=Ce.stopTask(r);return n?n.action==="already_terminal"?{text:`Task is already ${n.task.status}.`}:{text:`Task "${n.task.name}" (${n.task.id}) stopped.`}:{text:`Error: Goal task "${r}" not found.`}}})}import{execFile as IA}from"child_process";import{createHash as Kf}from"crypto";import{existsSync as uA,mkdirSync as pA,readFileSync as dA,renameSync as lA,writeFileSync as mA}from"fs";import{homedir as cA}from"os";import{dirname as fA,join as Df}from"path";function gA(t){let e=t.OPENCLAW_HOME?.trim();return e||Df(cA(),".openclaw")}function hA(t){let e=t.OPENCLAW_CODE_AGENT_GOAL_TASKS_PATH?.trim();return e||Df(gA(t),"code-agent-goal-tasks.json")}function yA(t){return t instanceof Error?t.message:String(t)}function kA(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 SA(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 r=e.status,n=r==="running"||r==="waiting_for_session"?"waiting_for_session":r;return{id:e.id,name:e.name,goal:e.goal,workdir:e.workdir,status:n,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:kA(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 Gs=class{path;tasks=new Map;constructor(e=process.env){this.path=hA(e),this.load()}load(){try{if(!uA(this.path))return;let e=dA(this.path,"utf8"),r=JSON.parse(e);if(!Array.isArray(r))return;for(let n of r){let o=SA(n);o&&this.tasks.set(o.id,o)}this.save()}catch{}}save(){try{pA(fA(this.path),{recursive:!0});let e=`${this.path}.tmp`;mA(e,JSON.stringify([...this.tasks.values()],null,2),"utf8"),lA(e,this.path)}catch(e){console.warn(`[GoalTaskStore] Failed to save ${this.path}: ${yA(e)}`)}}upsert(e){this.tasks.set(e.id,e),this.save()}get(e){let r=this.tasks.get(e);return r||[...this.tasks.values()].find(n=>n.name===e)}list(){return[...this.tasks.values()].sort((e,r)=>r.createdAt-e.createdAt)}};ir();var xA=8,jf=600*1e3,PA=4e3,Op=1200,wA="DONE",vA=["BASH_ENV","ENV"];function bA(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"goal-task"}function zo(t,e){return t.length<=e?t:`${t.slice(0,e-3)}...`}function Tr(t,e=20){let r=t.split(/\r?\n/).map(n=>n.trimEnd()).filter(n=>n.trim().length>0);return r.length<=e?r.join(`
112
112
  `):r.slice(-e).join(`
113
- `)}function Rf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cf(t){let e=t?.trim();return e&&e.length>0?e:lA}function fA(t){return t.route??wo(t.originChannel,t.originThreadId,t.originSessionKey)}function Rp(t){return t.map((e,r)=>({label:e.label.trim()||`check-${r+1}`,command:e.command.trim(),timeoutMs:e.timeoutMs??Lf})).filter(e=>e.command.length>0)}function gA(t){return t.loopMode==="verifier"}function hA(t){return Rp(t.verifierCommands).length>0}function Ef(t){return gA(t)&&!hA(t)}function Ns(){return"Verifier-mode goal tasks require at least one verifier command."}function $f(t){let e=t.steps.filter(r=>!r.ok).map(r=>`${r.label}:${r.exitCode}:${Tr(r.output,12)}`).join(`
114
- `);return Df("sha1").update(e).digest("hex")}function yA(t){return Df("sha1").update(Tr(t,24)).digest("hex")}function Mf(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 SA(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(`
113
+ `)}function Lf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ff(t){let e=t?.trim();return e&&e.length>0?e:wA}function AA(t){return t.route??wo(t.originChannel,t.originThreadId,t.originSessionKey)}function _p(t){return t.map((e,r)=>({label:e.label.trim()||`check-${r+1}`,command:e.command.trim(),timeoutMs:e.timeoutMs??jf})).filter(e=>e.command.length>0)}function TA(t){return t.loopMode==="verifier"}function RA(t){return _p(t.verifierCommands).length>0}function Nf(t){return TA(t)&&!RA(t)}function Vs(){return"Verifier-mode goal tasks require at least one verifier command."}function qf(t){let e=t.steps.filter(r=>!r.ok).map(r=>`${r.label}:${r.exitCode}:${Tr(r.output,12)}`).join(`
114
+ `);return Kf("sha1").update(e).digest("hex")}function CA(t){return Kf("sha1").update(Tr(t,24)).digest("hex")}function Bf(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 EA(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(`
115
115
  `);let e=t.verifierCommands.map(r=>`- ${r.label}: ${r.command}`).join(`
116
116
  `);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(`
117
- `)}function Of(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(`
117
+ `)}function Uf(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(`
118
118
  `):["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(`
119
- `)}function kA(t,e){let r=e.steps.filter(o=>!o.ok).map(o=>[`- ${o.label} failed (exit ${o.exitCode})`,Tr(o.output,18)].join(`
119
+ `)}function $A(t,e){let r=e.steps.filter(o=>!o.ok).map(o=>[`- ${o.label} failed (exit ${o.exitCode})`,Tr(o.output,18)].join(`
120
120
  `)).join(`
121
121
 
122
122
  `);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:",r,"","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(`
123
- `)}function IA(t,e){let r=Tr(e,18)||"(no meaningful output)",n=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}.`,`- ${n}`,"","Latest output / blockers:",r,"","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(`
124
- `)}function xA(t,e){let r=e.steps.filter(n=>!n.ok).map(n=>[`- ${n.label} failed (exit ${n.exitCode})`,Tr(n.output,18)].join(`
123
+ `)}function MA(t,e){let r=Tr(e,18)||"(no meaningful output)",n=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}.`,`- ${n}`,"","Latest output / blockers:",r,"","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(`
124
+ `)}function OA(t,e){let r=e.steps.filter(n=>!n.ok).map(n=>[`- ${n.label} failed (exit ${n.exitCode})`,Tr(n.output,18)].join(`
125
125
  `)).join(`
126
126
 
127
127
  `);return["You emitted the completion promise, but the external verifiers did not pass.","","Goal:",t.goal,"","Verifier failures:",r,"","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(`
128
- `)}function PA(t,e){let r=e.trim();if(!r)return!1;let n=new RegExp(`(^|\\n)\\s*${Rf(r)}\\s*(\\n|$)`,"i"),o=new RegExp(`<promise>\\s*${Rf(r)}\\s*<\\/promise>`,"i");return n.test(t)||o.test(t)}function _f(t){return t.steps.map(e=>`${e.ok?"PASS":"FAIL"} ${e.label} (exit ${e.exitCode}, ${Math.round(e.durationMs)}ms)`).join(`
129
- `)}function ln(t){return t instanceof Error?t.message:String(t)}function wA(t){return t==="succeeded"||t==="failed"||t==="stopped"}function vA(t){return Go(t.error?.trim()||"Underlying session failed.",Tp)}function bA(t=process.env){let e={...t};for(let r of mA)delete e[r];return e}function AA(t,e){return new Promise(r=>{let n=Date.now();uA("bash",["-lc",e.command],{cwd:t,timeout:e.timeoutMs??Lf,maxBuffer:1024*1024,env:bA()},(o,i,a)=>{let u=Date.now()-n,p=typeof o?.code=="number"?o.code:o?1:0,d=`${i??""}${a?`
130
- ${a}`:""}`.trim();r({label:e.label,command:e.command,ok:!o,exitCode:p,durationMs:u,output:Go(d||"(no output)",dA)})})})}var qs=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 Fs}start(){this.started||(this.started=!0,!this.restorePromise&&(this.restorePromise=this.restoreRecoverableTasks().catch(e=>{console.warn(`[GoalController] Failed to restore recoverable tasks: ${ln(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 r=e.loopMode??"verifier",n=Rp(e.verifierCommands);if(r==="verifier"&&n.length===0)throw new Error(Ns());let i={id:rs(8),name:cA(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??pA,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:r,completionPromise:Cf(e.completionPromise),verifierCommands:n,repeatedFailureCount:0},a=await this.spawnTaskSession(i,SA(i));return this.attachSessionObservers(i,a),i.sessionId=a.id,i.sessionName=a.name,i.harnessSessionId=a.harnessSessionId,i.status="running",i.updatedAt=Date.now(),this.store.upsert(i),this.scheduleTaskEvaluation(i.id,"launch",a.id),this.notify(i,`\u{1F3AF} [${i.name}] Goal task started
128
+ `)}function _A(t,e){let r=e.trim();if(!r)return!1;let n=new RegExp(`(^|\\n)\\s*${Lf(r)}\\s*(\\n|$)`,"i"),o=new RegExp(`<promise>\\s*${Lf(r)}\\s*<\\/promise>`,"i");return n.test(t)||o.test(t)}function Wf(t){return t.steps.map(e=>`${e.ok?"PASS":"FAIL"} ${e.label} (exit ${e.exitCode}, ${Math.round(e.durationMs)}ms)`).join(`
129
+ `)}function ln(t){return t instanceof Error?t.message:String(t)}function DA(t){return t==="succeeded"||t==="failed"||t==="stopped"}function LA(t){return zo(t.error?.trim()||"Underlying session failed.",Op)}function FA(t=process.env){let e={...t};for(let r of vA)delete e[r];return e}function NA(t,e){return new Promise(r=>{let n=Date.now();IA("bash",["-lc",e.command],{cwd:t,timeout:e.timeoutMs??jf,maxBuffer:1024*1024,env:FA()},(o,i,a)=>{let u=Date.now()-n,p=typeof o?.code=="number"?o.code:o?1:0,d=`${i??""}${a?`
130
+ ${a}`:""}`.trim();r({label:e.label,command:e.command,ok:!o,exitCode:p,durationMs:u,output:zo(d||"(no output)",PA)})})})}var Hs=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 Gs}start(){this.started||(this.started=!0,!this.restorePromise&&(this.restorePromise=this.restoreRecoverableTasks().catch(e=>{console.warn(`[GoalController] Failed to restore recoverable tasks: ${ln(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 r=e.loopMode??"verifier",n=_p(e.verifierCommands);if(r==="verifier"&&n.length===0)throw new Error(Vs());let i={id:is(8),name:bA(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??xA,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:r,completionPromise:Ff(e.completionPromise),verifierCommands:n,repeatedFailureCount:0},a=await this.spawnTaskSession(i,EA(i));return this.attachSessionObservers(i,a),i.sessionId=a.id,i.sessionName=a.name,i.harnessSessionId=a.harnessSessionId,i.status="running",i.updatedAt=Date.now(),this.store.upsert(i),this.scheduleTaskEvaluation(i.id,"launch",a.id),this.notify(i,`\u{1F3AF} [${i.name}] Goal task started
131
131
 
132
132
  Goal:
133
- ${Go(i.goal,500)}`,"goal-task-started"),i}stopTask(e){let r=this.store.get(e);if(r)return wA(r.status)?{task:r,action:"already_terminal"}:(r.sessionId&&this.sessionManager.kill(r.sessionId,"user"),this.markTaskStopped(r,"Stopped by user."),{task:r,action:"stopped"})}async spawnTaskSession(e,r){return this.spawnManagedTaskSession(e,r)}async spawnManagedTaskSession(e,r,n){let o=n?this.sessionManager.resolveHarnessSessionId(n)??n:void 0,i=n?this.sessionManager.resolve(n):void 0,a=o?this.sessionManager.getPersistedSession(o)??this.sessionManager.getPersistedSession(n??o):void 0,{resumeSessionId:u}=_n({requestedResumeSessionId:o,activeSession:i?{harnessSessionId:i.harnessSessionId}:void 0,persistedSession:a?{harness:a.harness,backendRef:a.backendRef}:void 0}),p={prompt:r,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:fA(e),permissionMode:e.permissionMode,multiTurn:!0,goalTaskId:e.id,harness:e.harness,resumeSessionId:u,resumeWorktreeFrom:o,worktreeStrategy:"off"};return this.sessionManager.spawnAndAwaitRunning(p,{notifyLaunch:!1})}async resumeTaskSession(e,r,n){if(!n.harnessSessionId){let i=await this.spawnTaskSession(e,["The previous session ended without a resumable harness session id.","Continue working on the same goal.","",r].join(`
134
- `));return this.attachSessionObservers(e,i),i}let o=await this.spawnManagedTaskSession(e,r,n.harnessSessionId);return this.attachSessionObservers(e,o),o}resolveResumeSessionId(e){if(e.harnessSessionId)return e.harnessSessionId;if(e.sessionId){let n=this.sessionManager.resolveHarnessSessionId(e.sessionId);if(n)return n}let r=this.sessionManager.resolveHarnessSessionId(e.name);if(r)return r}captureRecoverableTasks(){for(let e of this.store.list()){if(e.status!=="running"&&e.status!=="waiting_for_session")continue;let r=e.sessionId?this.sessionManager.resolve(e.sessionId):void 0;r&&(e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId??e.harnessSessionId,e.route=r.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(Ef(e)){this.markTaskFailed(e,Ns());continue}if(e.sessionId){let n=this.sessionManager.resolve(e.sessionId);if(n&&(n.status==="starting"||n.status==="running"))continue}let r=this.resolveResumeSessionId(e);if(!r){this.markTaskFailed(e,"Goal task could not be resumed after gateway restart because no resumable session id was available.");continue}try{let n=await this.spawnManagedTaskSession(e,Of(e),r);if(!this.started){e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId??r,e.route=n.route??e.route,e.status="waiting_for_session",e.updatedAt=Date.now(),this.store.upsert(e),this.sessionManager.kill(n.id,"shutdown");break}this.attachSessionObservers(e,n),e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId??r,e.route=n.route??e.route,e.status="running",e.updatedAt=Date.now(),this.store.upsert(e),this.notifyIterationStatus(e,`\u{1F504} [${e.name}] Goal task resumed after gateway restart`,n),this.scheduleTaskEvaluation(e.id,"restore",n.id)}catch(n){this.markTaskFailed(e,`Failed to resume the goal task after gateway restart: ${ln(n)}`)}}}async runVerifiers(e){let r=Rp(e.verifierCommands);if(r.length===0){let a={status:"fail",steps:[{label:"verifier-config",command:"(none configured)",ok:!1,exitCode:1,durationMs:0,output:Ns()}],summary:"",fingerprint:""};return a.fingerprint=$f(a),a.summary=_f(a),a}let n=[];for(let a of r)n.push(await AA(e.workdir,a));let i={status:n.every(a=>a.ok)?"pass":"fail",steps:n,summary:"",fingerprint:""};return i.fingerprint=$f(i),i.summary=_f(i),i}notify(e,r,n){this.sessionManager.emitGoalTaskUpdate(e,r,n)}notifyIterationStatus(e,r,n){let o=vr(n??(e.sessionId?this.sessionManager.resolve(e.sessionId):void 0)),i=`${r}
133
+ ${zo(i.goal,500)}`,"goal-task-started"),i}stopTask(e){let r=this.store.get(e);if(r)return DA(r.status)?{task:r,action:"already_terminal"}:(r.sessionId&&this.sessionManager.kill(r.sessionId,"user"),this.markTaskStopped(r,"Stopped by user."),{task:r,action:"stopped"})}async spawnTaskSession(e,r){return this.spawnManagedTaskSession(e,r)}async spawnManagedTaskSession(e,r,n){let o=n?this.sessionManager.resolveHarnessSessionId(n)??n:void 0,i=n?this.sessionManager.resolve(n):void 0,a=o?this.sessionManager.getPersistedSession(o)??this.sessionManager.getPersistedSession(n??o):void 0,{resumeSessionId:u}=_n({requestedResumeSessionId:o,activeSession:i?{harnessSessionId:i.harnessSessionId}:void 0,persistedSession:a?{harness:a.harness,backendRef:a.backendRef}:void 0}),p={prompt:r,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:AA(e),permissionMode:e.permissionMode,multiTurn:!0,goalTaskId:e.id,harness:e.harness,resumeSessionId:u,resumeWorktreeFrom:o,worktreeStrategy:"off"};return this.sessionManager.spawnAndAwaitRunning(p,{notifyLaunch:!1})}async resumeTaskSession(e,r,n){if(!n.harnessSessionId){let i=await this.spawnTaskSession(e,["The previous session ended without a resumable harness session id.","Continue working on the same goal.","",r].join(`
134
+ `));return this.attachSessionObservers(e,i),i}let o=await this.spawnManagedTaskSession(e,r,n.harnessSessionId);return this.attachSessionObservers(e,o),o}resolveResumeSessionId(e){if(e.harnessSessionId)return e.harnessSessionId;if(e.sessionId){let n=this.sessionManager.resolveHarnessSessionId(e.sessionId);if(n)return n}let r=this.sessionManager.resolveHarnessSessionId(e.name);if(r)return r}captureRecoverableTasks(){for(let e of this.store.list()){if(e.status!=="running"&&e.status!=="waiting_for_session")continue;let r=e.sessionId?this.sessionManager.resolve(e.sessionId):void 0;r&&(e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId??e.harnessSessionId,e.route=r.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(Nf(e)){this.markTaskFailed(e,Vs());continue}if(e.sessionId){let n=this.sessionManager.resolve(e.sessionId);if(n&&(n.status==="starting"||n.status==="running"))continue}let r=this.resolveResumeSessionId(e);if(!r){this.markTaskFailed(e,"Goal task could not be resumed after gateway restart because no resumable session id was available.");continue}try{let n=await this.spawnManagedTaskSession(e,Uf(e),r);if(!this.started){e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId??r,e.route=n.route??e.route,e.status="waiting_for_session",e.updatedAt=Date.now(),this.store.upsert(e),this.sessionManager.kill(n.id,"shutdown");break}this.attachSessionObservers(e,n),e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId??r,e.route=n.route??e.route,e.status="running",e.updatedAt=Date.now(),this.store.upsert(e),this.notifyIterationStatus(e,`\u{1F504} [${e.name}] Goal task resumed after gateway restart`,n),this.scheduleTaskEvaluation(e.id,"restore",n.id)}catch(n){this.markTaskFailed(e,`Failed to resume the goal task after gateway restart: ${ln(n)}`)}}}async runVerifiers(e){let r=_p(e.verifierCommands);if(r.length===0){let a={status:"fail",steps:[{label:"verifier-config",command:"(none configured)",ok:!1,exitCode:1,durationMs:0,output:Vs()}],summary:"",fingerprint:""};return a.fingerprint=qf(a),a.summary=Wf(a),a}let n=[];for(let a of r)n.push(await NA(e.workdir,a));let i={status:n.every(a=>a.ok)?"pass":"fail",steps:n,summary:"",fingerprint:""};return i.fingerprint=qf(i),i.summary=Wf(i),i}notify(e,r,n){this.sessionManager.emitGoalTaskUpdate(e,r,n)}notifyIterationStatus(e,r,n){let o=vr(n??(e.sessionId?this.sessionManager.resolve(e.sessionId):void 0)),i=`${r}
135
135
 
136
- ${br(e,o)}`;this.notify(e,i,"goal-task-progress")}setTaskRunningWithSession(e,r){e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId,e.route=r.route??e.route,e.status="running",e.waitingForUserReason=void 0,e.updatedAt=Date.now(),this.store.upsert(e)}attachSessionObservers(e,r){if(this.observerDisposers.has(r.id))return;let n=(i,a)=>{(a==="completed"||a==="failed"||a==="killed")&&(this.removeSessionObserver(r.id),this.scheduleTaskEvaluation(e.id,`status:${a}`,r.id))},o=()=>{let i=this.store.get(e.id);i&&(i.sessionId=r.id,i.sessionName=r.name,i.harnessSessionId=r.harnessSessionId,i.route=r.route??i.route,i.updatedAt=Date.now(),i.status==="waiting_for_session"&&(i.status="running"),this.store.upsert(i),this.notifyIterationStatus(i,`\u{1F504} [${i.name}] Coding turn complete`,r),this.scheduleTaskEvaluation(e.id,"turnEnd",r.id))};r.on("statusChange",n),r.on("turnEnd",o),this.observerDisposers.set(r.id,()=>{r.off?.("statusChange",n),r.off?.("turnEnd",o),r.removeListener?.("statusChange",n),r.removeListener?.("turnEnd",o)})}scheduleTaskEvaluation(e,r,n){if(!this.started)return;let o=this.scheduledEvaluations.get(e);if(o){!o.sessionId&&n&&(o.sessionId=n);return}let i={timer:setTimeout(()=>{this.scheduledEvaluations.delete(e),this.evaluateTask(e,r,i.sessionId).catch(a=>{console.warn(`[GoalController] evaluateTask error (${r}): ${ln(a)}`)})},0),sessionId:n};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 r=this.observerDisposers.get(e);r&&(this.observerDisposers.delete(e),r())}markTaskFailed(e,r){e.status="failed",e.failureReason=Go(r,Tp),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u274C [${e.name}] Goal task failed
136
+ ${br(e,o)}`;this.notify(e,i,"goal-task-progress")}setTaskRunningWithSession(e,r){e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId,e.route=r.route??e.route,e.status="running",e.waitingForUserReason=void 0,e.updatedAt=Date.now(),this.store.upsert(e)}attachSessionObservers(e,r){if(this.observerDisposers.has(r.id))return;let n=(i,a)=>{(a==="completed"||a==="failed"||a==="killed")&&(this.removeSessionObserver(r.id),this.scheduleTaskEvaluation(e.id,`status:${a}`,r.id))},o=()=>{let i=this.store.get(e.id);i&&(i.sessionId=r.id,i.sessionName=r.name,i.harnessSessionId=r.harnessSessionId,i.route=r.route??i.route,i.updatedAt=Date.now(),i.status==="waiting_for_session"&&(i.status="running"),this.store.upsert(i),this.notifyIterationStatus(i,`\u{1F504} [${i.name}] Coding turn complete`,r),this.scheduleTaskEvaluation(e.id,"turnEnd",r.id))};r.on("statusChange",n),r.on("turnEnd",o),this.observerDisposers.set(r.id,()=>{r.off?.("statusChange",n),r.off?.("turnEnd",o),r.removeListener?.("statusChange",n),r.removeListener?.("turnEnd",o)})}scheduleTaskEvaluation(e,r,n){if(!this.started)return;let o=this.scheduledEvaluations.get(e);if(o){!o.sessionId&&n&&(o.sessionId=n);return}let i={timer:setTimeout(()=>{this.scheduledEvaluations.delete(e),this.evaluateTask(e,r,i.sessionId).catch(a=>{console.warn(`[GoalController] evaluateTask error (${r}): ${ln(a)}`)})},0),sessionId:n};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 r=this.observerDisposers.get(e);r&&(this.observerDisposers.delete(e),r())}markTaskFailed(e,r){e.status="failed",e.failureReason=zo(r,Op),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u274C [${e.name}] Goal task failed
137
137
 
138
138
  ${e.failureReason}`,"goal-task-failed")}markTaskFailedWaitingForUser(e,r){this.markTaskFailed(e,`Goal task was waiting for user input and cannot continue autonomously: ${r}`)}markTaskSucceeded(e,r){e.status="succeeded",e.lastVerifierSummary=r,e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u2705 [${e.name}] Goal task succeeded
139
139
 
140
- ${r}`,"goal-task-succeeded")}markTaskStopped(e,r){e.status="stopped",e.failureReason=Go(r,Tp),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u26D4 [${e.name}] Goal task stopped
140
+ ${r}`,"goal-task-succeeded")}markTaskStopped(e,r){e.status="stopped",e.failureReason=zo(r,Op),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u26D4 [${e.name}] Goal task stopped
141
141
 
142
142
  ${e.failureReason}`,"goal-task-stopped")}async handleRunningSession(e,r){if(r.pendingPlanApproval){let a=await Et(this.sessionManager,{session:r.id,message:"Approved. Implement the plan.",approve:!0,userInitiated:!1});a.isError&&this.markTaskFailed(e,a.text);return}if(!r.pendingInputState){this.setTaskRunningWithSession(e,r);return}let n=r.getOutput(30).join(`
143
- `),o=Mf(n);if(!o){this.markTaskFailedWaitingForUser(e,Tr(n,24)||"The session is waiting for user input.");return}let i=await Et(this.sessionManager,{session:r.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,r,n){try{let o=await this.resumeTaskSession(e,n,r);this.setTaskRunningWithSession(e,o),this.notifyIterationStatus(e,`\u{1F504} [${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: ${ln(o)}`)}}async handleTerminalSession(e,r){if(r.status==="failed"){this.markTaskFailed(e,vA(r));return}if(r.status==="killed"&&r.killReason==="user"){this.markTaskStopped(e,"Stopped by user.");return}if(r.status==="killed"&&r.killReason==="idle-timeout"){let i=r.getOutput(60).join(`
144
- `);if(r.pendingPlanApproval){let a=await Et(this.sessionManager,{session:r.id,message:"Approved. Implement the plan.",approve:!0,userInitiated:!1});if(a.isError){this.markTaskFailed(e,a.text);return}let u=this.sessionManager.resolve(r.id);if(!u){this.markTaskFailed(e,"Failed to resolve the resumed goal task session after idle timeout plan approval.");return}this.attachSessionObservers(e,u),this.setTaskRunningWithSession(e,u),this.notifyIterationStatus(e,`\u{1F504} [${e.name}] Goal task resumed after idle timeout`,u),this.scheduleTaskEvaluation(e.id,"idle-timeout-plan-resume",u.id);return}if(r.pendingInputState){let a=Mf(i);if(!a){this.markTaskFailed(e,`Goal task was waiting for user input and cannot continue autonomously: ${Tr(i,24)||"The goal task hit idle timeout while waiting for user input."}`);return}await this.resumeAfterIdleTimeout(e,r,["The previous session hit idle timeout while waiting for a response.",`Use this response and continue the goal: ${a}`].join(`
143
+ `),o=Bf(n);if(!o){this.markTaskFailedWaitingForUser(e,Tr(n,24)||"The session is waiting for user input.");return}let i=await Et(this.sessionManager,{session:r.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,r,n){try{let o=await this.resumeTaskSession(e,n,r);this.setTaskRunningWithSession(e,o),this.notifyIterationStatus(e,`\u{1F504} [${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: ${ln(o)}`)}}async handleTerminalSession(e,r){if(r.status==="failed"){this.markTaskFailed(e,LA(r));return}if(r.status==="killed"&&r.killReason==="user"){this.markTaskStopped(e,"Stopped by user.");return}if(r.status==="killed"&&r.killReason==="idle-timeout"){let i=r.getOutput(60).join(`
144
+ `);if(r.pendingPlanApproval){let a=await Et(this.sessionManager,{session:r.id,message:"Approved. Implement the plan.",approve:!0,userInitiated:!1});if(a.isError){this.markTaskFailed(e,a.text);return}let u=this.sessionManager.resolve(r.id);if(!u){this.markTaskFailed(e,"Failed to resolve the resumed goal task session after idle timeout plan approval.");return}this.attachSessionObservers(e,u),this.setTaskRunningWithSession(e,u),this.notifyIterationStatus(e,`\u{1F504} [${e.name}] Goal task resumed after idle timeout`,u),this.scheduleTaskEvaluation(e.id,"idle-timeout-plan-resume",u.id);return}if(r.pendingInputState){let a=Bf(i);if(!a){this.markTaskFailed(e,`Goal task was waiting for user input and cannot continue autonomously: ${Tr(i,24)||"The goal task hit idle timeout while waiting for user input."}`);return}await this.resumeAfterIdleTimeout(e,r,["The previous session hit idle timeout while waiting for a response.",`Use this response and continue the goal: ${a}`].join(`
145
145
 
146
- `));return}await this.resumeAfterIdleTimeout(e,r,Of(e));return}if(r.status==="killed"&&r.killReason!=="done"){this.markTaskFailed(e,`Underlying session was killed (${r.killReason}).`);return}if(e.loopMode==="ralph"){let i=r.getOutput(200).join(`
147
- `),a=Cf(e.completionPromise);if(PA(i,a)){if(e.verifierCommands.length===0){this.markTaskSucceeded(e,`Completion promise "${a}" detected in agent output.`);return}let l=await this.runVerifiers(e);if(e.lastVerifierSummary=l.summary,e.updatedAt=Date.now(),l.status==="pass"){this.markTaskSucceeded(e,[`Completion promise "${a}" detected.`,l.summary].join(`
146
+ `));return}await this.resumeAfterIdleTimeout(e,r,Uf(e));return}if(r.status==="killed"&&r.killReason!=="done"){this.markTaskFailed(e,`Underlying session was killed (${r.killReason}).`);return}if(e.loopMode==="ralph"){let i=r.getOutput(200).join(`
147
+ `),a=Ff(e.completionPromise);if(_A(i,a)){if(e.verifierCommands.length===0){this.markTaskSucceeded(e,`Completion promise "${a}" detected in agent output.`);return}let l=await this.runVerifiers(e);if(e.lastVerifierSummary=l.summary,e.updatedAt=Date.now(),l.status==="pass"){this.markTaskSucceeded(e,[`Completion promise "${a}" detected.`,l.summary].join(`
148
148
  `));return}if(e.lastVerifierFingerprint===l.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=l.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}).`,l.summary].join(`
149
- `));return}e.iteration+=1;let m=xA(e,l);try{let c=await this.resumeTaskSession(e,m,r);this.setTaskRunningWithSession(e,c),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Completion claimed but verifiers still failed`),this.scheduleTaskEvaluation(e.id,"ralph-verifier-resume",c.id)}catch(c){this.markTaskFailed(e,`Failed to resume the Ralph goal task after verifier failure: ${ln(c)}`)}return}let p=yA(i);if(e.lastVerifierFingerprint===p?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=p,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Completion promise "${a}" was not emitted before hitting the iteration budget (${e.maxIterations}).`,"Latest output:",Tr(i,20)||"(no output)"].join(`
150
- `));return}e.iteration+=1;let d=IA(e,i);try{let l=await this.resumeTaskSession(e,d,r);this.setTaskRunningWithSession(e,l),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Ralph iteration continued`),this.scheduleTaskEvaluation(e.id,"ralph-continue",l.id)}catch(l){this.markTaskFailed(e,`Failed to continue the Ralph goal task: ${ln(l)}`)}return}let n=await this.runVerifiers(e);if(e.lastVerifierSummary=n.summary,e.updatedAt=Date.now(),n.status==="pass"){this.markTaskSucceeded(e,n.summary);return}if(e.lastVerifierFingerprint===n.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=n.fingerprint,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Verifier did not pass before hitting the iteration budget (${e.maxIterations}).`,n.summary].join(`
151
- `));return}e.iteration+=1;let o=kA(e,n);try{let i=await this.resumeTaskSession(e,o,r);this.setTaskRunningWithSession(e,i),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Repair iteration started after verifier failure`),this.scheduleTaskEvaluation(e.id,"repair-resume",i.id)}catch(i){this.markTaskFailed(e,`Failed to resume the goal task: ${ln(i)}`)}}async evaluateTask(e,r,n){this.restorePromise&&await this.restorePromise;let o=this.store.get(e);o&&await this.reconcileTask(o,r,n)}async reconcileTask(e,r="manual",n){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)&&n?this.dirtyEvaluationSessionIds.set(e.id,n):this.dirtyEvaluationSessionIds.has(e.id)||this.dirtyEvaluationSessionIds.set(e.id,n);return}this.inFlight.add(e.id);try{if(n&&e.sessionId&&e.sessionId!==n){let i=this.sessionManager.resolve(n);if(i&&(i.status==="completed"||i.status==="failed"||i.status==="killed"))return}let o=n?this.sessionManager.resolve(n)??(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(Ef(e)){this.markTaskFailed(e,Ns());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,`${r}:dirty`,o)}}}}};ze();import{existsSync as TA,realpathSync as RA}from"fs";import{resolve as CA}from"path";function Ff(t){if(!t)return;let e=CA(t);try{if(TA(e))return RA.native(e)}catch{}return e}function Bs(t,e){return!t||!e?!1:Ff(t)===Ff(e)}Ee();ze();import{existsSync as EA}from"fs";Ee();Pt();function Nf(t){return t instanceof Error?t.message:String(t)}function $A(t){let e=t.worktreeStrategy??K.defaultWorktreeStrategy;return!!e&&e!=="off"&&tp(Mo({harnessName:t.harness??dt(),backendRef:t.backendRef}))}function MA(t,e,r,n){let o=["","You are working in a git worktree.",`Worktree path: ${r}`,`Branch: ${n}`,"",`IMPORTANT: ALL file edits must be made within this worktree at ${r}.`,`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" \u2192 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(`
152
- `);return(t??"")+o}function OA(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=ls(n.worktreePath);return n.workdir&&u&&Bs(n.workdir,u)?n.workdir:u??n.workdir}return n.workdir})();if(!t.worktreeStrategy&&n.worktreeStrategy&&(t.worktreeStrategy=n.worktreeStrategy),!t.planApproval&&n.planApproval&&(t.planApproval=n.planApproval),!n.worktreePath){let u=o&&Hi(Mo({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=Hi(Mo({persistedHarness:n.harness,backendRef:n.backendRef}))&&!!n.backendRef?.worktreePath;if(EA(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{cs(i);let u=up(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: ${Nf(u)}, using original workdir`),{actualWorkdir:i,originalWorkdir:i,clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom,failedResumeWorktreeRestore:!0}}}function qf(t,e,r){let{actualWorkdir:n,originalWorkdir:o,worktreePath:i,worktreeBranchName:a,clearedResumeSessionId:u,clearedResumeWorktreeFrom:p,restoredMissingNativeBackendWorktree:d,canCreateManagedWorktreeForResumeWithoutPersistedPath:l,failedResumeWorktreeRestore:m}=OA(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=$A(t),I=(!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&&!sp(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${h}" requires a git worktree, but "${o}" is not a git repository.`);if(I&&sp(o)){if(!Sc(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=up(o,e),n=i,a=ms(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: ${Nf(x)}`)}}else if(I)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?MA(t.systemPrompt,o,i,a):t.systemPrompt,worktreePath:i,worktreeBranchName:a,clearedResumeSessionId:u,clearedResumeWorktreeFrom:p,restoredMissingNativeBackendWorktree:d,failedResumeWorktreeRestore:m}}var Us=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,r){return qf(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 Ws=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(ye(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 _A=new Set(["starting","running"]),Ks=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),_A.has(i.status)&&(!n||i.startedAt>n.startedAt)&&(n=i));return n??o}};Ee();Ee();Pt();var js=class{constructor(e){this.deps=e}deps;async plan(e){let r=ye(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}};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 n=e.worktreeStrategy;if(!n||n==="off"||n==="manual")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let o=e.worktreePath,i=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,o),a=e.worktreeBranch;if(!i)return{kind:"notify",label:"worktree-missing-repo-dir",message:`\u26A0\uFE0F [${e.name}] Cannot determine the original repo for worktree ${o}. Manual inspection is required.`};if(!a)return{kind:"notify",label:"worktree-no-branch-name",message:`\u26A0\uFE0F [${e.name}] Cannot determine branch name for worktree ${o}. The worktree may have been removed or is in detached HEAD state. Manual cleanup may be needed.`};let u=e.worktreeBaseBranch??wr(i),p=this.deps.getWorktreeCompletionState(i,o,a,u);if(p==="no-change")return{kind:"no-change",repoDir:i,worktreePath:o,nativeBackendWorktree:lt(e)};if(p==="base-advanced")return{kind:"notify",label:"worktree-no-commits-ahead",message:`\u26A0\uFE0F [${e.name}] Auto-merge: branch '${a}' has no commits ahead of '${u}', but '${u}' has new commits \u2014 commits likely landed outside the worktree branch. Verify that commits were not made directly to '${u}' instead of the worktree branch. Worktree: ${o}`};if(p==="dirty-uncommitted")return{kind:"dirty-uncommitted",worktreePath:o,branchName:a,baseBranch:u};let d=sn(i,a,u);return d?{kind:"decision",strategy:n,repoDir:i,worktreePath:o,branchName:a,baseBranch:u,diffSummary:d,sessionRef:r??void 0}:(console.warn(`[SessionManager] Failed to get diff summary for ${a}, skipping merge-back`),{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}})}};function Cp(t,e){return{...e,baseBranch:e.baseBranch??t.worktreeBaseBranch,targetRepo:e.targetRepo??t.worktreePrTargetRepo,pushRemote:e.pushRemote??t.worktreePushRemote}}function Gs(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:Cp(t,{state:"pending_decision",updatedAt:r,notes:e.notes})};return e.clearResolverSessionId&&(n.autoMergeResolverSessionId=void 0),n}function Bf(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:Cp(t,{state:"merge_conflict_resolving",updatedAt:o,notes:n.notes})}}function Uf(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:Cp(t,{state:"merged",updatedAt:r,resolvedAt:n,resolutionSource:e.resolutionSource??"agent_merge"})};return e.clearResolverSessionId&&(o.autoMergeResolverSessionId=void 0),o}function DA(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 Wf="COMPLETION_FOLLOWUP_DELIVERED",Kf="COMPLETION_FOLLOWUP_SKIPPED";function Vs(t){let e=DA(t);return[`Requested permission mode: ${t.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${t.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${t.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function Vo(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 LA(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function FA(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToWorktreeTerminalOutcomes:!0}}function Ep(t){let{sessionId:e,canonicalStatusDetail:r,canonicalStatusDelivered:n=!0,hasOriginRouteBlock:o=!1}=t,i=o?["6. 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?7:6,u=o?8:7;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. Unless you are silently continuing an internal multi-phase pipeline or there is still no meaningful confirmed outcome to report, you must send the user a short factual completion summary for this completed session.","5. 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.`,...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 ${Wf}. If you are silently continuing an internal multi-phase pipeline or there is no meaningful confirmed outcome to report, finish with ${Kf}: <brief reason>. Otherwise do not use either marker and do not answer NO_REPLY.`]}function NA(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 $p(t){let{session:e,originThreadLine:r,preview:n}=t,o=!!r.trim(),i=`$${(e.costUsd??0).toFixed(2)}`,a=Ft(e.duration),u=LA(),p=d=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,...o?[r]:[],...Vs(e),"","Output preview:",n,"",...NA({contract:u,canonicalStatusDelivered:d}),"",...Ep({sessionId:e.id,canonicalStatusDelivered:d,hasOriginRouteBlock:o})].join(`
153
- `);return{userMessage:`\u2705 [${e.name}] Completed | ${i} | ${a}`,wakeMessageOnNotifySuccess:p(!0),wakeMessageOnNotifyFailed:p(!1),followupContract:u}}function Hn(t){let e=FA(),r=!!t.originThreadLine.trim(),n=(t.detailLines??[]).map(o=>o.trim()).filter(o=>o.length>0);return["Worktree follow-through outcome recorded.",`Name: ${t.sessionName??"unknown"} | ID: ${t.sessionId}`,...r?[t.originThreadLine]:[],"","Canonical outcome status:",t.outcomeLine,...n.length>0?["","Outcome details:",...n.map(o=>`- ${o}`)]:[],"","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. Send the user one short factual outcome summary grounded in the full output plus the canonical outcome status above.","3. If full output is unavailable or not meaningful, say only what is proven by the merge/PR facts above; do not invent task details.","4. Mention blockers such as push failure when present; do not describe a local-only merge as pushed.",...r?["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."]:[],`${r?6:5}. Do NOT repeat only the plugin status line; keep the follow-up brief, concrete, and non-duplicative.`,`${r?7:6}. After the visible follow-up summary has actually been sent to the user or origin route, finish this wake turn with ${Wf}. If there is no meaningful confirmed outcome to report, finish with ${Kf}: <brief reason>. Otherwise do not use either marker and do not answer NO_REPLY.`].join(`
154
- `)}function Mp(t){let{session:e,originThreadLine:r,errorSummary:n,preview:o,worktreeAutoCleaned:i,failedButtons:a}=t,u=o.trim()?["","Output preview:",o]:[],p=i?["","Note: Worktree and branch were auto-removed (zero cost, startup failure)."]:[],d=`$${(e.costUsd??0).toFixed(2)}`,l=Ft(e.duration);return{userMessage:[`\u274C [${e.name}] Failed | ${d} | ${l}`,` \u26A0\uFE0F ${n}`].join(`
155
- `),wakeMessage:["Coding agent session failed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,r,...Vs(e),...e.harnessSessionId?[`Backend conversation ID: ${e.harnessSessionId}`]:[],"","Failure summary:",n,...u,...p,"","[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(`
156
- `),buttons:a}}function Op(t){let{session:e,originThreadLine:r,preview:n}=t,o=`$${(e.costUsd??0).toFixed(2)}`;return{userMessage:`\u23F8\uFE0F [${e.name}] Turn completed | ${o}`,wakeMessage:["Coding agent session turn ended.",`Name: ${e.name}`,`ID: ${e.id}`,`Status: ${e.status}`,`Lifecycle: ${e.lifecycle}`,"","Last output (~20 lines):",n,...r?["",r]:[]].join(`
157
- `)}}function _p(t){let{sessionName:e,sessionId:r,branchName:n,baseBranch:o,promptSnippet:i,commitLines:a,moreNote:u,originThreadLine:p,diffSummary:d}=t,l=!!p?.trim();return[`[DELEGATED WORKTREE DECISION] Session "${e}" completed with changes.`,"",`Session ID: ${r}`,`Branch: ${n} \u2192 ${o}`,`Commits: ${d.commits} | Files: ${d.filesChanged} | +${d.insertions} / -${d.deletions}`,...l?[p]:[],"",...a,...u?[u]:[],"","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, message the user with the summary and ask for confirmation before calling agent_pr().","- If scope or risk is unclear, message the user and ask for guidance.","- Never call agent_pr() autonomously in delegate mode.","- After deciding, notify the user briefly with what you did and why.",...l?["- 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(`
158
- `)}function Dp(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(`
159
- `)}function Lp(t){let{sessionName:e,sessionId:r,cleanupSummary:n,preview:o,originThreadLine:i,requestedPermissionMode:a,currentPermissionMode:u,approvalExecutionState:p,approvalState:d,planApproval:l,approvalPromptStatus:m,approvalPromptMessageKind:c,approvalPromptDeliveredAt:h}=t,y=o.trim()?["","Output preview:",o]:[],S=!!i?.trim();return["Coding agent session completed with no repository changes.",`Name: ${e} | ID: ${r}`,`Worktree outcome: ${n}`,...S?[i]:[],...Vs({requestedPermissionMode:a,currentPermissionMode:u,approvalExecutionState:p,approvalState:d,planApproval:l,approvalPromptStatus:m,approvalPromptMessageKind:c,approvalPromptDeliveredAt:h}),...y,"",...Ep({sessionId:r,canonicalStatusDetail:"The plugin already sent the canonical completion status to the user, including that no repo changes were kept.",hasOriginRouteBlock:S})].join(`
160
- `)}function Fp(t){let e=[],r=t.changedFiles.slice(0,3).map(o=>`\`${o}\``);if(r.length>0){let o=t.changedFiles.length-r.length;e.push(o>0?`Touches ${r.join(", ")} and ${o} more file${o===1?"":"s"}`:`Touches ${r.join(", ")}`)}let n=[...new Set(t.commitMessages.map(o=>o.message.trim()).filter(Boolean))].slice(0,2);return n.length>0&&e.push(`Recent work: ${n.join("; ")}`),e}var Vf=3200,Np=3e3,qA=2400,BA=120,UA=5,WA=280,jf=1400,Gf="- Additional plan details omitted for brevity.";function Hf(t){return t.replace(/^#{1,6}\s+/,"").replace(/^[-*+]\s+/,"").replace(/^\d+[.)]\s+/,"").replace(/^`([^`]+)`$/,"$1").trim()}function KA(t){return t.split(`
161
- `).map(e=>e.trim()).filter(Boolean).map(Hf).map(e=>Je(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 jA(t){return t.split(`
162
- `).map(e=>e.trim()).filter(Boolean).map(Hf).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 qp(t){let e=KA(t);return e.length===0?`Review summary:
149
+ `));return}e.iteration+=1;let m=OA(e,l);try{let c=await this.resumeTaskSession(e,m,r);this.setTaskRunningWithSession(e,c),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Completion claimed but verifiers still failed`),this.scheduleTaskEvaluation(e.id,"ralph-verifier-resume",c.id)}catch(c){this.markTaskFailed(e,`Failed to resume the Ralph goal task after verifier failure: ${ln(c)}`)}return}let p=CA(i);if(e.lastVerifierFingerprint===p?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=p,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Completion promise "${a}" was not emitted before hitting the iteration budget (${e.maxIterations}).`,"Latest output:",Tr(i,20)||"(no output)"].join(`
150
+ `));return}e.iteration+=1;let d=MA(e,i);try{let l=await this.resumeTaskSession(e,d,r);this.setTaskRunningWithSession(e,l),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Ralph iteration continued`),this.scheduleTaskEvaluation(e.id,"ralph-continue",l.id)}catch(l){this.markTaskFailed(e,`Failed to continue the Ralph goal task: ${ln(l)}`)}return}let n=await this.runVerifiers(e);if(e.lastVerifierSummary=n.summary,e.updatedAt=Date.now(),n.status==="pass"){this.markTaskSucceeded(e,n.summary);return}if(e.lastVerifierFingerprint===n.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=n.fingerprint,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Verifier did not pass before hitting the iteration budget (${e.maxIterations}).`,n.summary].join(`
151
+ `));return}e.iteration+=1;let o=$A(e,n);try{let i=await this.resumeTaskSession(e,o,r);this.setTaskRunningWithSession(e,i),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Repair iteration started after verifier failure`),this.scheduleTaskEvaluation(e.id,"repair-resume",i.id)}catch(i){this.markTaskFailed(e,`Failed to resume the goal task: ${ln(i)}`)}}async evaluateTask(e,r,n){this.restorePromise&&await this.restorePromise;let o=this.store.get(e);o&&await this.reconcileTask(o,r,n)}async reconcileTask(e,r="manual",n){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)&&n?this.dirtyEvaluationSessionIds.set(e.id,n):this.dirtyEvaluationSessionIds.has(e.id)||this.dirtyEvaluationSessionIds.set(e.id,n);return}this.inFlight.add(e.id);try{if(n&&e.sessionId&&e.sessionId!==n){let i=this.sessionManager.resolve(n);if(i&&(i.status==="completed"||i.status==="failed"||i.status==="killed"))return}let o=n?this.sessionManager.resolve(n)??(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(Nf(e)){this.markTaskFailed(e,Vs());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,`${r}:dirty`,o)}}}}};ze();import{existsSync as qA,realpathSync as BA}from"fs";import{resolve as UA}from"path";function Gf(t){if(!t)return;let e=UA(t);try{if(qA(e))return BA.native(e)}catch{}return e}function zs(t,e){return!t||!e?!1:Gf(t)===Gf(e)}Ee();ze();import{existsSync as WA}from"fs";Ee();Pt();function Vf(t){return t instanceof Error?t.message:String(t)}function KA(t){let e=t.worktreeStrategy??K.defaultWorktreeStrategy;return!!e&&e!=="off"&&up(Oo({harnessName:t.harness??dt(),backendRef:t.backendRef}))}function jA(t,e,r,n){let o=["","You are working in a git worktree.",`Worktree path: ${r}`,`Branch: ${n}`,"",`IMPORTANT: ALL file edits must be made within this worktree at ${r}.`,`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" \u2192 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(`
152
+ `);return(t??"")+o}function GA(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=fs(n.worktreePath);return n.workdir&&u&&zs(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&&Ji(Oo({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=Ji(Oo({persistedHarness:n.harness,backendRef:n.backendRef}))&&!!n.backendRef?.worktreePath;if(WA(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{hs(i);let u=gp(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: ${Vf(u)}, using original workdir`),{actualWorkdir:i,originalWorkdir:i,clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom,failedResumeWorktreeRestore:!0}}}function Hf(t,e,r){let{actualWorkdir:n,originalWorkdir:o,worktreePath:i,worktreeBranchName:a,clearedResumeSessionId:u,clearedResumeWorktreeFrom:p,restoredMissingNativeBackendWorktree:d,canCreateManagedWorktreeForResumeWithoutPersistedPath:l,failedResumeWorktreeRestore:m}=GA(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=KA(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&&!cp(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${h}" requires a git worktree, but "${o}" is not a git repository.`);if(S&&cp(o)){if(!vc(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=gp(o,e),n=i,a=gs(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: ${Vf(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?jA(t.systemPrompt,o,i,a):t.systemPrompt,worktreePath:i,worktreeBranchName:a,clearedResumeSessionId:u,clearedResumeWorktreeFrom:p,restoredMissingNativeBackendWorktree:d,failedResumeWorktreeRestore:m}}var Js=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,r){return Hf(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 Qs=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(ye(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 VA=new Set(["starting","running"]),Ys=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),VA.has(i.status)&&(!n||i.startedAt>n.startedAt)&&(n=i));return n??o}};Ee();Ee();Pt();var zf=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]),Zs=class{constructor(e){this.deps=e}deps;async plan(e){let r=ye(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=zf.has(e.worktreeState)?e.worktreeState:e.worktreeLifecycle?.state&&zf.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}})}};Ns();function HA(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 Dp="COMPLETION_FOLLOWUP_DELIVERED",Lp="COMPLETION_FOLLOWUP_SKIPPED";function Xs(t){let e=HA(t);return[`Requested permission mode: ${t.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${t.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${t.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function Jo(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 zA(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function JA(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToWorktreeTerminalOutcomes:!0}}function QA(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToGoalTaskCompletions:!0}}function Fp(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 ${Dp}. Use ${Lp}: <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 YA(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 Np(t){let{session:e,originThreadLine:r,preview:n}=t,o=!!r.trim(),i=`$${(e.costUsd??0).toFixed(2)}`,a=Ft(e.duration),u=zA(),p=d=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,...o?[r]:[],...Xs(e),"","Output preview:",n,"",...YA({contract:u,canonicalStatusDelivered:d}),"",...Fp({sessionId:e.id,canonicalStatusDelivered:d,hasOriginRouteBlock:o})].join(`
153
+ `);return{userMessage:`\u2705 [${e.name}] Completed | ${i} | ${a}`,wakeMessageOnNotifySuccess:p(!0),wakeMessageOnNotifyFailed:p(!1),followupContract:u}}function Hn(t){let e=JA(),r=!!t.originThreadLine.trim(),n=(t.detailLines??[]).map(o=>o.trim()).filter(o=>o.length>0);return["Worktree follow-through outcome recorded.",`Name: ${t.sessionName??"unknown"} | ID: ${t.sessionId}`,...r?[t.originThreadLine]:[],"","Canonical outcome status:",t.outcomeLine,...n.length>0?["","Outcome details:",...n.map(o=>`- ${o}`)]:[],"","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. If the visible result is only the plugin's terse status line, use the full output plus the canonical outcome status 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.",...r?["6. 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."]:[],`${r?7:6}. Do NOT repeat only the plugin status line; keep the follow-up brief, concrete, and non-duplicative. Send at most one orchestrator-owned human summary for this terminal/worktree outcome.`,`${r?8:7}. After the visible follow-up summary has actually been sent to the user or origin route, finish this wake turn with ${Dp}. Use ${Lp}: <brief reason> only for valid skip cases: 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.`].join(`
154
+ `)}function qp(t){let e=QA(),r=!!t.originThreadLine.trim();return["Goal task succeeded.",`Task: ${t.taskName}`,`Name: ${t.sessionName??t.taskName} | ID: ${t.sessionId}`,...r?[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. Send the user one short factual completion summary grounded in the full output plus the canonical goal status above.","3. If full output is unavailable or not meaningful, say only what is proven by the goal status above; do not invent task details.",...r?["4. 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."]:[],`${r?5:4}. Do NOT repeat only the plugin status line; keep the follow-up brief, concrete, and non-duplicative.`,`${r?6:5}. After the visible follow-up summary has actually been sent to the user or origin route, finish this wake turn with ${Dp}. If there is no meaningful confirmed outcome to report, finish with ${Lp}: <brief reason>. Otherwise do not use either marker and do not answer NO_REPLY.`].join(`
155
+ `)}function Bp(t){let{session:e,originThreadLine:r,errorSummary:n,preview:o,worktreeAutoCleaned:i,failedButtons:a}=t,u=o.trim()?["","Output preview:",o]:[],p=i?["","Note: Worktree and branch were auto-removed (zero cost, startup failure)."]:[],d=`$${(e.costUsd??0).toFixed(2)}`,l=Ft(e.duration);return{userMessage:[`\u274C [${e.name}] Failed | ${d} | ${l}`,` \u26A0\uFE0F ${n}`].join(`
156
+ `),wakeMessage:["Coding agent session failed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,r,...Xs(e),...e.harnessSessionId?[`Backend conversation ID: ${e.harnessSessionId}`]:[],"","Failure summary:",n,...u,...p,"","[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(`
157
+ `),buttons:a}}function Up(t){let{session:e,originThreadLine:r,preview:n}=t,o=`$${(e.costUsd??0).toFixed(2)}`;return{userMessage:`\u23F8\uFE0F [${e.name}] Turn completed | ${o}`,wakeMessage:["Coding agent session turn ended.",`Name: ${e.name}`,`ID: ${e.id}`,`Status: ${e.status}`,`Lifecycle: ${e.lifecycle}`,"","Last output (~20 lines):",n,...r?["",r]:[]].join(`
158
+ `)}}function Wp(t){let{sessionName:e,sessionId:r,branchName:n,baseBranch:o,promptSnippet:i,commitLines:a,moreNote:u,originThreadLine:p,diffSummary:d}=t,l=!!p?.trim();return[`[DELEGATED WORKTREE DECISION] Session "${e}" completed with changes.`,"",`Session ID: ${r}`,`Branch: ${n} \u2192 ${o}`,`Commits: ${d.commits} | Files: ${d.filesChanged} | +${d.insertions} / -${d.deletions}`,...l?[p]:[],"",...a,...u?[u]:[],"","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, message the user with the summary and ask for confirmation before calling agent_pr().","- If scope or risk is unclear, message the user and ask for guidance.","- Never call agent_pr() autonomously in delegate mode.","- After deciding, notify the user briefly with what you did and why.",...l?["- 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(`
159
+ `)}function Kp(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(`
160
+ `)}function jp(t){let{sessionName:e,sessionId:r,cleanupSummary:n,preview:o,originThreadLine:i,requestedPermissionMode:a,currentPermissionMode:u,approvalExecutionState:p,approvalState:d,planApproval:l,approvalPromptStatus:m,approvalPromptMessageKind:c,approvalPromptDeliveredAt:h}=t,y=o.trim()?["","Output preview:",o]:[],k=!!i?.trim();return["Coding agent session completed with no repository changes.",`Name: ${e} | ID: ${r}`,`Worktree outcome: ${n}`,...k?[i]:[],...Xs({requestedPermissionMode:a,currentPermissionMode:u,approvalExecutionState:p,approvalState:d,planApproval:l,approvalPromptStatus:m,approvalPromptMessageKind:c,approvalPromptDeliveredAt:h}),...y,"",...Fp({sessionId:r,canonicalStatusDetail:"The plugin already sent the canonical completion status to the user, including that no repo changes were kept.",hasOriginRouteBlock:k})].join(`
161
+ `)}var Yf=3200,Gp=3e3,ZA=2400,XA=120,eT=5,tT=280,Jf=1400,Qf="- Additional plan details omitted for brevity.";function Zf(t){return t.replace(/^#{1,6}\s+/,"").replace(/^[-*+]\s+/,"").replace(/^\d+[.)]\s+/,"").replace(/^`([^`]+)`$/,"$1").trim()}function rT(t){return t.split(`
162
+ `).map(e=>e.trim()).filter(Boolean).map(Zf).map(e=>Je(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 nT(t){return t.split(`
163
+ `).map(e=>e.trim()).filter(Boolean).map(Zf).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 Vp(t){let e=rT(t);return e.length===0?`Review summary:
163
164
  - Plan details are available in the full session output.`:["Review summary:",...e.slice(0,6).map(r=>`- ${r}`)].join(`
164
- `)}function GA(t){let e=[],r=!1;for(let o of t){let i=o.replace(/\s+/g," ").trim();if(!i)continue;let a=Je(i,WA);a.length<i.length&&(r=!0);let u=`- ${a}`;if(e.length>=UA||[...e,u].join(`
165
- `).length>jf){r=!0;break}e.push(u)}if(e.length===0)return["- Plan details are available in the full session output."];if(!r)return e;let n=[...e];for(;n.length>0&&[...n,Gf].join(`
166
- `).length>jf;)n.pop();return[...n,Gf]}function Bp(t){return GA(jA(t)).join(`
167
- `)}function VA(t,e){let r=[],n=t.trim();for(;n.length>e;){let o=n.lastIndexOf(" ",e);o<Math.floor(e*.6)&&(o=e),r.push(n.slice(0,o).trimEnd()),n=n.slice(o).trimStart()}return n.length>0&&r.push(n),r}function HA(t,e){let r=t.split(`
168
- `),n=[],o="",i=()=>{o.trim().length>0&&(n.push(o.trimEnd()),o="")};for(let a of r){if(a.length>e){i();for(let p of VA(a,e))n.push(p);continue}let u=o.length>0?`${o}
169
- ${a}`:a;if(u.length>e){i(),o=a;continue}o=u}return i(),n}function zf(t){return Je(t.trim(),BA)}function Jf(t,e){return e?t?`
165
+ `)}function oT(t){let e=[],r=!1;for(let o of t){let i=o.replace(/\s+/g," ").trim();if(!i)continue;let a=Je(i,tT);a.length<i.length&&(r=!0);let u=`- ${a}`;if(e.length>=eT||[...e,u].join(`
166
+ `).length>Jf){r=!0;break}e.push(u)}if(e.length===0)return["- Plan details are available in the full session output."];if(!r)return e;let n=[...e];for(;n.length>0&&[...n,Qf].join(`
167
+ `).length>Jf;)n.pop();return[...n,Qf]}function Hp(t){return oT(nT(t)).join(`
168
+ `)}function iT(t,e){let r=[],n=t.trim();for(;n.length>e;){let o=n.lastIndexOf(" ",e);o<Math.floor(e*.6)&&(o=e),r.push(n.slice(0,o).trimEnd()),n=n.slice(o).trimStart()}return n.length>0&&r.push(n),r}function sT(t,e){let r=t.split(`
169
+ `),n=[],o="",i=()=>{o.trim().length>0&&(n.push(o.trimEnd()),o="")};for(let a of r){if(a.length>e){i();for(let p of iT(a,e))n.push(p);continue}let u=o.length>0?`${o}
170
+ ${a}`:a;if(u.length>e){i(),o=a;continue}o=u}return i(),n}function Xf(t){return Je(t.trim(),XA)}function eg(t,e){return e?t?`
170
171
 
171
172
  Choose Approve, Revise, or Reject below.`:`
172
173
 
173
174
  Approval is still pending for this plan version.`:`
174
175
 
175
- Continued in next message.`}function zA(t){let{sessionName:e,actionableVersion:r,fullPlanText:n,hasButtons:o}=t,i=`\u{1F4CB} [${e}] Plan v${r??"?"} ready for approval:`,a=`
176
+ Continued in next message.`}function aT(t){let{sessionName:e,actionableVersion:r,fullPlanText:n,hasButtons:o}=t,i=`\u{1F4CB} [${e}] Plan v${r??"?"} ready for approval:`,a=`
176
177
 
177
178
  Full plan (truncated):
178
- `,u=Jf(o,!0),p=Math.max(0,Np-i.length-a.length-u.length);return`${i}${a}${Je(n,p)}${u}`}function JA(t){let{sessionName:e,actionableVersion:r,fullPlanText:n,hasButtons:o}=t,i=zf(e),a=qA;for(;a>0;){let u=HA(n,a),p=u.map((m,c)=>{let h=u.length,y=[`\u{1F4CB} [${i}] Plan v${r??"?"} ready for approval (${c+1}/${h}):`,"",c===0?"Full plan:":""].filter(Boolean).join(`
179
- `),S=Jf(o,c===h-1);return`${y}
180
- ${m}${S}`}),d=p.reduce((m,c)=>Math.max(m,c.length),0);if(d<=Np)return p;let l=d-Np;a-=Math.max(l,50)}return[zA({sessionName:i,actionableVersion:r,fullPlanText:n,hasButtons:o})]}function Up(t){let{preview:e,artifact:r}=t,n=r?.markdown?.trim();return n&&n.length<=Vf?`Full plan:
181
- ${n}`:qp(n||e)}function Qf(t){let{sessionName:e,actionableVersion:r,preview:n,artifact:o,hasButtons:i}=t,a=o?.markdown?.trim(),u=zf(e);if(a){let d=`\u{1F4CB} [${u}] Plan v${r??"?"} ready for approval:
179
+ `,u=eg(o,!0),p=Math.max(0,Gp-i.length-a.length-u.length);return`${i}${a}${Je(n,p)}${u}`}function uT(t){let{sessionName:e,actionableVersion:r,fullPlanText:n,hasButtons:o}=t,i=Xf(e),a=ZA;for(;a>0;){let u=sT(n,a),p=u.map((m,c)=>{let h=u.length,y=[`\u{1F4CB} [${i}] Plan v${r??"?"} ready for approval (${c+1}/${h}):`,"",c===0?"Full plan:":""].filter(Boolean).join(`
180
+ `),k=eg(o,c===h-1);return`${y}
181
+ ${m}${k}`}),d=p.reduce((m,c)=>Math.max(m,c.length),0);if(d<=Gp)return p;let l=d-Gp;a-=Math.max(l,50)}return[aT({sessionName:i,actionableVersion:r,fullPlanText:n,hasButtons:o})]}function zp(t){let{preview:e,artifact:r}=t,n=r?.markdown?.trim();return n&&n.length<=Yf?`Full plan:
182
+ ${n}`:Vp(n||e)}function tg(t){let{sessionName:e,actionableVersion:r,preview:n,artifact:o,hasButtons:i}=t,a=o?.markdown?.trim(),u=Xf(e);if(a){let d=`\u{1F4CB} [${u}] Plan v${r??"?"} ready for approval:
182
183
 
183
184
  Full plan:
184
185
  ${a}
185
186
 
186
- ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`;return d.length<=Vf?{displayMode:"single-full-plan",userMessages:[d],reviewSummary:`Full plan:
187
- ${a}`}:{displayMode:"chunked-full-plan",userMessages:JA({sessionName:e,actionableVersion:r,fullPlanText:a,hasButtons:i}),reviewSummary:qp(a)}}let p=qp(n);return{displayMode:"summary",userMessages:[`\u{1F4CB} [${u}] Plan v${r??"?"} ready for approval:
187
+ ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`;return d.length<=Yf?{displayMode:"single-full-plan",userMessages:[d],reviewSummary:`Full plan:
188
+ ${a}`}:{displayMode:"chunked-full-plan",userMessages:uT({sessionName:e,actionableVersion:r,fullPlanText:a,hasButtons:i}),reviewSummary:Vp(a)}}let p=Vp(n);return{displayMode:"summary",userMessages:[`\u{1F4CB} [${u}] Plan v${r??"?"} ready for approval:
188
189
 
189
190
  ${p}
190
191
 
191
- ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`],reviewSummary:p}}var Yf=700;function QA(t){let e=t?.trim();return e||void 0}function YA(t,e){let r=e?.trim();if(!r)return;if(!t)return r;let n=t.trim(),o=r.split(`
192
+ ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`],reviewSummary:p}}var rg=700;function pT(t){let e=t?.trim();return e||void 0}function dT(t,e){let r=e?.trim();if(!r)return;if(!t)return r;let n=t.trim(),o=r.split(`
192
193
  `).map(u=>u.trimEnd());for(;o.length>0&&!o[o.length-1]?.trim();)o.pop();for(;o.length>0&&o[o.length-1]?.trim()===n;)o.pop();let a=o.filter((u,p,d)=>{let l=u.trim();return!l||l!==n?!0:!d.some((c,h)=>h!==p&&c.trim().length>0&&c.trim()!==n)}).join(`
193
- `).trim();if(!(!a||a===n))return a.length>Yf?Zi(a,Yf):a}function ZA(t){let e=QA(t.questionText)??"The session is waiting for your reply.",r=YA(e,t.contextPreview);return r?[`\u2753 [${t.sessionName}] Question waiting for reply:`,"","Question:",e,"","Recent context:",r].join(`
194
+ `).trim();if(!(!a||a===n))return a.length>rg?es(a,rg):a}function lT(t){let e=pT(t.questionText)??"The session is waiting for your reply.",r=dT(e,t.contextPreview);return r?[`\u2753 [${t.sessionName}] Question waiting for reply:`,"","Question:",e,"","Recent context:",r].join(`
194
195
  `):`\u2753 [${t.sessionName}] Question waiting for reply:
195
196
 
196
- ${e}`}function XA(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function Ho(t){let{session:e,summary:r}=t,n=e.actionablePlanDecisionVersion??e.planDecisionVersion;return[`\u{1F4CB} [${e.name}] Plan v${n??"?"} 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:","",r].join(`
197
- `)}function Wp(t){let{session:e,preview:r,questionText:n,questionContextPreview:o,planArtifact:i,originThreadLine:a,planApprovalMode:u,planApprovalButtons:p,questionButtons:d}=t,l=e.pendingPlanApproval,m=e.actionablePlanDecisionVersion??e.planDecisionVersion,c=XA(e,m),h=u??"delegate",y=l&&h==="ask"&&!c?Qf({sessionName:e.name,actionableVersion:m,preview:r,artifact:i,hasButtons:!!p}):void 0,S=l?y?.reviewSummary??Up({preview:r,artifact:i}):void 0,I=l?y&&y.userMessages.length===1?y.userMessages[0]:void 0:ZA({sessionName:e.name,questionText:n??r,contextPreview:o}),x=l&&y&&y.userMessages.length>1?y.userMessages.map(($,C,Ie)=>({text:$,buttons:C===Ie.length-1?p:void 0})):void 0;if(l){let $=h,C="Permission mode: plan \u2192 will switch to bypassPermissions on approval";return $==="delegate"?{label:"plan-approval",userMessage:I,userMessages:x,planReviewSummary:S,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${m??"?"}`,a,C,"","\u26A0\uFE0F YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","\u2501\u2501\u2501 STEP 1 (MANDATORY): Read the full plan \u2501\u2501\u2501",`Call agent_output(session='${e.id}', full=true) to read the FULL plan output.`,"The preview below is truncated \u2014 you MUST read the full output before making any decision.","","Preview (truncated):",r,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Review privately \u2501\u2501\u2501","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.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","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 \u2014 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(`
198
- `)}:$==="ask"?{label:"plan-approval",userMessage:I,userMessages:x,planReviewSummary:S,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${m??"?"}`,a,C,"","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):",r].join(`
199
- `),buttons:x?void 0:p}:{label:"plan-approval",userMessage:I,planReviewSummary:S,wakeMessage:["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true)`].join(`
200
- `)}}let R=e.multiTurn?"Multi-turn session":"Session";return{label:"waiting",userMessage:I,wakeMessage:[`[SYSTEM INSTRUCTION: Follow your auto-respond rules strictly. If this is a permission request or "should I continue?" \u2192 auto-respond. For ALL other questions \u2192 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.]`,"",`${R} is waiting for a genuine user reply.`,`Name: ${e.name} | ID: ${e.id}`,a,"","Last output:",r,"",`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(`
201
- `),buttons:d}}Pt();var Hs=class{constructor(e){this.deps=e;this.actions=new js({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(r=>typeof r=="string").join(`
197
+ ${e}`}function mT(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function Qo(t){let{session:e,summary:r}=t,n=e.actionablePlanDecisionVersion??e.planDecisionVersion;return[`\u{1F4CB} [${e.name}] Plan v${n??"?"} 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:","",r].join(`
198
+ `)}function Jp(t){let{session:e,preview:r,questionText:n,questionContextPreview:o,planArtifact:i,originThreadLine:a,planApprovalMode:u,planApprovalButtons:p,questionButtons:d}=t,l=e.pendingPlanApproval,m=e.actionablePlanDecisionVersion??e.planDecisionVersion,c=mT(e,m),h=u??"delegate",y=l&&h==="ask"&&!c?tg({sessionName:e.name,actionableVersion:m,preview:r,artifact:i,hasButtons:!!p}):void 0,k=l?y?.reviewSummary??zp({preview:r,artifact:i}):void 0,S=l?y&&y.userMessages.length===1?y.userMessages[0]:void 0:lT({sessionName:e.name,questionText:n??r,contextPreview:o}),x=l&&y&&y.userMessages.length>1?y.userMessages.map(($,C,Ie)=>({text:$,buttons:C===Ie.length-1?p:void 0})):void 0;if(l){let $=h,C="Permission mode: plan \u2192 will switch to bypassPermissions on approval";return $==="delegate"?{label:"plan-approval",userMessage:S,userMessages:x,planReviewSummary:k,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${m??"?"}`,a,C,"","\u26A0\uFE0F YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","\u2501\u2501\u2501 STEP 1 (MANDATORY): Read the full plan \u2501\u2501\u2501",`Call agent_output(session='${e.id}', full=true) to read the FULL plan output.`,"The preview below is truncated \u2014 you MUST read the full output before making any decision.","","Preview (truncated):",r,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Review privately \u2501\u2501\u2501","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.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","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 \u2014 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(`
199
+ `)}:$==="ask"?{label:"plan-approval",userMessage:S,userMessages:x,planReviewSummary:k,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${m??"?"}`,a,C,"","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):",r].join(`
200
+ `),buttons:x?void 0:p}:{label:"plan-approval",userMessage:S,planReviewSummary:k,wakeMessage:["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true)`].join(`
201
+ `)}}let R=e.multiTurn?"Multi-turn session":"Session";return{label:"waiting",userMessage:S,wakeMessage:[`[SYSTEM INSTRUCTION: Follow your auto-respond rules strictly. If this is a permission request or "should I continue?" \u2192 auto-respond. For ALL other questions \u2192 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.]`,"",`${R} is waiting for a genuine user reply.`,`Name: ${e.name} | ID: ${e.id}`,a,"","Last output:",r,"",`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(`
202
+ `),buttons:d}}var ng=3,cT=180,fT=4e3,og=32;function ig(){let t=ts(),e=ST(t);if(e)return{async generateWorktreeDecisionSummary(r){if(typeof e.generateWorktreeDecisionSummary=="function")return await e.generateWorktreeDecisionSummary(r);if(typeof e.summarizeWorktreeDecision=="function")return await e.summarizeWorktreeDecision(r);let n=IT(r);if(typeof e.generateObject=="function")return await e.generateObject({task:"openclaw-code-agent.worktree-decision-summary",prompt:n,input:r});if(typeof e.generateText=="function")return await e.generateText({task:"openclaw-code-agent.worktree-decision-summary",prompt:n});if(typeof e.complete=="function")return await e.complete({prompt:n})}}}function gT(t){let e=[],r=t.changedFiles.slice(0,3).map(o=>`\`${o}\``);if(r.length>0){let o=t.changedFiles.length-r.length;e.push(o>0?`Touches ${r.join(", ")} and ${o} more file${o===1?"":"s"}`:`Touches ${r.join(", ")}`)}let n=[...new Set(t.commitMessages.map(o=>o.message.trim()).filter(Boolean))].slice(0,2);return n.length>0&&e.push(`Recent work: ${n.join("; ")}`),e}async function sg(t){let e=hT(t),r=gT(t.diffSummary??{changedFiles:e.changedFiles,commitMessages:e.commitSubjects.map(n=>({message:n}))});if(!t.provider)return{source:"fallback",lines:r,evidence:e,error:"LLM summary provider unavailable."};try{let n=await t.provider.generateWorktreeDecisionSummary(e),o=yT(n);return o.length>0?{source:"llm",lines:o,evidence:e}:{source:"fallback",lines:r,evidence:e,error:"LLM-generated worktree summary failed schema validation."}}catch(n){let o=n instanceof Error?n.message:String(n);return console.warn(`[worktree_decision_summary] LLM summary provider failed: ${o}`),{source:"fallback",lines:r,evidence:e,error:"LLM summary provider failed."}}}function hT(t){let e=t.diffSummary;return{sessionName:t.sessionName,objective:xT(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(r=>ag(r.message)).filter(Boolean).slice(0,8)??[],outputPreview:ug(pg(t.outputPreview??""),fT)}}function yT(t){let e=kT(t),r=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.summary)?e.summary:void 0;if(!r||r.length===0||r.length>ng)return[];let n=r.map(o=>typeof o=="string"?ag(o):"").filter(Boolean);return n.length!==r.length?[]:n.some(o=>o.length>cT)?[]:n.some(PT)?[]:n}function kT(t){if(typeof t!="string")return t;let e=t.trim();if(e)try{return JSON.parse(e)}catch{return{summary:e.split(`
203
+ `).map(r=>r.replace(/^[-*•]\s+/,"").trim()).filter(Boolean).slice(0,ng)}}}function ST(t){return[t?.worktreeDecisionSummary,t?.llm,t?.ai,t?.model,t?.models].find(r=>!!(r&&typeof r=="object"&&(typeof r.generateWorktreeDecisionSummary=="function"||typeof r.summarizeWorktreeDecision=="function"||typeof r.generateObject=="function"||typeof r.generateText=="function"||typeof r.complete=="function")))}function IT(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(`
204
+ `)}function xT(t){let e=t?.replace(/\r\n/g,`
205
+ `).split(`
206
+ `).map(o=>o.trim()).filter(Boolean).join(" ");if(!e)return;let r=e.match(/^[^.!?]+[.!?]/)?.[0]??e,n=pg(r).replace(/\s+/g," ").trim();return n?ug(n,180):void 0}function ag(t){return t.replace(/^[-*•]\s+/,"").replace(/\s+/g," ").trim()}function ug(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-3)).trimEnd()}...`}function pg(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_-]{${og},}\\b`,"g"),"[redacted token]")}function PT(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_-]{${og},}\\b`).test(t)}Pt();var ea=class{constructor(e){this.deps=e;this.actions=new Zs({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(r=>typeof r=="string").join(`
202
207
  `)}notifyAutoMergeConflictEscalation(e,r,n){this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-escalated",userMessage:[`\u26A0\uFE0F [${e.name}] Auto-merge could not finish after one conflict-resolution attempt.`,`Branch \`${r}\` was preserved for manual follow-up.`,"",n].join(`
203
- `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}updatePersistedSessionFor(e,r){for(let n of ct(e))this.deps.updatePersistedSession(n,r)}markPendingDecision(e,r={}){this.updatePersistedSessionFor(e,Gs(e,r))}markAutoMergeConflictResolving(e,r,n){this.updatePersistedSessionFor(e,Bf(e,r,n,{notes:[`resolver_session:${r}`]}))}markMerged(e){this.updatePersistedSessionFor(e,Uf(e,{clearResolverSessionId:!0}))}async handleWorktreeStrategy(e){let r=await this.actions.plan(e);return r.kind==="skip"?r.result:r.kind==="notify"?(this.deps.dispatchSessionNotification(e,{label:r.label,userMessage:r.message}),{notificationSent:!0,worktreeRemoved:!1}):r.kind==="dirty-uncommitted"?this.handleDirtyUncommittedCompletion(e,r.worktreePath,r.branchName,r.baseBranch):r.kind==="no-change"?this.handleNoChange(e,r.repoDir,r.worktreePath,r.nativeBackendWorktree):r.strategy==="ask"?this.handleAskStrategy(e,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="delegate"?this.handleDelegateStrategy(e,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="auto-merge"?(await this.handleAutoMergeStrategy(e,r.repoDir,r.worktreePath,r.branchName,r.baseBranch,r.diffSummary,r.sessionRef),{notificationSent:!0,worktreeRemoved:!1}):r.strategy==="auto-pr"?this.handleAutoPrStrategy(e,r.baseBranch):{notificationSent:!1,worktreeRemoved:!1}}async handleNoChange(e,r,n,o=lt(e)){let i=o?!0:xt(r,n);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:n,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:n,preview:this.deps.getOutputPreview(e),originThreadLine:this.deps.originThreadLine(e)})),{notificationSent:!0,worktreeRemoved:i}}handleAskStrategy(e,r,n,o){return this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildAskNotification({session:e,branchName:r,baseBranch:n,diffSummary:o,buttons:this.deps.getWorktreeDecisionButtons(e.id)})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleDelegateStrategy(e,r,n,o){return this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildDelegateNotification({session:e,branchName:r,baseBranch:n,diffSummary:o,originThreadLine:this.deps.originThreadLine(e)})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleDirtyUncommittedCompletion(e,r,n,o){this.markPendingDecision(e,{notes:["dirty_uncommitted_completion"]});let i=Wn(r),a=i.slice(0,20).map(p=>`- ${p}`),u=i.length>20?[`- ...and ${i.length-20} more`]:[];return this.deps.dispatchSessionNotification(e,{label:"worktree-dirty-uncommitted",userMessage:[`\u26A0\uFE0F [${e.name}] Session completed with uncommitted worktree changes.`,"",`Branch \`${n}\` has no commits ahead of \`${o}\`, so merge/PR follow-through is blocked until the worktree is fixed.`,`Worktree: ${r}`,"",...a.length>0?["Dirty entries:",...a,...u,""]:[],"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(`
208
+ `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}updatePersistedSessionFor(e,r){for(let n of lt(e))this.deps.updatePersistedSession(n,r)}markPendingDecision(e,r={}){this.updatePersistedSessionFor(e,Ls(e,r))}markAutoMergeConflictResolving(e,r,n){this.updatePersistedSessionFor(e,Xc(e,r,n,{notes:[`resolver_session:${r}`]}))}markMerged(e){this.updatePersistedSessionFor(e,Fs(e,{clearResolverSessionId:!0}))}async handleWorktreeStrategy(e){let r=await this.actions.plan(e);return r.kind==="skip"?r.result:r.kind==="notify"?(this.deps.dispatchSessionNotification(e,{label:r.label,userMessage:r.message}),{notificationSent:!0,worktreeRemoved:!1}):r.kind==="dirty-uncommitted"?this.handleDirtyUncommittedCompletion(e,r.worktreePath,r.branchName,r.baseBranch):r.kind==="no-change"?this.handleNoChange(e,r.repoDir,r.worktreePath,r.nativeBackendWorktree):r.strategy==="ask"?await this.handleAskStrategy(e,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="delegate"?this.handleDelegateStrategy(e,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="auto-merge"?(await this.handleAutoMergeStrategy(e,r.repoDir,r.worktreePath,r.branchName,r.baseBranch,r.diffSummary,r.sessionRef),{notificationSent:!0,worktreeRemoved:!1}):r.strategy==="auto-pr"?this.handleAutoPrStrategy(e,r.baseBranch):{notificationSent:!1,worktreeRemoved:!1}}async handleNoChange(e,r,n,o=mt(e)){let i=o?!0:xt(r,n);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:n,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:n,preview:this.deps.getOutputPreview(e),originThreadLine:this.deps.originThreadLine(e)})),{notificationSent:!0,worktreeRemoved:i}}async handleAskStrategy(e,r,n,o){let i=await sg({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:r,baseBranch:n,diffSummary:o,summaryLines:i.lines,buttons:this.deps.getWorktreeDecisionButtons(e.id)})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleDelegateStrategy(e,r,n,o){return this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildDelegateNotification({session:e,branchName:r,baseBranch:n,diffSummary:o,originThreadLine:this.deps.originThreadLine(e)})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleDirtyUncommittedCompletion(e,r,n,o){this.markPendingDecision(e,{notes:["dirty_uncommitted_completion"]});let i=Wn(r),a=i.slice(0,20).map(p=>`- ${p}`),u=i.length>20?[`- ...and ${i.length-20} more`]:[];return this.deps.dispatchSessionNotification(e,{label:"worktree-dirty-uncommitted",userMessage:[`\u26A0\uFE0F [${e.name}] Session completed with uncommitted worktree changes.`,"",`Branch \`${n}\` has no commits ahead of \`${o}\`, so merge/PR follow-through is blocked until the worktree is fixed.`,`Worktree: ${r}`,"",...a.length>0?["Dirty entries:",...a,...u,""]:[],"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(`
204
209
  `)}),{notificationSent:!0,worktreeRemoved:!1}}handleAutoMergeSuccess(e,r,n,o,i,a){Jt(r,n),this.markMerged(e);let u=an({kind:"merge",branch:n,base:o,filesChanged:i.filesChanged,insertions:i.insertions,deletions:i.deletions}),p=u;a.stashPopConflict?p+=`
205
210
  \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${a.stashRef??"stash@{0}"}\` in ${r} to review stashed changes.`:a.stashed&&(p+=`
206
211
  (Pre-existing changes on ${o} were auto-stashed and restored.)`);let d=[a.fastForward?"Merge type: fast-forward.":"Merge type: merge commit.",`Auto-merge landed ${n} into ${o}.`,"Local worktree branch cleanup was requested.",...a.stashPopConflict?[`Pre-merge stash pop conflicted; run git stash show ${a.stashRef??"stash@{0}"} in ${r} to review stashed changes.`]:[],...!a.stashPopConflict&&a.stashed?[`Pre-existing changes on ${o} were auto-stashed and restored.`]:[]];this.deps.dispatchSessionNotification(e,{label:"worktree-merge-success",userMessage:p,notifyUser:"always",completionWakeSummaryRequired:!0,deferConditionalWakeUntilNextTick:!0,wakeMessageOnNotifySuccess:Hn({sessionId:e.id,sessionName:e.name,outcomeLine:u,originThreadLine:this.deps.originThreadLine(e),detailLines:d,canonicalStatusDelivered:!0}),wakeMessageOnNotifyFailed:Hn({sessionId:e.id,sessionName:e.name,outcomeLine:u,originThreadLine:this.deps.originThreadLine(e),detailLines:d,canonicalStatusDelivered:!1})})}async handleInitialAutoMergeConflict(e,r,n,o,i,a){let u=e.autoMergeConflictResolutionAttemptCount??0;if(u>=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 ${n}.`);return}let p=this.buildConflictResolverPrompt({session:e,repoDir:r,worktreePath:n,branchName:o,baseBranch:i,mergeError:a});try{let d=await this.deps.spawnConflictResolver({session:e,repoDir:r,worktreePath:n,branchName:o,baseBranch:i,prompt:p});this.markAutoMergeConflictResolving(e,d.id,u+1),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-resolving",userMessage:`\u26A0\uFE0F [${e.name}] Auto-merge hit a rebase conflict. Started resolver session ${d.name} and will retry automatically if it succeeds.`})}catch(d){this.markPendingDecision(e,{notes:["auto_merge_conflict_resolver_spawn_failed"]}),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-spawn-failed",userMessage:`\u274C [${e.name}] Auto-merge hit a rebase conflict and failed to start the resolver: ${d instanceof Error?d.message:String(d)}`,buttons:[[this.deps.makeOpenPrButton(e.id)]]})}}handleAutoMergeRetryFailure(e,r,n,o){this.markPendingDecision(e,{notes:["auto_merge_conflict_retry_failed"],clearResolverSessionId:!0}),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-error",userMessage:[o,"","Auto-merge retry did not complete after conflict resolution.",`Branch \`${r}\` was preserved for manual follow-up in ${n}.`].join(`
207
- `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}async handleAutoMergeStrategy(e,r,n,o,i,a,u=ye(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 ET,writeFileSync as $T}from"fs";ir();import{randomUUID as eT}from"crypto";function tT(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}var zs=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:eT(),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||!tT(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 Js=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 bT,mkdirSync as AT,readFileSync as TT,readdirSync as jp,renameSync as og,statSync as ig,unlinkSync as sg,writeFileSync as ag}from"fs";import{tmpdir as Gp}from"os";import{dirname as RT,join as Xs}from"path";import{homedir as rT}from"node:os";import{join as nT}from"node:path";function Zf(t){let e=t.OPENCLAW_HOME?.trim();if(e)return e;let r=t.HOME?.trim()||rT();return nT(r,".openclaw")}ir();var Qs=6,oT=new Set(["running","completed","failed","killed"]);function zo(t){return!!t&&typeof t=="object"}function zn(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 iT(t){return typeof t=="string"&&jc.has(t)?t:void 0}function Xf(t){return t==="default"||t==="plan"||t==="bypassPermissions"?t:void 0}function sT(t){return t==="never"||t==="on-request"?"never":void 0}function aT(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 eg(t){return typeof t=="string"&&bs.has(t)?t:void 0}function pT(t){return t==="user"||t==="idle-timeout"||t==="startup-timeout"||t==="shutdown"||t==="done"||t==="unknown"?t:void 0}function dT(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 lT(t){return t==="not_required"||t==="pending"||t==="approved"||t==="changes_requested"||t==="rejected"?t:void 0}function mT(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 cT(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 fT(t){return t==="live"||t==="stopped"?t:void 0}function gT(t){return t==="not_sent"||t==="sending"||t==="delivered"||t==="fallback_delivered"||t==="failed"?t:void 0}function hT(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 ST(t){return t==="idle"||t==="notifying"||t==="wake_pending"||t==="failed"?t:void 0}function kT(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 IT(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 tg(t){if(!zo(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 xT(t,e,r){if(zo(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 PT(t){if(!zo(t))return;let e=cT(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 wT(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 vT(t){if(typeof t=="string"&&oT.has(t))return t==="running"?"killed":t}function rg(t){if(!zo(t))return;let e=zn(t.harnessSessionId);if(!e)return;let r=vT(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=tg(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=xT(t.backendRef,m,e),h=PT(t.worktreeLifecycle)??wT(t),y=w(t.completionWakeSucceededAt),S=w(t.completionWakeSkippedAt),I=t.completionWakeSummaryRequired===!0&&!S?!0:void 0;return{sessionId:w(t.sessionId),harnessSessionId:e,backendRef:c,name:zn(t.name,e),prompt:zn(t.prompt),workdir:zn(t.workdir,"(unknown)"),model:w(t.model),reasoningEffort:iT(t.reasoningEffort),fastMode:t.fastMode===!0?!0:void 0,createdAt:gt(t.createdAt),completedAt:gt(t.completedAt),status:r,lifecycle:n?"suspended":dT(t.lifecycle),approvalState:lT(t.approvalState),worktreeState:mT(t.worktreeState),runtimeState:n?"stopped":fT(t.runtimeState),deliveryState:ST(t.deliveryState),completionWakeIssuedAt:w(t.completionWakeIssuedAt),completionWakeSucceededAt:y,completionWakeFailedAt:w(t.completionWakeFailedAt),completionWakeSkippedAt:S,completionWakeSkipReason:w(t.completionWakeSkipReason),completionWakeSummaryRequired:I,killReason:pT(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,requestedPermissionMode:Xf(t.requestedPermissionMode),currentPermissionMode:Xf(t.currentPermissionMode),approvalExecutionState:kT(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:gT(t.approvalPromptStatus),approvalPromptTransport:hT(t.approvalPromptTransport),approvalPromptMessageKind:yT(t.approvalPromptMessageKind),approvalPromptLastAttemptAt:w(t.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:w(t.approvalPromptDeliveredAt),approvalPromptFailedAt:w(t.approvalPromptFailedAt),planApproval:aT(t.planApproval),codexApprovalPolicy:sT(t.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:eg(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 ng(t){if(!zo(t))return;let e=IT(t.kind),r=zn(t.id),n=zn(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:tg(t.route),launchName:w(t.launchName),launchPrompt:w(t.launchPrompt),launchWorkdir:w(t.launchWorkdir),launchWorktreeStrategy:eg(t.launchWorktreeStrategy)}}function Ys(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 Kp(t){return!!t&&typeof t=="object"}function Vp(t){return t instanceof Error?t.message:String(t)}function ug(t){let e=t.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||Xs(Zf(t),"code-agent-sessions.json")}function pg(t,e,r){try{AT(RT(t),{recursive:!0});let n=t+".tmp";ag(n,JSON.stringify({schemaVersion:Qs,sessions:e,actionTokens:r},null,2),"utf-8"),og(n,t)}catch(n){console.warn(`[SessionStore] Failed to save session index: ${Vp(n)}`)}}function Zs(t,e){try{if(!bT(t))return;let r=`${t}.legacy-${Date.now()}.json`;og(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: ${Vp(r)}`)}}function CT(t,e){try{if(e.length===0)return;let r=`${t}.codex-sdk-legacy-${Date.now()}.json`;ag(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: ${Vp(r)}`)}}function dg(t,e){try{let r=Gp(),n=jp(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n)try{let i=Xs(r,o),a=ig(i).mtimeMs;t-a>e&&sg(i)}catch{}}catch{}}function lg(t,e){try{let r=Gp(),n=jp(r).filter(i=>i.startsWith("openclaw-agent-")&&i.endsWith(".txt")),o;for(let i of n)try{let a=Xs(r,i),u=ig(a).mtimeMs+e;if(u<=t)return t;o=o==null?u:Math.min(o,u)}catch{}return o}catch{return}}function mg(t){try{let e=new Set(t),r=Gp(),n=jp(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n){let i=Xs(r,o);if(!e.has(i))try{sg(i)}catch{}}}catch{}}function cg(t){let{indexPath:e,clearAll:r,indexPersistedEntry:n,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:a}=t;try{let u=TT(e,"utf-8"),p=JSON.parse(u);if(Array.isArray(p)){Zs(e,"legacy array store"),a();return}if(!Kp(p)||p.schemaVersion!==Qs&&p.schemaVersion!==4){Zs(e,`schema mismatch (expected v${Qs})`),a();return}let d=Array.isArray(p.sessions)?p.sessions:[],l=[];for(let c of d){if(Kp(c)&&c.harness==="codex"){let y=Kp(c.backendRef)?c.backendRef:void 0;if((typeof y?.kind=="string"?y.kind:void 0)!=="codex-app-server"){l.push(c);continue}}let h=rg(c);if(!h){r(),Zs(e,"invalid v4 session entry"),a();return}n(h)}l.length>0&&(CT(e,l),a());let m=Array.isArray(p.actionTokens)?p.actionTokens:[];for(let c of m){let h=ng(c);if(!h){r(),Zs(e,"invalid v4 action token"),a();return}o(h)}i()}catch{}}var MT=new Set(["completed","failed","killed"]),Hp=1440*60*1e3;function OT(t){return t instanceof Error?t.message:String(t)}var ea=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??ug(r),this.actionTokenStore=new zs(()=>this.saveIndex(),Hp),this.actionTokens=this.actionTokenStore.tokens,this.queries=new Js({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(){cg({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(){pg(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(e){Ys(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){return e.backendRef??{kind:ep(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};Ys(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=Bn(e.id);if(ET(a))o=a;else{let u=e.getOutput().join(`
208
- `);u.length>0&&($T(a,u,"utf-8"),o=a)}}catch(a){console.warn(`[SessionStore] Failed to write output file for session ${e.id}: ${OT(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,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};Ys(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),dg(e,Hp)}getNextTmpOutputCleanupAt(e){return lg(e,Hp)}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||!MT.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(){mg(this.getReferencedOutputPaths())}};var _T=new Set(["completed","failed","killed"]),ta=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),_T.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:Je(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 hg from"child_process";var fg=5e3,DT=64,LT={primary:"primary",success:"success",positive:"success",danger:"danger",destructive:"danger",negative:"danger"},FT={execFile:hg.execFile},Rr=class extends Error{constructor(e){super(e),this.name="MissingRuntimeDirectNotificationCapabilityError"}},ra=class{constructor(e=FT.execFile){this.execFile=e}execFile;async send(e,r,n){ie("direct_send_started",{...$t(e),messageTextLength:r.length,...xe(n)});try{await this.sendViaRuntime(e,r,n),ie("direct_send_succeeded",{...$t(e),deliveryPath:"runtime",...xe(n)});return}catch(o){if(!(o instanceof Rr))throw ie("direct_send_failed",{...$t(e),deliveryPath:"runtime",...xe(n),error:zp(o)}),o;ie("direct_send_runtime_capability_missing",{...$t(e),deliveryPath:"runtime",...xe(n),reason:o.message}),await this.sendViaBoundedCliFallback(e,r,n,o.message),ie("direct_send_succeeded",{...$t(e),deliveryPath:"cli-fallback",...xe(n)})}}async sendViaRuntime(e,r,n){let o=nc(),i=ic(),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=${Jp(o)})`);if(!o.channel.outbound)throw new Rr(`OpenClaw plugin runtime channel outbound surface is unavailable for direct notification delivery (runtimeVersion=${Jp(o)})`);if(!a)throw new Rr(`OpenClaw plugin runtime channel outbound loadAdapter is unavailable for direct notification delivery (runtimeVersion=${Jp(o)})`);let u=await a(e.channel);if(!u)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" is unavailable`);let p=na(n);if(ie("runtime_adapter_loaded",{...$t(e),adapterHasRenderPresentation:typeof u.renderPresentation=="function",adapterHasSendPayload:typeof u.sendPayload=="function",adapterHasSendText:typeof u.sendText=="function",...xe(n),...p?Pp(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=qT(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",...Pp(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=UT(d,a,n.channel);if(ie("presentation_render_completed",{...$t(n),adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...wp(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),...wp(l),...ff(m)})}sendViaBoundedCliFallback(e,r,n,o){return new Promise((i,a)=>{let u=NT(e,r,n);ie("direct_send_cli_fallback_started",{...$t(e),deliveryPath:"cli-fallback",reason:o,messageTextLength:r.length,...xe(n)}),this.execFile("openclaw",u,{timeout:fg,killSignal:"SIGKILL"},(p,d,l)=>{if(!p){ie("direct_send_cli_fallback_completed",{...$t(e),deliveryPath:"cli-fallback",...xe(n)}),i();return}let m=l?.trim()?` | stderr: ${l.trim()}`:"";ie("direct_send_cli_fallback_failed",{...$t(e),deliveryPath:"cli-fallback",...xe(n),error:zp(p),stderrLength:l?.length}),a(new Error(`${o}; bounded openclaw message send fallback failed within ${fg}ms timeout: ${zp(p)}${m}`))})})}};function $t(t){return{channel:t.channel,target:t.target,accountId:t.accountId,threadId:t.threadId,sessionKey:t.sessionKey}}function NT(t,e,r){let n=na(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 zp(t){return t instanceof Error?t.message:String(t)}function Jp(t){if(!t||typeof t!="object")return"unknown";let e=t.version;return typeof e=="string"&&e.trim()?e:"unknown"}function na(t){let e=(t??[]).filter(r=>Array.isArray(r)&&r.length>0).map(r=>({type:"buttons",buttons:r.map(n=>({label:n.label,value:VT(n.callbackData),...n.style?{style:n.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function qT(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 BT(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 UT(t,e,r){if(!e)return t;let n=BT(t)?t:WT(t,e);return r!=="telegram"?n:KT(n,e)}function WT(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:{...t,interactive:e}}function KT(t,e){if(!t||typeof t!="object"||Array.isArray(t))return t;let r=t,n=gg(r.channelData),o=gg(n?.telegram),i=GT(o?.buttons);if(i)return{...r,channelData:{...n??{},telegram:{...o??{},buttons:i}}};let a=jT(e);return a?{...r,channelData:{...n??{},telegram:{...o??{},buttons:a}}}:t}function jT(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")<=DT).map(n=>({text:n.label,callback_data:n.value,...yg(n.style)}))).filter(r=>r.length>0);return e.length>0?e:void 0}function GT(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,...yg(o)}}).filter(n=>!!n):[]).filter(r=>r.length>0);return e.length>0?e:void 0}function yg(t){if(typeof t!="string")return{};let e=t.trim().toLowerCase(),r=LT[e];return r?{style:r}:{}}function gg(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function VT(t){return t.startsWith(`${wt}:`)?t:`${wt}:${t}`}import*as Sg from"child_process";var Jn=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 Qp=3e4,HT=2e3,zT=2e4,ht=4;function Jo(t){return t instanceof Error?t.message:String(t)}function JT(){return new Error(`Dispatch timed out after ${Qp}ms`)}function QT(t){if(!(t instanceof Error))return!1;let e=t;return e.killed===!0&&e.signal==="SIGKILL"}var YT={execFile:Sg.execFile},oa=class{pendingRetryTimers=new Map;orderedDispatches=new Jn;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}),YT.execFile("openclaw",e,{timeout:Qp,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"&&QT(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:`${Jo(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:`${Jo(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:`${Jo(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:Jo(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:Jo(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(JT()))},Qp);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=HT*2**r;return Math.min(n,zT)}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 ia=class{resolve(e){let r=$i(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 ZT}from"crypto";var sa=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:ZT()})]}buildDirectNotificationArgs(e,r,n){let o=na(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 kg="COMPLETION_FOLLOWUP_DELIVERED",Ig="COMPLETION_FOLLOWUP_SKIPPED";function XT(t){let e=eR(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(kg)){let r=tR(e);return r?{outcome:"skipped",reason:r}:{outcome:"failure",reason:`completion follow-up wake did not confirm ${kg}`}}return{outcome:"success"}}function eR(t){let e=t.trim();if(!e)return"";try{return Yp(JSON.parse(e)).trim()}catch{return e}}function Yp(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>Yp(n)).filter(Boolean).join(`
209
- `);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=Yp(e[n]);if(o.trim())return o}return""}function tR(t){let e=t.indexOf(Ig);return e<0?void 0:t.slice(e+Ig.length).replace(/^[:\s-]+/,"").split(/\r?\n/,1)[0]?.trim()||"explicitly skipped by wake agent"}var aa=class{routes=new ia;transport;directNotifications;executor=new oa;constructor(e={}){this.transport=e.transport??new sa(e.transportOptions),this.directNotifications=e.directNotifications===void 0?new ra: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,...xe(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,...xe(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,...xe(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,...xe(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,...xe(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",...xe(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?XT: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)}},S=()=>{d?.()!==!1&&(n?.onNotifySucceeded?.(),m&&y(m))},I=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,I,S,r.requireDirectUserNotification===!0,d)}else I();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 ua=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,...xe(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,...xe(p)}),p}};Ee();ir();var pa=class{constructor(e,r){this.wakeDispatcher=e;this.applyPersistedPatch=r}wakeDispatcher;applyPersistedPatch;dispatch(e,r){let n=this.getDeliveryRef(e),o=this.buildCompletionWakePatch(r),i=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifySuccess?.trim()),a=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifyFailed?.trim()),u={onNotifyStarted:()=>{this.applyDeliveryState(n,"notifying"),r.hooks?.onNotifyStarted?.()},onNotifySucceeded:()=>{this.applyNotifyDeliveryState(n,i?"wake_pending":"idle",i?o:void 0),r.hooks?.onNotifySucceeded?.()},onNotifyFailed:()=>{this.applyNotifyDeliveryState(n,a?"wake_pending":"failed",a?o:void 0),r.hooks?.onNotifyFailed?.()},onWakeStarted:()=>{this.applyPersistedPatchWithCompletionWake(n,"wake_pending",o,{completionWakeIssuedAt:new Date().toISOString(),completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0,completionWakeSkippedAt:void 0,completionWakeSkipReason:void 0}),r.hooks?.onWakeStarted?.()},onWakeSucceeded:()=>{this.applyPersistedPatchWithCompletionWake(n,"idle",this.buildCompletionWakeSucceededPatch(o),{completionWakeSucceededAt:new Date().toISOString(),completionWakeFailedAt:void 0,completionWakeSkippedAt:void 0,completionWakeSkipReason:void 0}),r.hooks?.onWakeSucceeded?.()},onWakeSkipped:p=>{this.applyPersistedPatchWithCompletionWake(n,"idle",this.buildCompletionWakeSucceededPatch(o),{completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0,completionWakeSkippedAt:new Date().toISOString(),completionWakeSkipReason:p}),r.hooks?.onWakeSkipped?.(p)},onWakeFailed:()=>{this.applyPersistedPatchWithCompletionWake(n,"failed",o,{completionWakeFailedAt:new Date().toISOString()}),r.hooks?.onWakeFailed?.()}};this.wakeDispatcher.dispatchSessionNotification(e,{...r,hooks:u})}notifyWorktreeOutcome(e,r,n={}){let o=this.getDeliveryRef(e),i=u=>Hn({sessionId:o,sessionName:e.name,outcomeLine:r,originThreadLine:Mi(e),detailLines:n.detailLines,canonicalStatusDelivered:u}),a=n.summaryWakeRequired??!0;this.dispatch(e,{label:"worktree-outcome",userMessage:r,notifyUser:"always",requireDirectUserNotification:!0,completionWakeSummaryRequired:a,deferConditionalWakeUntilNextTick:!0,wakeMessageOnNotifySuccess:a?i(!0):void 0,wakeMessageOnNotifyFailed:a?i(!1):void 0})}dispose(){this.wakeDispatcher.dispose()}getDeliveryRef(e){return ye(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}}};Pt();import{existsSync as rR}from"fs";var da=class{getCompletionState(e,r,n,o){return Fo(e,n,o)?"has-commits":Fo(e,o,n)?"base-advanced":Kn(r)?"dirty-uncommitted":"no-change"}isResolvedWorktreeEligibleForCleanup(e,r,n){if(!e.worktreePath||!e.workdir||!rR(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&&r-i>=n}};var la=class{constructor(e,r,n,o){this.pendingQuestions=e;this.dispatchSessionNotification=r;this.clearWaitingTimestamp=n;this.getQuestionButtons=o}pendingQuestions;dispatchSessionNotification;clearWaitingTimestamp;getQuestionButtons;async handleAskUserQuestion(e,r){let i=r?.questions??[];if(i.length===0)throw new Error("AskUserQuestion: no questions in input");let a=i[0],u=a.options??[],p=this.getQuestionButtons(e.id,u),d=`\u2753 [${e.name}] ${a.question}`,l=[`[ASK USER QUESTION] Session "${e.name}" has a question requiring user input.`,"",`Question: ${a.question}`,...u.length>0?["Options:",...u.map((m,c)=>` ${c+1}. ${m.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${e.id}", message="<answer>") with their answer.`].join(`
212
+ `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}async handleAutoMergeStrategy(e,r,n,o,i,a,u=ye(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 XT,writeFileSync as eR}from"fs";ir();import{randomUUID as wT}from"crypto";function vT(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}var ta=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:wT(),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||!vT(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 ra=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 zT,mkdirSync as JT,readFileSync as QT,readdirSync as Yp,renameSync as hg,statSync as yg,unlinkSync as kg,writeFileSync as Sg}from"fs";import{tmpdir as Zp}from"os";import{dirname as YT,join as sa}from"path";import{homedir as bT}from"node:os";import{join as AT}from"node:path";function dg(t){let e=t.OPENCLAW_HOME?.trim();if(e)return e;let r=t.HOME?.trim()||bT();return AT(r,".openclaw")}ir();var na=6,TT=new Set(["running","completed","failed","killed"]);function Yo(t){return!!t&&typeof t=="object"}function zn(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 RT(t){return typeof t=="string"&&Qc.has(t)?t:void 0}function lg(t){return t==="default"||t==="plan"||t==="bypassPermissions"?t:void 0}function CT(t){return t==="never"||t==="on-request"?"never":void 0}function ET(t){return t==="approve"||t==="ask"||t==="delegate"?t:void 0}function $T(t){if(t==="plan-mode"||t==="codex-first-turn-plan"||t==="soft-plan")return"plan-mode"}function mg(t){return typeof t=="string"&&Rs.has(t)?t:void 0}function MT(t){return t==="user"||t==="idle-timeout"||t==="startup-timeout"||t==="shutdown"||t==="done"||t==="unknown"?t:void 0}function OT(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 _T(t){return t==="not_required"||t==="pending"||t==="approved"||t==="changes_requested"||t==="rejected"?t:void 0}function DT(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 LT(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 FT(t){return t==="live"||t==="stopped"?t:void 0}function NT(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 BT(t){return t==="none"||t==="canonical_buttons"||t==="explicit_fallback_text"?t:void 0}function UT(t){return t==="idle"||t==="notifying"||t==="wake_pending"||t==="failed"?t:void 0}function WT(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 KT(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 cg(t){if(!Yo(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 jT(t,e,r){if(Yo(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 GT(t){if(!Yo(t))return;let e=LT(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 VT(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 HT(t){if(typeof t=="string"&&TT.has(t))return t==="running"?"killed":t}function fg(t){if(!Yo(t))return;let e=zn(t.harnessSessionId);if(!e)return;let r=HT(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=cg(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=jT(t.backendRef,m,e),h=GT(t.worktreeLifecycle)??VT(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:zn(t.name,e),prompt:zn(t.prompt),workdir:zn(t.workdir,"(unknown)"),model:w(t.model),reasoningEffort:RT(t.reasoningEffort),fastMode:t.fastMode===!0?!0:void 0,createdAt:gt(t.createdAt),completedAt:gt(t.completedAt),status:r,lifecycle:n?"suspended":OT(t.lifecycle),approvalState:_T(t.approvalState),worktreeState:DT(t.worktreeState),runtimeState:n?"stopped":FT(t.runtimeState),deliveryState:UT(t.deliveryState),completionWakeIssuedAt:w(t.completionWakeIssuedAt),completionWakeSucceededAt:y,completionWakeFailedAt:w(t.completionWakeFailedAt),completionWakeSkippedAt:k,completionWakeSkipReason:w(t.completionWakeSkipReason),completionWakeSummaryRequired:S,killReason:MT(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,requestedPermissionMode:lg(t.requestedPermissionMode),currentPermissionMode:lg(t.currentPermissionMode),approvalExecutionState:WT(t.approvalExecutionState),approvalRationale:w(t.approvalRationale),planModeApproved:t.planModeApproved===!0,pendingPlanApproval:t.pendingPlanApproval===!0,planApprovalContext:$T(t.planApprovalContext),planDecisionVersion:gt(t.planDecisionVersion),actionablePlanDecisionVersion:gt(t.actionablePlanDecisionVersion),canonicalPlanPromptVersion:gt(t.canonicalPlanPromptVersion),approvalPromptRequiredVersion:gt(t.approvalPromptRequiredVersion),approvalPromptVersion:gt(t.approvalPromptVersion),approvalPromptStatus:NT(t.approvalPromptStatus),approvalPromptTransport:qT(t.approvalPromptTransport),approvalPromptMessageKind:BT(t.approvalPromptMessageKind),approvalPromptLastAttemptAt:w(t.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:w(t.approvalPromptDeliveredAt),approvalPromptFailedAt:w(t.approvalPromptFailedAt),planApproval:ET(t.planApproval),codexApprovalPolicy:CT(t.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:mg(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 gg(t){if(!Yo(t))return;let e=KT(t.kind),r=zn(t.id),n=zn(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:cg(t.route),launchName:w(t.launchName),launchPrompt:w(t.launchPrompt),launchWorkdir:w(t.launchWorkdir),launchWorktreeStrategy:mg(t.launchWorktreeStrategy)}}function oa(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 Qp(t){return!!t&&typeof t=="object"}function Xp(t){return t instanceof Error?t.message:String(t)}function Ig(t){let e=t.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||sa(dg(t),"code-agent-sessions.json")}function xg(t,e,r){try{JT(YT(t),{recursive:!0});let n=t+".tmp";Sg(n,JSON.stringify({schemaVersion:na,sessions:e,actionTokens:r},null,2),"utf-8"),hg(n,t)}catch(n){console.warn(`[SessionStore] Failed to save session index: ${Xp(n)}`)}}function ia(t,e){try{if(!zT(t))return;let r=`${t}.legacy-${Date.now()}.json`;hg(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: ${Xp(r)}`)}}function ZT(t,e){try{if(e.length===0)return;let r=`${t}.codex-sdk-legacy-${Date.now()}.json`;Sg(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: ${Xp(r)}`)}}function Pg(t,e){try{let r=Zp(),n=Yp(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n)try{let i=sa(r,o),a=yg(i).mtimeMs;t-a>e&&kg(i)}catch{}}catch{}}function wg(t,e){try{let r=Zp(),n=Yp(r).filter(i=>i.startsWith("openclaw-agent-")&&i.endsWith(".txt")),o;for(let i of n)try{let a=sa(r,i),u=yg(a).mtimeMs+e;if(u<=t)return t;o=o==null?u:Math.min(o,u)}catch{}return o}catch{return}}function vg(t){try{let e=new Set(t),r=Zp(),n=Yp(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n){let i=sa(r,o);if(!e.has(i))try{kg(i)}catch{}}}catch{}}function bg(t){let{indexPath:e,clearAll:r,indexPersistedEntry:n,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:a}=t;try{let u=QT(e,"utf-8"),p=JSON.parse(u);if(Array.isArray(p)){ia(e,"legacy array store"),a();return}if(!Qp(p)||p.schemaVersion!==na&&p.schemaVersion!==4){ia(e,`schema mismatch (expected v${na})`),a();return}let d=Array.isArray(p.sessions)?p.sessions:[],l=[];for(let c of d){if(Qp(c)&&c.harness==="codex"){let y=Qp(c.backendRef)?c.backendRef:void 0;if((typeof y?.kind=="string"?y.kind:void 0)!=="codex-app-server"){l.push(c);continue}}let h=fg(c);if(!h){r(),ia(e,"invalid v4 session entry"),a();return}n(h)}l.length>0&&(ZT(e,l),a());let m=Array.isArray(p.actionTokens)?p.actionTokens:[];for(let c of m){let h=gg(c);if(!h){r(),ia(e,"invalid v4 action token"),a();return}o(h)}i()}catch{}}var tR=new Set(["completed","failed","killed"]),ed=1440*60*1e3;function rR(t){return t instanceof Error?t.message:String(t)}var aa=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??Ig(r),this.actionTokenStore=new ta(()=>this.saveIndex(),ed),this.actionTokens=this.actionTokenStore.tokens,this.queries=new ra({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(){bg({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(){xg(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(e){oa(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){return e.backendRef??{kind:ap(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};oa(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=Bn(e.id);if(XT(a))o=a;else{let u=e.getOutput().join(`
213
+ `);u.length>0&&(eR(a,u,"utf-8"),o=a)}}catch(a){console.warn(`[SessionStore] Failed to write output file for session ${e.id}: ${rR(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,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};oa(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),Pg(e,ed)}getNextTmpOutputCleanupAt(e){return wg(e,ed)}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||!tR.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(){vg(this.getReferencedOutputPaths())}};var nR=new Set(["completed","failed","killed"]),ua=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),nR.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:Je(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 Rg from"child_process";var Ag=5e3,oR=64,iR={primary:"primary",success:"success",positive:"success",danger:"danger",destructive:"danger",negative:"danger"},sR={execFile:Rg.execFile},Rr=class extends Error{constructor(e){super(e),this.name="MissingRuntimeDirectNotificationCapabilityError"}},pa=class{constructor(e=sR.execFile){this.execFile=e}execFile;async send(e,r,n){ie("direct_send_started",{...$t(e),messageTextLength:r.length,...xe(n)});try{await this.sendViaRuntime(e,r,n),ie("direct_send_succeeded",{...$t(e),deliveryPath:"runtime",...xe(n)});return}catch(o){if(!(o instanceof Rr))throw ie("direct_send_failed",{...$t(e),deliveryPath:"runtime",...xe(n),error:td(o)}),o;ie("direct_send_runtime_capability_missing",{...$t(e),deliveryPath:"runtime",...xe(n),reason:o.message}),await this.sendViaBoundedCliFallback(e,r,n,o.message),ie("direct_send_succeeded",{...$t(e),deliveryPath:"cli-fallback",...xe(n)})}}async sendViaRuntime(e,r,n){let o=ts(),i=lc(),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=${rd(o)})`);if(!o.channel.outbound)throw new Rr(`OpenClaw plugin runtime channel outbound surface is unavailable for direct notification delivery (runtimeVersion=${rd(o)})`);if(!a)throw new Rr(`OpenClaw plugin runtime channel outbound loadAdapter is unavailable for direct notification delivery (runtimeVersion=${rd(o)})`);let u=await a(e.channel);if(!u)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" is unavailable`);let p=da(n);if(ie("runtime_adapter_loaded",{...$t(e),adapterHasRenderPresentation:typeof u.renderPresentation=="function",adapterHasSendPayload:typeof u.sendPayload=="function",adapterHasSendText:typeof u.sendText=="function",...xe(n),...p?Cp(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=uR(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",...Cp(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=dR(d,a,n.channel);if(ie("presentation_render_completed",{...$t(n),adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...Ep(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),...Ep(l),...xf(m)})}sendViaBoundedCliFallback(e,r,n,o){return new Promise((i,a)=>{let u=aR(e,r,n);ie("direct_send_cli_fallback_started",{...$t(e),deliveryPath:"cli-fallback",reason:o,messageTextLength:r.length,...xe(n)}),this.execFile("openclaw",u,{timeout:Ag,killSignal:"SIGKILL"},(p,d,l)=>{if(!p){ie("direct_send_cli_fallback_completed",{...$t(e),deliveryPath:"cli-fallback",...xe(n)}),i();return}let m=l?.trim()?` | stderr: ${l.trim()}`:"";ie("direct_send_cli_fallback_failed",{...$t(e),deliveryPath:"cli-fallback",...xe(n),error:td(p),stderrLength:l?.length}),a(new Error(`${o}; bounded openclaw message send fallback failed within ${Ag}ms timeout: ${td(p)}${m}`))})})}};function $t(t){return{channel:t.channel,target:t.target,accountId:t.accountId,threadId:t.threadId,sessionKey:t.sessionKey}}function aR(t,e,r){let n=da(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 td(t){return t instanceof Error?t.message:String(t)}function rd(t){if(!t||typeof t!="object")return"unknown";let e=t.version;return typeof e=="string"&&e.trim()?e:"unknown"}function da(t){let e=(t??[]).filter(r=>Array.isArray(r)&&r.length>0).map(r=>({type:"buttons",buttons:r.map(n=>({label:n.label,value:gR(n.callbackData),...n.style?{style:n.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function uR(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 pR(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 dR(t,e,r){if(!e)return t;let n=pR(t)?t:lR(t,e);return r!=="telegram"?n:mR(n,e)}function lR(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:{...t,interactive:e}}function mR(t,e){if(!t||typeof t!="object"||Array.isArray(t))return t;let r=t,n=Tg(r.channelData),o=Tg(n?.telegram),i=fR(o?.buttons);if(i)return{...r,channelData:{...n??{},telegram:{...o??{},buttons:i}}};let a=cR(e);return a?{...r,channelData:{...n??{},telegram:{...o??{},buttons:a}}}:t}function cR(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")<=oR).map(n=>({text:n.label,callback_data:n.value,...Cg(n.style)}))).filter(r=>r.length>0);return e.length>0?e:void 0}function fR(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,...Cg(o)}}).filter(n=>!!n):[]).filter(r=>r.length>0);return e.length>0?e:void 0}function Cg(t){if(typeof t!="string")return{};let e=t.trim().toLowerCase(),r=iR[e];return r?{style:r}:{}}function Tg(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function gR(t){return t.startsWith(`${wt}:`)?t:`${wt}:${t}`}import*as Eg from"child_process";var Jn=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 nd=3e4,hR=2e3,yR=2e4,ht=4;function Zo(t){return t instanceof Error?t.message:String(t)}function kR(){return new Error(`Dispatch timed out after ${nd}ms`)}function SR(t){if(!(t instanceof Error))return!1;let e=t;return e.killed===!0&&e.signal==="SIGKILL"}var IR={execFile:Eg.execFile},la=class{pendingRetryTimers=new Map;orderedDispatches=new Jn;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}),IR.execFile("openclaw",e,{timeout:nd,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"&&SR(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:`${Zo(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:`${Zo(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:`${Zo(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:Zo(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:Zo(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(kR()))},nd);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=hR*2**r;return Math.min(n,yR)}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 ma=class{resolve(e){let r=_i(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 xR}from"crypto";var ca=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:xR()})]}buildDirectNotificationArgs(e,r,n){let o=da(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 $g="COMPLETION_FOLLOWUP_DELIVERED",Mg="COMPLETION_FOLLOWUP_SKIPPED";function PR(t){let e=wR(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($g)){let r=vR(e);return r?bR(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 ${$g}`}}return{outcome:"success"}}function wR(t){let e=t.trim();if(!e)return"";try{return od(JSON.parse(e)).trim()}catch{return e}}function od(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>od(n)).filter(Boolean).join(`
214
+ `);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=od(e[n]);if(o.trim())return o}return""}function vR(t){let e=t.indexOf(Mg);return e<0?void 0:t.slice(e+Mg.length).replace(/^[:\s-]+/,"").split(/\r?\n/,1)[0]?.trim()||"explicitly skipped by wake agent"}function bR(t){return/\balready summarized by completed session\b/i.test(t)}var fa=class{routes=new ma;transport;directNotifications;executor=new la;constructor(e={}){this.transport=e.transport??new ca(e.transportOptions),this.directNotifications=e.directNotifications===void 0?new pa: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,...xe(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,...xe(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,...xe(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,...xe(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,...xe(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",...xe(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?PR: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 ga=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,...xe(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,...xe(p)}),p}};Ee();ir();import{createHash as AR}from"crypto";var TR=1024,ha=class{constructor(e,r,n={}){this.wakeDispatcher=e;this.applyPersistedPatch=r;this.maxCompletedCompletionWakeKeys=Math.max(1,Math.floor(n.maxCompletedCompletionWakeKeys??TR))}wakeDispatcher;applyPersistedPatch;inFlightCompletionWakes=new Set;completedCompletionWakes=new Map;maxCompletedCompletionWakeKeys;dispatch(e,r){let n=this.getDeliveryRef(e),o=this.buildCompletionWakeKey(n,r);if(o){if(this.inFlightCompletionWakes.has(o)||this.completedCompletionWakes.has(o)){r.hooks?.onWakeSkipped?.("duplicate completion follow-up wake already handled");return}this.inFlightCompletionWakes.add(o)}let i=this.buildCompletionWakePatch(r),a=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifySuccess?.trim()),u=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifyFailed?.trim()),p={onNotifyStarted:()=>{this.applyDeliveryState(n,"notifying"),r.hooks?.onNotifyStarted?.()},onNotifySucceeded:()=>{this.applyNotifyDeliveryState(n,a?"wake_pending":"idle",a?i:void 0),a||this.markCompletionWakeFinished(o,!1),r.hooks?.onNotifySucceeded?.()},onNotifyFailed:()=>{this.applyNotifyDeliveryState(n,u?"wake_pending":"failed",u?i:void 0),u||this.markCompletionWakeFinished(o,!1),r.hooks?.onNotifyFailed?.()},onWakeStarted:()=>{this.applyPersistedPatchWithCompletionWake(n,"wake_pending",i,{completionWakeIssuedAt:new Date().toISOString(),completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0,completionWakeSkippedAt:void 0,completionWakeSkipReason:void 0}),r.hooks?.onWakeStarted?.()},onWakeSucceeded:()=>{this.applyPersistedPatchWithCompletionWake(n,"idle",this.buildCompletionWakeSucceededPatch(i),{completionWakeSucceededAt:new Date().toISOString(),completionWakeFailedAt:void 0,completionWakeSkippedAt:void 0,completionWakeSkipReason:void 0}),this.markCompletionWakeFinished(o,!0),r.hooks?.onWakeSucceeded?.()},onWakeSkipped:d=>{this.applyPersistedPatchWithCompletionWake(n,"idle",this.buildCompletionWakeSucceededPatch(i),{completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0,completionWakeSkippedAt:new Date().toISOString(),completionWakeSkipReason:d}),this.markCompletionWakeFinished(o,!0),r.hooks?.onWakeSkipped?.(d)},onWakeFailed:()=>{this.applyPersistedPatchWithCompletionWake(n,"failed",i,{completionWakeFailedAt:new Date().toISOString()}),this.markCompletionWakeFinished(o,!1),r.hooks?.onWakeFailed?.()}};this.wakeDispatcher.dispatchSessionNotification(e,{...r,hooks:p})}notifyWorktreeOutcome(e,r,n={}){let o=this.getDeliveryRef(e),i=u=>Hn({sessionId:o,sessionName:e.name,outcomeLine:r,originThreadLine:vo(e),detailLines:n.detailLines,canonicalStatusDelivered:u}),a=n.summaryWakeRequired??!0;this.dispatch(e,{label:"worktree-outcome",userMessage:r,notifyUser:"always",requireDirectUserNotification:!0,completionWakeSummaryRequired:a,deferConditionalWakeUntilNextTick:!0,wakeMessageOnNotifySuccess:a?i(!0):void 0,wakeMessageOnNotifyFailed:a?i(!1):void 0})}dispose(){this.wakeDispatcher.dispose()}getDeliveryRef(e){return ye(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}}buildCompletionWakeKey(e,r){if(r.completionWakeSummaryRequired!==!0||!e)return;let n=[r.wakeMessage,r.wakeMessageOnNotifySuccess,r.wakeMessageOnNotifyFailed].map(i=>i?.trim()).filter(i=>!!i);if(n.length===0)return;let o=AR("sha256").update(n.join(`
215
+ ---completion-wake---
216
+ `)).digest("hex").slice(0,16);return`${e}:${r.label}:${o}`}markCompletionWakeFinished(e,r){if(e&&(this.inFlightCompletionWakes.delete(e),r))for(this.completedCompletionWakes.delete(e),this.completedCompletionWakes.set(e,!0);this.completedCompletionWakes.size>this.maxCompletedCompletionWakeKeys;){let n=this.completedCompletionWakes.keys().next().value;if(n===void 0)break;this.completedCompletionWakes.delete(n)}}};Pt();import{existsSync as RR}from"fs";var ya=class{getCompletionState(e,r,n,o){return No(e,n,o)?"has-commits":No(e,o,n)?"base-advanced":Kn(r)?"dirty-uncommitted":"no-change"}isResolvedWorktreeEligibleForCleanup(e,r,n){if(!e.worktreePath||!e.workdir||!RR(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&&r-i>=n}};var ka=class{constructor(e,r,n,o){this.pendingQuestions=e;this.dispatchSessionNotification=r;this.clearWaitingTimestamp=n;this.getQuestionButtons=o}pendingQuestions;dispatchSessionNotification;clearWaitingTimestamp;getQuestionButtons;async handleAskUserQuestion(e,r){let i=r?.questions??[];if(i.length===0)throw new Error("AskUserQuestion: no questions in input");let a=i[0],u=a.options??[],p=this.getQuestionButtons(e.id,u),d=`\u2753 [${e.name}] ${a.question}`,l=[`[ASK USER QUESTION] Session "${e.name}" has a question requiring user input.`,"",`Question: ${a.question}`,...u.length>0?["Options:",...u.map((m,c)=>` ${c+1}. ${m.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${e.id}", message="<answer>") with their answer.`].join(`
210
217
  `);return new Promise((m,c)=>{let h=setTimeout(()=>{this.pendingQuestions.delete(e.id),c(new Error(`AskUserQuestion timed out after 600s for session "${e.name}"`))},6e5);h.unref?.(),this.pendingQuestions.set(e.id,{resolve:m,reject:c,questions:i,timeoutHandle:h}),this.dispatchSessionNotification(e,{label:"ask-user-question",userMessage:d,notifyUser:"always",buttons:p,wakeMessageOnNotifySuccess:["AskUserQuestion delivered to the user.",`Session: ${e.name} | ID: ${e.id}`,`Question: ${a.question}`,"Await their selection \u2014 do NOT answer this question yourself."].join(`
211
- `),wakeMessageOnNotifyFailed:l})})}resolveAskUserQuestion(e,r){let n=this.pendingQuestions.get(e);if(!n){console.warn(`[SessionQuestionService] resolveAskUserQuestion: no pending question for session "${e}"`);return}clearTimeout(n.timeoutHandle),this.pendingQuestions.delete(e);let o=n.questions[0],i=o.options??[],a=i[r];if(!a){n.reject(new Error(`AskUserQuestion: invalid option index ${r} (${i.length} options available)`));return}this.clearWaitingTimestamp(e),n.resolve({behavior:"allow",updatedInput:{questions:n.questions,answers:{[o.question]:a.label}}})}dispose(){for(let e of this.pendingQuestions.values())clearTimeout(e.timeoutHandle),e.reject(new Error("SessionManager disposed before AskUserQuestion resolved."));this.pendingQuestions.clear()}};Ee();Bo();var ma=class t{constructor(e,r,n,o){this.buildRoutingProxy=e;this.dispatchNotification=r;this.updatePersistedSession=n;this.getWorktreeDecisionButtons=o}buildRoutingProxy;dispatchNotification;updatePersistedSession;getWorktreeDecisionButtons;static REMINDER_THRESHOLD_MS=10800*1e3;static REMINDER_INTERVAL_MS=10800*1e3;getNextReminderAt(e){let r=new Date(e.pendingWorktreeDecisionSince).getTime();if(this.getWorktreeDecisionReminderStatus(e,r)!=="pending")return;let n=[r+t.REMINDER_THRESHOLD_MS];if(e.worktreeDecisionSnoozedUntil){let o=new Date(e.worktreeDecisionSnoozedUntil).getTime();Number.isFinite(o)&&n.push(o)}if(e.lastWorktreeReminderAt){let o=new Date(e.lastWorktreeReminderAt).getTime();Number.isFinite(o)&&n.push(o+t.REMINDER_INTERVAL_MS)}return Math.max(...n)}sendReminderIfDue(e,r=Date.now()){this.clearResolvedReminderState(e);let n=this.getNextReminderAt(e);if(n==null||n>r)return!1;let o=r-new Date(e.pendingWorktreeDecisionSince).getTime(),i=Math.floor(Math.max(0,o)/(3600*1e3));try{this.sendReminderNotification(e,i)}catch(a){return console.warn(`[SessionReminderService] Failed to send stale-decision reminder for session ${e.name}: ${a instanceof Error?a.message:String(a)}`),!1}for(let a of ct(e))this.updatePersistedSession(a,{lastWorktreeReminderAt:new Date(r).toISOString()});return!0}sendReminderNotification(e,r){let n=this.buildRoutingProxy({id:e.sessionId??e.name??q(e)??e.harnessSessionId,sessionId:e.sessionId,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef,route:e.route});if(e.worktreeStrategy==="delegate"){this.dispatchNotification(n,{label:`worktree-stale-reminder-${e.name}`,wakeMessage:Dp(e,r),notifyUser:"never"});return}let o=[`\u23F0 Reminder: branch \`${e.worktreeBranch??"unknown"}\` is still waiting for a merge decision.`,`Session: ${e.name} | Pending: ${r}h`,"",`agent_merge(session="${e.name}") or agent_pr(session="${e.name}") or agent_worktree_cleanup() to resolve.`].join(`
212
- `);this.dispatchNotification(n,{label:`worktree-stale-reminder-${e.name}`,userMessage:o,notifyUser:"always",buttons:this.getWorktreeDecisionButtons(ye(e)??e.harnessSessionId)})}clearResolvedReminderState(e){if(!e.pendingWorktreeDecisionSince&&!e.lastWorktreeReminderAt&&!e.worktreeDecisionSnoozedUntil||this.getWorktreeDecisionReminderStatus(e)!=="resolved")return!1;let r=!1;for(let n of ct(e))r=this.updatePersistedSession(n,{pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDecisionSnoozedUntil:void 0})||r;return r}getWorktreeDecisionReminderStatus(e,r){if(!e.pendingWorktreeDecisionSince)return"inactive";let n=r??new Date(e.pendingWorktreeDecisionSince).getTime();if(!Number.isFinite(n))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 a=e.worktreeState==="pending_decision"||e.lifecycle==="awaiting_worktree_decision"||e.worktreeLifecycle?.state==="pending_decision",u=e.worktreeState==null&&e.lifecycle==null&&e.worktreeLifecycle?.state==null&&!e.worktreeMerged&&!e.worktreePrUrl;if(!a&&!u)return"inactive";let p=un(e,{activeSession:!1,includePrSync:!1});return p.derivedState==="merged"||p.derivedState==="released"||p.derivedState==="cleanup_failed"?"resolved":"pending"}};Pt();Ee();ir();function Qo(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&nR(t.approvalPromptStatus)}function nR(t){return t==="delivered"||t==="fallback_delivered"}function Yo(t,e){return!t||e==null?!1:!!(t.pendingPlanApproval&&t.approvalState==="pending"&&t.lifecycle==="awaiting_plan_decision"&&(t.actionablePlanDecisionVersion??t.planDecisionVersion)===e)}function Qn(t,e,r=!1){let n="id"in t?t.id:t.sessionId??"unknown-session";return[r?"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: ${n} | Plan v${e??"?"}`,`Wait for their ${r?"explicit reply":"button callback"} \u2014 do NOT approve or reject this plan yourself.`].join(`
213
- `)}function ca(t){let e="id"in t.session?t.session.id:t.session.sessionId??"unknown-session",r=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??"?"}`,r,"","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(`
214
- `)}import{existsSync as oR,readFileSync as iR}from"fs";function sR(t,e){if(t.latestPlanArtifactVersion===e&&t.latestPlanArtifact)return t.latestPlanArtifact;let r=t.planFilePath?.trim();if(!(!r||!oR(r)))try{let n=iR(r,"utf-8").trim();return n?{markdown:n,steps:[]}:void 0}catch{return}}var fa=class{constructor(e){this.deps=e}deps;dispatchPlanApprovalFallback(e,r,n){let o=new Date().toISOString();this.deps.dispatchSessionNotification(e,{label:"plan-approval-fallback",userMessage:Ho({session:e,summary:n}),notifyUser:"always",shouldDispatch:()=>Yo(e,r),hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.deps.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.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:Qn(e,r,!0),wakeMessageOnNotifyFailed:ca({session:e,planDecisionVersion:r,originThreadLine:this.deps.originThreadLine(e)})})}logCompletionWakeDiagnostic(e){console.info(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:!!$i(e)}handleTurnEnd(e,r){if(e.status!=="running"){console.info(`[SessionManager] Suppressing turn-end wake for session ${e.id} (status=${e.status}) \u2014 terminal notification owns the completion path.`);return}if(!e.goalTaskId){if(r||e.pendingPlanApproval){this.emitWaitingForInput(e);return}if(e.worktreeStrategy==="ask"||e.worktreeStrategy==="delegate"){console.info(`[SessionManager] Suppressing turn-complete wake for session ${e.id} (worktreeStrategy=${e.worktreeStrategy}) \u2014 worktree notification will follow.`);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 r={notificationSent:!1,worktreeRemoved:!1};e.worktreePath&&e.originalWorkdir&&(r=await this.deps.handleWorktreeStrategy(e));let n=!1;if(e.worktreePath&&e.originalWorkdir&&e.status==="failed"&&e.costUsd===0&&e.duration<3e4){let u=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath),p=e.worktreeBranch,d=lt(e);console.info(`[SessionManager] Early startup failure for "${e.name}" \u2014 auto-cleaning worktree (cost=$${e.costUsd.toFixed(2)}, duration=${e.duration}ms)`);let l=!1;if(u&&!d&&(l=xt(u,e.worktreePath)),u&&p&&!d&&l&&Jt(u,p),l){for(let m of ct(e))this.deps.updatePersistedSession(m,{worktreePath:void 0,worktreeBranch:void 0});n=!0}}let o=e.worktreeStrategy&&e.worktreeStrategy!=="off"&&e.worktreeStrategy!=="manual";if(!n&&e.worktreePath&&e.originalWorkdir){let u=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath),p=lt(e);r.worktreeRemoved?console.info(`[SessionManager] Worktree already removed for "${e.name}" during strategy handling.`):o?console.info(`[SessionManager] Keeping worktree alive for "${e.name}" (strategy=${e.worktreeStrategy}) \u2014 will be cleaned up on explicit resolution.`):u&&!p&&xt(u,e.worktreePath)}if(e.killReason==="done"){if(r.notificationSent||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 u=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,Je(u,200),n);return}let i=`$${(e.costUsd??0).toFixed(2)}`,a=e.duration;if(e.killReason==="idle-timeout"){let u=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0;if(e.pendingPlanApproval){let p=e.actionablePlanDecisionVersion??e.planDecisionVersion,d=Qo(e,p);if(u==="delegate"){this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",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(`
218
+ `),wakeMessageOnNotifyFailed:l})})}resolveAskUserQuestion(e,r){let n=this.pendingQuestions.get(e);if(!n){console.warn(`[SessionQuestionService] resolveAskUserQuestion: no pending question for session "${e}"`);return}clearTimeout(n.timeoutHandle),this.pendingQuestions.delete(e);let o=n.questions[0],i=o.options??[],a=i[r];if(!a){n.reject(new Error(`AskUserQuestion: invalid option index ${r} (${i.length} options available)`));return}this.clearWaitingTimestamp(e),n.resolve({behavior:"allow",updatedInput:{questions:n.questions,answers:{[o.question]:a.label}}})}dispose(){for(let e of this.pendingQuestions.values())clearTimeout(e.timeoutHandle),e.reject(new Error("SessionManager disposed before AskUserQuestion resolved."));this.pendingQuestions.clear()}};Ee();Uo();var Sa=class t{constructor(e,r,n,o){this.buildRoutingProxy=e;this.dispatchNotification=r;this.updatePersistedSession=n;this.getWorktreeDecisionButtons=o}buildRoutingProxy;dispatchNotification;updatePersistedSession;getWorktreeDecisionButtons;static REMINDER_THRESHOLD_MS=10800*1e3;static REMINDER_INTERVAL_MS=10800*1e3;getNextReminderAt(e){let r=new Date(e.pendingWorktreeDecisionSince).getTime();if(this.getWorktreeDecisionReminderStatus(e,r)!=="pending")return;let n=[r+t.REMINDER_THRESHOLD_MS];if(e.worktreeDecisionSnoozedUntil){let o=new Date(e.worktreeDecisionSnoozedUntil).getTime();Number.isFinite(o)&&n.push(o)}if(e.lastWorktreeReminderAt){let o=new Date(e.lastWorktreeReminderAt).getTime();Number.isFinite(o)&&n.push(o+t.REMINDER_INTERVAL_MS)}return Math.max(...n)}sendReminderIfDue(e,r=Date.now()){this.clearResolvedReminderState(e);let n=this.getNextReminderAt(e);if(n==null||n>r)return!1;let o=r-new Date(e.pendingWorktreeDecisionSince).getTime(),i=Math.floor(Math.max(0,o)/(3600*1e3));try{this.sendReminderNotification(e,i)}catch(a){return console.warn(`[SessionReminderService] Failed to send stale-decision reminder for session ${e.name}: ${a instanceof Error?a.message:String(a)}`),!1}for(let a of lt(e))this.updatePersistedSession(a,{lastWorktreeReminderAt:new Date(r).toISOString()});return!0}sendReminderNotification(e,r){let n=this.buildRoutingProxy({id:e.sessionId??e.name??q(e)??e.harnessSessionId,sessionId:e.sessionId,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef,route:e.route});if(e.worktreeStrategy==="delegate"){this.dispatchNotification(n,{label:`worktree-stale-reminder-${e.name}`,wakeMessage:Kp(e,r),notifyUser:"never"});return}let o=[`\u23F0 Reminder: branch \`${e.worktreeBranch??"unknown"}\` is still waiting for a merge decision.`,`Session: ${e.name} | Pending: ${r}h`,"",`agent_merge(session="${e.name}") or agent_pr(session="${e.name}") or agent_worktree_cleanup() to resolve.`].join(`
219
+ `);this.dispatchNotification(n,{label:`worktree-stale-reminder-${e.name}`,userMessage:o,notifyUser:"always",buttons:this.getWorktreeDecisionButtons(ye(e)??e.harnessSessionId)})}clearResolvedReminderState(e){if(!e.pendingWorktreeDecisionSince&&!e.lastWorktreeReminderAt&&!e.worktreeDecisionSnoozedUntil||this.getWorktreeDecisionReminderStatus(e)!=="resolved")return!1;let r=!1;for(let n of lt(e))r=this.updatePersistedSession(n,{pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDecisionSnoozedUntil:void 0})||r;return r}getWorktreeDecisionReminderStatus(e,r){if(!e.pendingWorktreeDecisionSince)return"inactive";let n=r??new Date(e.pendingWorktreeDecisionSince).getTime();if(!Number.isFinite(n))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 a=e.worktreeState==="pending_decision"||e.lifecycle==="awaiting_worktree_decision"||e.worktreeLifecycle?.state==="pending_decision",u=e.worktreeState==null&&e.lifecycle==null&&e.worktreeLifecycle?.state==null&&!e.worktreeMerged&&!e.worktreePrUrl;if(!a&&!u)return"inactive";let p=un(e,{activeSession:!1,includePrSync:!1});return p.derivedState==="merged"||p.derivedState==="released"||p.derivedState==="cleanup_failed"?"resolved":"pending"}};Pt();Ee();ir();function Xo(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&CR(t.approvalPromptStatus)}function CR(t){return t==="delivered"||t==="fallback_delivered"}function ei(t,e){return!t||e==null?!1:!!(t.pendingPlanApproval&&t.approvalState==="pending"&&t.lifecycle==="awaiting_plan_decision"&&(t.actionablePlanDecisionVersion??t.planDecisionVersion)===e)}function Qn(t,e,r=!1){let n="id"in t?t.id:t.sessionId??"unknown-session";return[r?"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: ${n} | Plan v${e??"?"}`,`Wait for their ${r?"explicit reply":"button callback"} \u2014 do NOT approve or reject this plan yourself.`].join(`
220
+ `)}function Ia(t){let e="id"in t.session?t.session.id:t.session.sessionId??"unknown-session",r=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??"?"}`,r,"","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(`
221
+ `)}import{existsSync as ER,readFileSync as $R}from"fs";function MR(t,e){if(t.latestPlanArtifactVersion===e&&t.latestPlanArtifact)return t.latestPlanArtifact;let r=t.planFilePath?.trim();if(!(!r||!ER(r)))try{let n=$R(r,"utf-8").trim();return n?{markdown:n,steps:[]}:void 0}catch{return}}var xa=class{constructor(e){this.deps=e}deps;dispatchPlanApprovalFallback(e,r,n){let o=new Date().toISOString();this.deps.dispatchSessionNotification(e,{label:"plan-approval-fallback",userMessage:Qo({session:e,summary:n}),notifyUser:"always",shouldDispatch:()=>ei(e,r),hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.deps.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.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:Qn(e,r,!0),wakeMessageOnNotifyFailed:Ia({session:e,planDecisionVersion:r,originThreadLine:this.deps.originThreadLine(e)})})}logCompletionWakeDiagnostic(e){console.info(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:!!_i(e)}handleTurnEnd(e,r){if(e.status!=="running"){console.info(`[SessionManager] Suppressing turn-end wake for session ${e.id} (status=${e.status}) \u2014 terminal notification owns the completion path.`);return}if(!e.goalTaskId){if(r||e.pendingPlanApproval){this.emitWaitingForInput(e);return}if(e.worktreeStrategy==="ask"||e.worktreeStrategy==="delegate"){console.info(`[SessionManager] Suppressing turn-complete wake for session ${e.id} (worktreeStrategy=${e.worktreeStrategy}) \u2014 worktree notification will follow.`);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 r={notificationSent:!1,worktreeRemoved:!1};e.worktreePath&&e.originalWorkdir&&(r=await this.deps.handleWorktreeStrategy(e));let n=!1;if(e.worktreePath&&e.originalWorkdir&&e.status==="failed"&&e.costUsd===0&&e.duration<3e4){let u=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath),p=e.worktreeBranch,d=mt(e);console.info(`[SessionManager] Early startup failure for "${e.name}" \u2014 auto-cleaning worktree (cost=$${e.costUsd.toFixed(2)}, duration=${e.duration}ms)`);let l=!1;if(u&&!d&&(l=xt(u,e.worktreePath)),u&&p&&!d&&l&&Jt(u,p),l){for(let m of lt(e))this.deps.updatePersistedSession(m,{worktreePath:void 0,worktreeBranch:void 0});n=!0}}let o=e.worktreeStrategy&&e.worktreeStrategy!=="off"&&e.worktreeStrategy!=="manual";if(!n&&e.worktreePath&&e.originalWorkdir){let u=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath),p=mt(e);r.worktreeRemoved?console.info(`[SessionManager] Worktree already removed for "${e.name}" during strategy handling.`):o?console.info(`[SessionManager] Keeping worktree alive for "${e.name}" (strategy=${e.worktreeStrategy}) \u2014 will be cleaned up on explicit resolution.`):u&&!p&&xt(u,e.worktreePath)}if(r.notificationSent){console.info(`[SessionManager] Suppressing generic terminal notification for session ${e.id} because worktree strategy handling already sent the authoritative outcome notification.`);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 u=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,Je(u,200),n);return}let i=`$${(e.costUsd??0).toFixed(2)}`,a=e.duration;if(e.killReason==="idle-timeout"){let u=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0;if(e.pendingPlanApproval){let p=e.actionablePlanDecisionVersion??e.planDecisionVersion,d=Xo(e,p);if(u==="delegate"){this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",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(`
215
222
  `),notifyUser:"never"}),this.deps.clearRetryTimersForSession(e.id);return}if(u==="ask"&&d){this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",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${p??"?"}`,this.deps.originThreadLine(e),"Do NOT post another approval summary unless canonical delivery is known to be missing."].join(`
216
223
  `)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",userMessage:[`\u{1F4CB} [${e.name}] Plan v${p??"?"} still awaiting approval after idle timeout | ${i} | ${Ft(a)}`,"","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(`
217
- `),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}] ${Vo(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"&&Qo(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=sR(e,n),d=Wp({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:()=>Yo(e,n),onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,n,l),wakeMessageOnNotifySuccess:Qn(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=Op({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=$p({session:e,originThreadLine:this.deps.originThreadLine(e),preview:r}),i;this.deps.dispatchSessionNotification(e,{label:"completed",userMessage:o.userMessage,notifyUser:"always",completionWakeSummaryRequired:n,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=Mp({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 aR}from"fs";var ga=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=lt(o);!d&&i&&aR(i)&&xt(a,i,{destructive:!0}),u&&Jt(a,u);for(let m of ct(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:ye(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 ct(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:ye(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 xg=new Set(["starting","running"]),ha=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>xg.has(e.status)).length}uniqueName(e){let r=new Set([...this.sessions.values()].filter(o=>xg.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 ya=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 Sa=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:Lp({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}=e,u=Fp(i),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(`
224
+ `),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}] ${Jo(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"&&Xo(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=MR(e,n),d=Jp({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:()=>ei(e,n),onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,n,l),wakeMessageOnNotifySuccess:Qn(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=Up({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=Np({session:e,originThreadLine:this.deps.originThreadLine(e),preview:r}),i;this.deps.dispatchSessionNotification(e,{label:"completed",userMessage:o.userMessage,notifyUser:"always",completionWakeSummaryRequired:n,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=Bp({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 OR}from"fs";var Pa=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&&OR(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:ye(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:ye(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 Og=new Set(["starting","running"]),wa=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>Og.has(e.status)).length}uniqueName(e){let r=new Set([...this.sessions.values()].filter(o=>Og.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 va=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 ba=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:jp({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(`
218
225
  `),notifyUser:"always",buttons:a,wakeMessageOnNotifySuccess:["Worktree decision buttons delivered to the user.",`Session: ${r.name} | ID: ${r.id}`,l,"Wait for their button callback \u2014 do NOT act on this worktree yourself."].join(`
219
226
  `),wakeMessageOnNotifyFailed:[`\u{1F500} Worktree decision required for session \`${r.name}\``,"",l,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`].join(`
220
- `)}}buildDelegateNotification(e){let{session:r,branchName:n,baseBranch:o,diffSummary:i,originThreadLine:a}=e,u=i.commitMessages.slice(0,5).map(l=>`\u2022 ${l.hash} ${l.message} (${l.author})`),p=i.commits>5?`...and ${i.commits-5} more`:void 0,d=r.prompt?r.prompt.slice(0,500):"(no prompt)";return{label:"worktree-delegate",wakeMessage:_p({sessionName:r.name,sessionId:r.id,branchName:n,baseBranch:o,promptSnippet:d,commitLines:u,moreNote:p,originThreadLine:a,diffSummary:i}),notifyUser:"never"}}};function Pg(t,e=1e3){let r=!Number.isFinite(e),n=typeof t.getOutput=="function"?t.getOutput():[],o=r?n.join(`
221
- `):uR(t);return r?o:o.length>e?wg(t)?Zi(o,e):tc(o,e):o}function uR(t){let e=typeof t.getOutput=="function"?t.getOutput():[],r=e.join(`
222
- `).trim();return r?wg(t)?pR(r)??r:e.slice(-20).join(`
223
- `):""}function wg(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 pR(t){let r=t.split(/\n\s*\n+/).map(n=>n.trim()).filter(n=>/[A-Za-z0-9]/.test(n)).at(-1);if(r)return r.length>=120||r.includes(`
224
- `)?r:void 0}ir();Pt();ze();import{unlinkSync as dR}from"fs";var ka=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();Bo();Pt();var vg=10080*60*1e3,lR=300*1e3,bg="tmp-output:cleanup";function mR(t){return t instanceof Error?t.message:String(t)}var Ia=class{constructor(e){this.deps=e}deps;scheduler=new ka;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+vg,()=>{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<vg))try{if(!e.worktreePath&&!lt(e))return;let u=this.deps.resolveWorktreeRepoDir(e.workdir,e.worktreePath);if(!u)return;let p=lt(e)?!1:xt(u,e.worktreePath);if(!lt(e)&&!p)return;for(let d of ct(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}: ${mR(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(bg);let r=this.deps.store.getNextTmpOutputCleanupAt(e);r!=null&&this.schedule(bg,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()+lR))})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.deps.store.hasOutputPathReference(e)))try{dR(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"}};var Ag=new Set(["completed","failed","killed"]),cR=new Set(["starting","running"]),fR=5e3,xa=class{registry;sessions;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueue=new Jn;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 ha,this.sessions=this.registry.sessions,this.store=new ea(n.store),this.metrics=new ta,this.wakeDispatcher=new aa,this.interactions=new ua(this.store.actionTokenStore,Pr),this.references=new Ks(this.sessions,this.store),this.stateSync=new Ws({store:this.store,sessions:this.sessions,resolveSession:o=>this.references.resolveActive(o)}),this.notifications=new pa(this.wakeDispatcher,(o,i)=>this.stateSync.applySessionPatch(o,i)),this.worktrees=new da,this.restore=new Us(o=>this.store.getPersistedSession(o)),this.worktreeMessages=new Sa,this.worktreeStrategy=new Hs({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"),worktreeMessages:this.worktreeMessages,enqueueMerge:(o,i,a)=>this.enqueueMerge(o,i,a),mergeBranch:gs,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(()=>(Os(),rf));return{success:(await a().execute("auto-pr",{session:o.id,base_branch:i}))?.meta?.success===!0}}}),this.questions=new la(this.pendingAskUserQuestions,(o,i)=>this.dispatchSessionNotification(o,i),o=>{this.lastWaitingEventTimestamps.delete(o)},(o,i)=>this.interactions.getQuestionButtons(o,i)),this.reminders=new ma(o=>this.buildRoutingProxy(o),(o,i)=>this.notifications.dispatch(o,i),(o,i)=>this.updatePersistedSession(o,i),o=>this.getWorktreeDecisionButtons(o)),this.maintenance=new Ia({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 fa({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 ga({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 ya({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||Xm(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 Ss({...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(Ag.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}Ag.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 Ei({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 Yo(n,r)}dispatchPlanApprovalFallback(e,r,n){let o=new Date().toISOString();this.notifications.dispatch(e,{label:"plan-approval-fallback",userMessage:Ho({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:Qn(e,r,!0),wakeMessageOnNotifyFailed:ca({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=Bp(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=ye(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(Qo(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(`
225
- `);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:Qn({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:ye(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||!Bs(e,r))||!r?e:ls(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,Gs({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(`
226
- `),buttons:[[this.makeActionButton(r,"worktree-create-pr","Open PR")]]})}getStoppedStatusLabel(e){return Vo(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=this.buildRoutingProxy({id:e.sessionId??e.id,route:e.route});o.originChannel=e.originChannel,o.originThreadId=e.originThreadId,o.originSessionKey=e.originSessionKey,this.dispatchSessionNotification(o,{label:n,userMessage:r,notifyUser:"always"})}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<fR?!1:(this.lastWaitingEventTimestamps.set(e,r),!0)}originThreadLine(e){return Mi(e)}extractLastOutputLine(e){return e.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(e,r=1e3){return Pg(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())cR.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()}};le();ze();var Rg=class{#t;#r;#e=new Map;constructor(t){this.#t=Tg(t,1),this.#r=this.#t}get maxEntries(){return this.#r}get size(){return this.#e.size}setMaxEntriesForTest(t){this.#r=typeof t=="number"?Tg(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 Tg(t,e){return!Number.isFinite(t)||t<=0?e:Math.max(1,Math.floor(t))}var gR="\\x1b\\[[\\x20-\\x3f]*[\\x40-\\x7e]",hR="\\x1b\\][^\\x07\\x1b]*(?:\\x1b\\\\|\\x07)",YU=new RegExp(gR,"g"),ZU=new RegExp(hR,"g"),XU=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;var ee={};Ct(ee,{Match:()=>yR});function yR(t,e){return e[t.length]?.(...t)??(()=>{throw Error("Invalid Arguments")})()}var s={};Ct(s,{Entries:()=>BR,EntriesRegExp:()=>qR,Every:()=>LR,EveryAll:()=>FR,GraphemeCount:()=>OR,HasPropertyKey:()=>NR,IsArray:()=>Xo,IsAsyncIterator:()=>wR,IsBigInt:()=>Zo,IsBoolean:()=>Dg,IsClassInstance:()=>$R,IsConstructor:()=>vR,IsDeepEqual:()=>td,IsEqual:()=>J,IsFunction:()=>Lg,IsGreaterEqualThan:()=>Ng,IsGreaterThan:()=>RR,IsInteger:()=>Xp,IsIterator:()=>bR,IsLessEqualThan:()=>Fg,IsLessThan:()=>CR,IsMaxLength:()=>_R,IsMinLength:()=>DR,IsMultipleOf:()=>ER,IsNull:()=>va,IsNumber:()=>ba,IsObject:()=>mn,IsObjectNotArray:()=>AR,IsString:()=>Aa,IsSymbol:()=>TR,IsUndefined:()=>ed,IsUnsafePropertyKey:()=>qg,IsValueLike:()=>MR,Keys:()=>wa,Symbols:()=>UR,TakeLeft:()=>Ta,Values:()=>WR});function Cr(t,e,r){return t>=e&&t<=r}function Cg(t){return Cr(t,127462,127487)}function SR(t){return Cr(t,65024,65039)}function kR(t){return Cr(t,768,879)||Cr(t,6832,6911)||Cr(t,7616,7679)||Cr(t,65056,65071)}function Pa(t){return t>65535?2:1}function Eg(t,e){for(;e<t.length;){let r=t.codePointAt(e);if(kR(r)||SR(r))e+=Pa(r);else break}return e}function Zp(t,e){let r=t.codePointAt(e),n=e+Pa(r);for(n=Eg(t,n);n<t.length-1&&t[n]==="\u200D";){let o=t.codePointAt(n+1);n+=1+Pa(o),n=Eg(t,n)}return Cg(r)&&n<t.length&&Cg(t.codePointAt(n))&&(n+=Pa(t.codePointAt(n))),n}function $g(t){return Cr(t,55296,56319)||Cr(t,768,879)||t===8205}function Mg(t){let e=0,r=0;for(;r<t.length;)r=Zp(t,r),e++;return e}function IR(t,e){if(e===0)return!0;let r=0,n=0;for(;n<t.length;)if(n=Zp(t,n),r++,r>=e)return!0;return!1}function xR(t,e){let r=0,n=0;for(;n<t.length;)if(n=Zp(t,n),r++,r>e)return!1;return!0}function Og(t,e){if(e===0)return!0;let r=0;for(;r<t.length;){if($g(t.charCodeAt(r)))return IR(t,e);if(r++,r>=e)return!0}return!1}function _g(t,e){let r=0;for(;r<t.length;){if($g(t.charCodeAt(r)))return xR(t,e);if(r++,r>e)return!1}return!0}function Xo(t){return Array.isArray(t)}function wR(t){return mn(t)&&Symbol.asyncIterator in t}function Zo(t){return J(typeof t,"bigint")}function Dg(t){return J(typeof t,"boolean")}function vR(t){if(ed(t)||!Lg(t))return!1;let e=Function.prototype.toString.call(t);return!!(/^class\s/.test(e)||/\[native code\]/.test(e))}function Lg(t){return J(typeof t,"function")}function Xp(t){return Number.isInteger(t)}function bR(t){return mn(t)&&Symbol.iterator in t}function va(t){return J(t,null)}function ba(t){return Number.isFinite(t)}function AR(t){return mn(t)&&!Xo(t)}function mn(t){return J(typeof t,"object")&&!va(t)}function Aa(t){return J(typeof t,"string")}function TR(t){return J(typeof t,"symbol")}function ed(t){return J(t,void 0)}function J(t,e){return t===e}function RR(t,e){return t>e}function CR(t,e){return t<e}function Fg(t,e){return t<=e}function Ng(t,e){return t>=e}function ER(t,e){if(Zo(t)||Zo(e))return BigInt(t)%BigInt(e)===0n;let r=1e-10;if(!ba(t)||Xp(t)&&1/e%1===0)return!0;let n=t%e;return Math.min(Math.abs(n),Math.abs(n-e))<r}function $R(t){if(!mn(t))return!1;let e=globalThis.Object.getPrototypeOf(t);return va(e)?!1:J(typeof e.constructor,"function")&&!(J(e.constructor,globalThis.Object)||J(e.constructor.name,"Object"))}function MR(t){return Zo(t)||Dg(t)||va(t)||ba(t)||Aa(t)||ed(t)}function OR(t){return Mg(t)}function _R(t,e){return _g(t,e)}function DR(t,e){return Og(t,e)}function LR(t,e,r){for(let n=e;n<t.length;n++)if(!r(t[n],n))return!1;return!0}function FR(t,e,r){let n=!0;for(let o=e;o<t.length;o++)r(t[o],o)||(n=!1);return n}function Ta(t,e,r){return J(t.length,0)?r():e(t[0],t.slice(1))}function qg(t){return J(t,"__proto__")||J(t,"constructor")||J(t,"prototype")}function NR(t,e){return qg(e)?Object.prototype.hasOwnProperty.call(t,e):e in t}function qR(t){return wa(t).map(e=>[new RegExp(`^${e}$`),t[e]])}function BR(t){return Object.entries(t)}function wa(t){return Object.getOwnPropertyNames(t)}function UR(t){return Object.getOwnPropertySymbols(t)}function WR(t){return Object.values(t)}function KR(t,e){if(!mn(e))return!1;let r=wa(t);return J(r.length,wa(e).length)&&r.every(n=>td(t[n],e[n]))}function jR(t,e){return Xo(e)&&J(t.length,e.length)&&t.every((r,n)=>td(t[n],e[n]))}function td(t,e){return Xo(t)?jR(t,e):mn(t)?KR(t,e):J(t,e)}var nt={};Ct(nt,{IsBigInt64Array:()=>oC,IsBigUint64Array:()=>iC,IsBoolean:()=>GR,IsDate:()=>aC,IsFloat32Array:()=>rC,IsFloat64Array:()=>nC,IsInt16Array:()=>ZR,IsInt32Array:()=>eC,IsInt8Array:()=>JR,IsMap:()=>pC,IsNumber:()=>VR,IsRegExp:()=>sC,IsSet:()=>uC,IsString:()=>HR,IsTypeArray:()=>zR,IsUint16Array:()=>XR,IsUint32Array:()=>tC,IsUint8Array:()=>QR,IsUint8ClampedArray:()=>YR});function GR(t){return t instanceof Boolean}function VR(t){return t instanceof Number}function HR(t){return t instanceof String}function zR(t){return globalThis.ArrayBuffer.isView(t)}function JR(t){return t instanceof globalThis.Int8Array}function QR(t){return t instanceof globalThis.Uint8Array}function YR(t){return t instanceof globalThis.Uint8ClampedArray}function ZR(t){return t instanceof globalThis.Int16Array}function XR(t){return t instanceof globalThis.Uint16Array}function eC(t){return t instanceof globalThis.Int32Array}function tC(t){return t instanceof globalThis.Uint32Array}function rC(t){return t instanceof globalThis.Float32Array}function nC(t){return t instanceof globalThis.Float64Array}function oC(t){return t instanceof globalThis.BigInt64Array}function iC(t){return t instanceof globalThis.BigUint64Array}function sC(t){return t instanceof globalThis.RegExp}function aC(t){return t instanceof globalThis.Date}function uC(t){return t instanceof globalThis.Set}function pC(t){return t instanceof globalThis.Map}function lC(t){return s.IsObject(t)&&s.HasPropertyKey(t,"check")&&s.HasPropertyKey(t,"errors")&&s.IsFunction(t.check)&&s.IsFunction(t.errors)}function rd(t){return s.HasPropertyKey(t,"~guard")&&lC(t["~guard"])}function nd(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 Ra(t){return s.IsBoolean(t)}function M(t){return Mt(t)||Ra(t)}function od(t){return s.HasPropertyKey(t,"additionalItems")&&M(t.additionalItems)}function sr(t){return s.HasPropertyKey(t,"additionalProperties")&&M(t.additionalProperties)}function id(t){return s.HasPropertyKey(t,"allOf")&&s.IsArray(t.allOf)&&t.allOf.every(e=>M(e))}function ei(t){return s.HasPropertyKey(t,"$anchor")&&s.IsString(t.$anchor)}function sd(t){return s.HasPropertyKey(t,"anyOf")&&s.IsArray(t.anyOf)&&t.anyOf.every(e=>M(e))}function ad(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 ud(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 pd(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 dd(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 ld(t){return s.HasPropertyKey(t,"$dynamicRef")&&s.IsString(t.$dynamicRef)}function md(t){return s.HasPropertyKey(t,"else")&&M(t.else)}function cd(t){return s.HasPropertyKey(t,"enum")&&s.IsArray(t.enum)}function fd(t){return s.HasPropertyKey(t,"exclusiveMaximum")&&(s.IsNumber(t.exclusiveMaximum)||s.IsBigInt(t.exclusiveMaximum))}function Yn(t){return s.HasPropertyKey(t,"exclusiveMinimum")&&(s.IsNumber(t.exclusiveMinimum)||s.IsBigInt(t.exclusiveMinimum))}function Ca(t){return s.HasPropertyKey(t,"format")&&s.IsString(t.format)}function ur(t){return s.HasPropertyKey(t,"$id")&&s.IsString(t.$id)}function gd(t){return s.HasPropertyKey(t,"if")&&M(t.if)}function Zn(t){return s.HasPropertyKey(t,"items")&&(M(t.items)||s.IsArray(t.items)&&t.items.every(e=>M(e)))}function hd(t){return Zn(t)&&s.IsArray(t.items)}function yd(t){return s.HasPropertyKey(t,"maximum")&&(s.IsNumber(t.maximum)||s.IsBigInt(t.maximum))}function Sd(t){return s.HasPropertyKey(t,"maxContains")&&s.IsNumber(t.maxContains)}function Ea(t){return s.HasPropertyKey(t,"maxItems")&&s.IsNumber(t.maxItems)}function kd(t){return s.HasPropertyKey(t,"maxLength")&&s.IsNumber(t.maxLength)}function Id(t){return s.HasPropertyKey(t,"maxProperties")&&s.IsNumber(t.maxProperties)}function Xn(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 ti(t){return s.HasPropertyKey(t,"minItems")&&s.IsNumber(t.minItems)}function $a(t){return s.HasPropertyKey(t,"minLength")&&s.IsNumber(t.minLength)}function Ma(t){return s.HasPropertyKey(t,"minProperties")&&s.IsNumber(t.minProperties)}function xd(t){return s.HasPropertyKey(t,"multipleOf")&&(s.IsNumber(t.multipleOf)||s.IsBigInt(t.multipleOf))}function Pd(t){return s.HasPropertyKey(t,"not")&&M(t.not)}function wd(t){return s.HasPropertyKey(t,"oneOf")&&s.IsArray(t.oneOf)&&t.oneOf.every(e=>M(e))}function Oa(t){return s.HasPropertyKey(t,"pattern")&&(s.IsString(t.pattern)||t.pattern instanceof RegExp)}function ri(t){return s.HasPropertyKey(t,"patternProperties")&&s.IsObject(t.patternProperties)&&Object.values(t.patternProperties).every(e=>M(e))}function eo(t){return s.HasPropertyKey(t,"prefixItems")&&s.IsArray(t.prefixItems)&&t.prefixItems.every(e=>M(e))}function ni(t){return s.HasPropertyKey(t,"properties")&&s.IsObject(t.properties)&&Object.values(t.properties).every(e=>M(e))}function vd(t){return s.HasPropertyKey(t,"propertyNames")&&(s.IsObject(t.propertyNames)||M(t.propertyNames))}function mC(t){return s.HasPropertyKey(t,"$recursiveAnchor")&&s.IsBoolean(t.$recursiveAnchor)}function _a(t){return mC(t)&&s.IsEqual(t.$recursiveAnchor,!0)}function bd(t){return s.HasPropertyKey(t,"$recursiveRef")&&s.IsString(t.$recursiveRef)}function Ad(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 Td(t){return s.HasPropertyKey(t,"then")&&M(t.then)}function Rd(t){return s.HasPropertyKey(t,"type")&&(s.IsString(t.type)||s.IsArray(t.type)&&t.type.every(e=>s.IsString(e)))}function oi(t){return s.HasPropertyKey(t,"uniqueItems")&&s.IsBoolean(t.uniqueItems)}function Da(t){return s.HasPropertyKey(t,"unevaluatedItems")&&M(t.unevaluatedItems)}function La(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}},ii=class extends ot{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},De=class extends ii{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};function Bg(t,e,r,n){return r["~guard"].check(n)}function Ug(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:()=>EC,HashCode:()=>Hg});function Y(){throw new Error("Unreachable")}function cC(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 fC(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 ro=BigInt("14695981039346656037"),[gC,hC]=[BigInt("1099511628211"),BigInt("18446744073709551616")],yC=Array.from({length:256}).map((t,e)=>BigInt(e)),jg=new Float64Array(1),Gg=new DataView(jg.buffer),Vg=new Uint8Array(jg.buffer);function Ue(t){ro=ro^yC[t],ro=ro*gC%hC}function SC(t){Ue(it.Array);for(let e of t)$r(e)}function kC(t){Ue(it.BigInt),Gg.setBigInt64(0,t);for(let e of Vg)Ue(e)}function Wg(t){Ue(it.Boolean),Ue(t?1:0)}function IC(t){Ue(it.Constructor),$r(t.toString())}function xC(t){Ue(it.Date),$r(t.getTime())}function PC(t){Ue(it.Function),$r(t.toString())}function wC(t){Ue(it.Null)}function Kg(t){Ue(it.Number),Gg.setFloat64(0,t,!0);for(let e of Vg)Ue(e)}function vC(t){Ue(it.Object);for(let e of cC(t).sort())$r(e),$r(t[e])}function bC(t){Ue(it.RegExp),Cd(t.toString())}var AC=new TextEncoder;function Cd(t){Ue(it.String);for(let e of AC.encode(t))Ue(e)}function TC(t){Ue(it.Symbol),$r(t.toString())}function RC(t){Ue(it.TypeArray);let e=new Uint8Array(t.buffer);for(let r=0;r<e.length;r++)Ue(e[r])}function CC(t){return Ue(it.Undefined)}function $r(t){return nt.IsTypeArray(t)?RC(t):nt.IsDate(t)?xC(t):nt.IsRegExp(t)?bC(t):nt.IsBoolean(t)?Wg(t.valueOf()):nt.IsString(t)?Cd(t.valueOf()):nt.IsNumber(t)?Kg(t.valueOf()):fC(t)?Kg(t):s.IsArray(t)?SC(t):s.IsBoolean(t)?Wg(t):s.IsBigInt(t)?kC(t):s.IsConstructor(t)?IC(t):s.IsNull(t)?wC(t):s.IsObject(t)?vC(t):s.IsString(t)?Cd(t):s.IsSymbol(t)?TC(t):s.IsUndefined(t)?CC(t):s.IsFunction(t)?PC(t):Y()}function Hg(t){return ro=BigInt("14695981039346656037"),$r(t),ro}function EC(t){return Hg(t).toString(16).padStart(16,"0")}function zg(t,e,r,n){return s.Every(r["~refine"],0,(o,i)=>o.check(n))}function Jg(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 Qg(t){return Zn(t)&&s.IsArray(t.items)}function Yg(t,e,r,n){return Qg(r)?n.every((i,a)=>s.IsLessThan(a,r.items.length)||vt(t,e,r.additionalItems,i)&&e.AddIndex(a)):!0}function Zg(t,e,r,n,o,i){return Qg(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 $C(t){return`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Xg(t){let e=[];return ri(t)&&e.push(...s.Keys(t.patternProperties)),ni(t)&&e.push(...s.Keys(t.properties).map($C)),s.IsEqual(e.length,0)?"(?!)":`(${e.join("|")})`}function eh(t,e,r,n){let o=new RegExp(Xg(r));return s.Every(s.Keys(n),0,(a,u)=>o.test(a)||vt(t,e,r.additionalProperties,n[a])&&e.AddKey(a))}function th(t,e,r,n,o,i){let a=new RegExp(Xg(o)),u=[];return s.EveryAll(s.Keys(i),0,(d,l)=>{let m=`${r}/additionalProperties`,c=`${n}/${d}`,h=new De,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 rh(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 nh(t,e,r,n,o,i){let a=[],u=o.allOf.reduce((d,l,m)=>{let c=`${r}/allOf/${m}`,h=new De,y=pe(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 oh(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 ih(t,e,r,n,o,i){let a=[],u=o.anyOf.reduce((d,l,m)=>{let c=new De,h=`${r}/anyOf/${m}`,y=pe(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 $d(t,e,r,n){return r}function sh(t,e,r,n,o,i){return $d(t,e,o,i)||e.AddError({keyword:"boolean",schemaPath:r,instancePath:n,params:{}})}function Md(t,e,r,n){return s.IsValueLike(r.const)?s.IsEqual(n,r.const):s.IsDeepEqual(n,r.const)}function ah(t,e,r,n,o,i){return Md(t,e,o,i)||e.AddError({keyword:"const",schemaPath:r,instancePath:n,params:{allowedValue:o.const}})}function MC(t){return!(fn(t)&&s.IsEqual(t.minContains,0))}function Od(t,e,r,n){return MC(r)?!s.IsEqual(n.length,0)&&n.some(o=>z(t,e,r.contains,o)):!0}function uh(t,e,r,n,o,i){return Od(t,e,o,i)||e.AddError({keyword:"contains",schemaPath:r,instancePath:n,params:{minContains:1}})}function ph(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 dh(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}})):pe(t,e,l,n,d,i))});return a||u}function lh(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 mh(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 ch(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 fh(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)||pe(t,e,l,n,d,i)});return a||u}function gh(t,e,r,n){let o=t.DynamicRef(r)??!1;return M(o)&&z(t,e,o,n)}function hh(t,e,r,n,o,i){let a=t.DynamicRef(o)??!1;return M(a)&&pe(t,e,"#",n,a,i)}function Ld(t,e,r,n){return r.enum.some(o=>s.IsValueLike(o)?s.IsEqual(n,o):s.IsDeepEqual(n,o))}function yh(t,e,r,n,o,i){return Ld(t,e,o,i)||e.AddError({keyword:"enum",schemaPath:r,instancePath:n,params:{allowedValues:o.enum}})}function Fd(t,e,r,n){return s.IsLessThan(n,r.exclusiveMaximum)}function Sh(t,e,r,n,o,i){return Fd(t,e,o,i)||e.AddError({keyword:"exclusiveMaximum",schemaPath:r,instancePath:n,params:{comparison:"<",limit:o.exclusiveMaximum}})}function Nd(t,e,r,n){return s.IsGreaterThan(n,r.exclusiveMinimum)}function kh(t,e,r,n,o,i){return Nd(t,e,o,i)||e.AddError({keyword:"exclusiveMinimum",schemaPath:r,instancePath:n,params:{comparison:">",limit:o.exclusiveMinimum}})}var yn={};Ct(yn,{Clear:()=>Ch,Entries:()=>fE,Get:()=>yE,Has:()=>hE,IsDate:()=>no,IsDateTime:()=>Fa,IsDuration:()=>Na,IsEmail:()=>qa,IsHostname:()=>Ba,IsIPv4:()=>Ka,IsIPv6:()=>ja,IsIdnEmail:()=>Ua,IsIdnHostname:()=>Wa,IsIri:()=>Va,IsIriReference:()=>Ga,IsJsonPointer:()=>za,IsJsonPointerUriFragment:()=>Ha,IsRegex:()=>Ja,IsRelativeJsonPointer:()=>Qa,IsTime:()=>oo,IsUri:()=>eu,IsUriReference:()=>Ya,IsUriTemplate:()=>Za,IsUrl:()=>tu,IsUuid:()=>ru,Reset:()=>Eh,Set:()=>gE,Test:()=>SE});var OC=[0,31,28,31,30,31,30,31,31,30,31,30,31],_C=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function DC(t){return t%4===0&&(t%100!==0||t%400===0)}function no(t){let e=_C.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&&DC(r)?29:OC[n])}var LC=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function oo(t,e=!0){let r=LC.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 Fa(t,e=!0){let r=t.split(/T/i);return r.length===2&&no(r[0])&&oo(r[1],e)}var FC=/^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 Na(t){return FC.test(t)}var NC=/^(?!.*\.\.)[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 qa(t){return NC.test(t)}function qC(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 Ih(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=qC(n-u,l,u===0),r+=Math.floor(n/l),n%=l,e.splice(n,0,r),n++}return globalThis.String.fromCodePoint(...e)}function UC(t){return new RegExp("\\p{Mn}","u").test(String.fromCodePoint(t))}function WC(t){return new RegExp("\\p{Mc}","u").test(String.fromCodePoint(t))}function KC(t){return new RegExp("\\p{Me}","u").test(String.fromCodePoint(t))}function jC(t){return UC(t)||WC(t)||KC(t)}var GC=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),VC=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 HC(t){return new RegExp("\\p{Script=Greek}","u").test(String.fromCodePoint(t))}function zC(t){return new RegExp("\\p{Script=Hebrew}","u").test(String.fromCodePoint(t))}function JC(t){return new RegExp("\\p{Script=Hiragana}","u").test(String.fromCodePoint(t))}function QC(t){return new RegExp("\\p{Script=Katakana}","u").test(String.fromCodePoint(t))}function YC(t){return new RegExp("\\p{Script=Han}","u").test(String.fromCodePoint(t))}function ZC(t){return t>=1632&&t<=1641}function XC(t){return t>=1776&&t<=1785}function eE(t){return VC.has(t)}function xh(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||jC(e[0]))return!1;let n=!1,o=!1,i=!1;for(let a=0;a<r;a++){let u=e[a];if(GC.has(u))return!1;(JC(u)||QC(u)||YC(u))&&(n=!0),ZC(u)&&(o=!0),XC(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||!HC(d))return!1;break;case 1523:case 1524:if(p===void 0||!zC(p))return!1;break;case 8205:if(p===void 0||!eE(p))return!1;break;case 12539:break}}return!(t.includes("\u30FB")&&!n||o&&i)}function tE(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 Ph(t){return t.toLowerCase().startsWith("xn--")}function wh(t){try{return xh(Ih(t.slice(4)))}catch{return!1}}function vh(t){return t.length===0||t.length>63?!1:Ph(t)?wh(t):xh(t)}function bh(t){return t.length===0||t.length>63?!1:Ph(t)?wh(t):tE(t)}function Ba(t){if(t.length===0||t.length>253||t.charCodeAt(t.length-1)===46)return!1;for(let e of t.split("."))if(!bh(e))return!1;return!0}var nE=/^(?!.*\.\.)[\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 Ua(t){return nE.test(t)}function Wa(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(!vh(r))return!1;return!0}function qd(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 Ka(t){return qd(t,0,t.length)}function oE(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function ja(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&&oE(t.charCodeAt(o));)o++,i++;if(i===0)return!1;let u=t.charCodeAt(o);if(u===46){if(!qd(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 Ah(t){try{return new URL(t,"http://example.com"),!0}catch{return!1}}function Ga(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))?Ah(t):t.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&e===-1?!1:Ah(t)}function Va(t){try{return new URL(t),!0}catch{return!1}}var iE=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Ha(t){return iE.test(t)}var sE=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function za(t){return sE.test(t)}function Ja(t){if(t.length===0)return!1;try{return new RegExp(t),!0}catch{return!1}}var aE=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Qa(t){return aE.test(t)}var uE=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function Ya(t){return uE.test(t)}var pE=/^(?:(?:[^\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 Za(t){return pE.test(t)}function Th(t){return t>=97&&t<=122||t>=65&&t<=90}function Rh(t){return Th(t)||t>=48&&t<=57}function Xa(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function dE(t){return Rh(t)||t===43||t===45||t===46}function Bd(t){return Rh(t)||t===45||t===46||t===95||t===126}function Ud(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 lE(t){return Bd(t)||Ud(t)||t===58||t===64}function eu(t){let e=t.length;if(e===0||!Th(t.charCodeAt(0)))return!1;let r=1;for(;r<e;){let n=t.charCodeAt(r);if(n===58)break;if(!dE(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||!Xa(t.charCodeAt(i+1))||!Xa(t.charCodeAt(i+2)))return!1;i+=2}else if(!Bd(a)&&!Ud(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&&!Bd(i)&&!Ud(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||!Xa(t.charCodeAt(r+1))||!Xa(t.charCodeAt(r+2)))return!1;r+=2}else{if(n>127)return!1;if(!(lE(n)||n===47||n===63||n===35))return!1}r++}return!0}var mE=/^(?: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 tu(t){return mE.test(t)}var cE=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function ru(t){return cE.test(t)}var ce=new Map;function Ch(){ce.clear()}function fE(){return[...ce.entries()]}function gE(t,e){ce.set(t,e)}function hE(t){return ce.has(t)}function yE(t){return ce.get(t)}function SE(t,e){return ce.get(t)?.(e)??!0}function Eh(){Ch(),ce.set("date-time",Fa),ce.set("date",no),ce.set("duration",Na),ce.set("email",qa),ce.set("hostname",Ba),ce.set("idn-email",Ua),ce.set("idn-hostname",Wa),ce.set("ipv4",Ka),ce.set("ipv6",ja),ce.set("iri-reference",Ga),ce.set("iri",Va),ce.set("json-pointer-uri-fragment",Ha),ce.set("json-pointer",za),ce.set("regex",Ja),ce.set("relative-json-pointer",Qa),ce.set("time",oo),ce.set("uri-reference",Ya),ce.set("uri-template",Za),ce.set("uri",eu),ce.set("url",tu),ce.set("uuid",ru)}Eh();function Wd(t,e,r,n){return yn.Test(r.format,n)}function $h(t,e,r,n,o,i){return Wd(t,e,o,i)||e.AddError({keyword:"format",schemaPath:r,instancePath:n,params:{format:o.format}})}function Mh(t,e,r,n){let o=Td(r)?r.then:!0,i=md(r)?r.else:!0;return z(t,e,r.if,n)?z(t,e,o,n):z(t,e,i,n)}function Oh(t,e,r,n,o,i){let a=Td(o)?o.then:!0,u=md(o)?o.else:!0,p=new De,d=pe(t,p,`${r}/if`,n,o.if,i)?pe(t,p,`${r}/then`,n,a,i)||e.AddError({keyword:"if",schemaPath:r,instancePath:n,params:{failingKeyword:"then"}}):pe(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 kE(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 IE(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 xE(t,e,r,n){let o=eo(r)?r.prefixItems.length:0;return s.Every(n,o,(i,a)=>vt(t,e,r.items,i)&&e.AddIndex(a))}function PE(t,e,r,n,o,i){let a=eo(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 _h(t,e,r,n){return hd(r)?kE(t,e,r,n):xE(t,e,r,n)}function Dh(t,e,r,n,o,i){return hd(o)?IE(t,e,r,n,o,i):PE(t,e,r,n,o,i)}function wE(t){return cn(t)}function Kd(t,e,r,n){if(!wE(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 Lh(t,e,r,n,o,i){let a=fn(o)?o.minContains:1;return Kd(t,e,o,i)||e.AddError({keyword:"contains",schemaPath:r,instancePath:n,params:{minContains:a,maxContains:o.maxContains}})}function jd(t,e,r,n){return s.IsLessEqualThan(n,r.maximum)}function Fh(t,e,r,n,o,i){return jd(t,e,o,i)||e.AddError({keyword:"maximum",schemaPath:r,instancePath:n,params:{comparison:"<=",limit:o.maximum}})}function Gd(t,e,r,n){return s.IsLessEqualThan(n.length,r.maxItems)}function Nh(t,e,r,n,o,i){return Gd(t,e,o,i)||e.AddError({keyword:"maxItems",schemaPath:r,instancePath:n,params:{limit:o.maxItems}})}function Vd(t,e,r,n){return s.IsMaxLength(n,r.maxLength)}function qh(t,e,r,n,o,i){return Vd(t,e,o,i)||e.AddError({keyword:"maxLength",schemaPath:r,instancePath:n,params:{limit:o.maxLength}})}function Hd(t,e,r,n){return s.IsLessEqualThan(s.Keys(n).length,r.maxProperties)}function Bh(t,e,r,n,o,i){return Hd(t,e,o,i)||e.AddError({keyword:"maxProperties",schemaPath:r,instancePath:n,params:{limit:o.maxProperties}})}function vE(t){return cn(t)}function zd(t,e,r,n){if(!vE(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 Uh(t,e,r,n,o,i){return zd(t,e,o,i)||e.AddError({keyword:"contains",schemaPath:r,instancePath:n,params:{minContains:o.minContains}})}function Jd(t,e,r,n){return s.IsGreaterEqualThan(n,r.minimum)}function Wh(t,e,r,n,o,i){return Jd(t,e,o,i)||e.AddError({keyword:"minimum",schemaPath:r,instancePath:n,params:{comparison:">=",limit:o.minimum}})}function Qd(t,e,r,n){return s.IsGreaterEqualThan(n.length,r.minItems)}function Kh(t,e,r,n,o,i){return Qd(t,e,o,i)||e.AddError({keyword:"minItems",schemaPath:r,instancePath:n,params:{limit:o.minItems}})}function Yd(t,e,r,n){return s.IsMinLength(n,r.minLength)}function jh(t,e,r,n,o,i){return Yd(t,e,o,i)||e.AddError({keyword:"minLength",schemaPath:r,instancePath:n,params:{limit:o.minLength}})}function Zd(t,e,r,n){return s.IsGreaterEqualThan(s.Keys(n).length,r.minProperties)}function Gh(t,e,r,n,o,i){return Zd(t,e,o,i)||e.AddError({keyword:"minProperties",schemaPath:r,instancePath:n,params:{limit:o.minProperties}})}function Xd(t,e,r,n){return s.IsMultipleOf(n,r.multipleOf)}function Vh(t,e,r,n,o,i){return Xd(t,e,o,i)||e.AddError({keyword:"multipleOf",schemaPath:r,instancePath:n,params:{multipleOf:o.multipleOf}})}function el(t,e,r,n){let o=new ot;return!z(t,o,r.not,n)&&e.Merge([o])}function Hh(t,e,r,n,o,i){return el(t,e,o,i)||e.AddError({keyword:"not",schemaPath:r,instancePath:n,params:{}})}function zh(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 Jh(t,e,r,n,o,i){let a=[],u=[],p=o.oneOf.reduce((l,m,c)=>{let h=new De,y=`${r}/oneOf/${c}`,S=pe(t,h,y,n,m,i);return S&&u.push(c),S||a.push(h),S?[...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 tl(t,e,r,n){return(s.IsString(r.pattern)?new RegExp(r.pattern,"u"):r.pattern).test(n)}function Qh(t,e,r,n,o,i){return tl(t,e,o,i)||e.AddError({keyword:"pattern",schemaPath:r,instancePath:n,params:{pattern:o.pattern}})}function Yh(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 Zh(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 Xh(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 ey(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 St={};Ct(St,{Get:()=>TE,Reset:()=>bE,Set:()=>AE});var _r={immutableTypes:!1,maxErrors:8,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1};function bE(){_r.immutableTypes=!1,_r.maxErrors=8,_r.useAcceleration=!0,_r.exactOptionalPropertyTypes=!1,_r.enumerableKind=!1,_r.correctiveParse=!1}function AE(t){for(let e of s.Keys(t)){let r=t[e];r!==void 0&&Object.defineProperty(_r,e,{value:r})}}function TE(){return _r}function rl(t,e){return t.includes(e)||St.Get().exactOptionalPropertyTypes}function nl(t,e){return s.IsUndefined(t[e])}function ty(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 rl(o,a)?p:nl(n,a)||p})}function ry(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 rl(a,p)?c():nl(i,p)||c()})}function ny(t,e,r,n){return s.Every(s.Keys(n),0,(o,i)=>z(t,e,r.propertyNames,o))}function oy(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 De,h=pe(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 iy(t,e,r,n){let o=t.RecursiveRef(r)??!1;return M(o)&&z(t,e,o,n)}function sy(t,e,r,n,o,i){let a=t.RecursiveRef(o)??!1;return M(a)&&pe(t,e,"#",n,a,i)}function ay(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 uy(t,e,r,n,o,i){let a=t.Ref(o)??!1,u=new De,p=M(a)&&pe(t,u,"#",n,a,i);return p&&e.Merge([u]),p||u.GetErrors().forEach(d=>e.AddError(d)),p}function py(t,e,r,n){return s.Every(r.required,0,o=>s.HasPropertyKey(n,o))}function dy(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 ol(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 ly(t,e,r,n,o){return r.some(i=>ol(t,e,i,n,o))}function my(t,e,r,n){return s.IsArray(r.type)?ly(t,e,r.type,r,n):ol(t,e,r.type,r,n)}function cy(t,e,r,n,o,i){return(s.IsArray(o.type)?ly(t,e,o.type,o,i):ol(t,e,o.type,o,i))||e.AddError({keyword:"type",schemaPath:r,instancePath:n,params:{type:o.type}})}function fy(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 gy(t,e,r,n,o,i){let a=e.GetIndices(),u=[];return s.EveryAll(i,0,(d,l)=>{let m=new De,c=(a.has(l)||pe(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 hy(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 yy(t,e,r,n,o,i){let a=e.GetKeys(),u=[];return s.EveryAll(s.Entries(i),0,([d,l])=>{let m=new De,c=a.has(d)||pe(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 Sy(t){return!s.IsEqual(t.uniqueItems,!1)}function ky(t,e,r,n){if(!Sy(r))return!0;let o=new Set(n.map(Mr.Hash)).size,i=n.length;return s.IsEqual(o,i)}function Iy(t,e,r,n,o,i){if(!Sy(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=Ra(r)?$d(t,e,r,n):(!Rd(r)||my(t,e,r,n))&&(!(s.IsObject(n)&&!s.IsArray(n))||(!gn(r)||py(t,e,r,n))&&(!sr(r)||eh(t,e,r,n))&&(!ud(r)||ph(t,e,r,n))&&(!pd(r)||lh(t,e,r,n))&&(!dd(r)||ch(t,e,r,n))&&(!ri(r)||Yh(t,e,r,n))&&(!ni(r)||ty(t,e,r,n))&&(!vd(r)||ny(t,e,r,n))&&(!Ma(r)||Zd(t,e,r,n))&&(!Id(r)||Hd(t,e,r,n)))&&(!s.IsArray(n)||(!od(r)||Yg(t,e,r,n))&&(!cn(r)||Od(t,e,r,n))&&(!Zn(r)||_h(t,e,r,n))&&(!Sd(r)||Kd(t,e,r,n))&&(!Ea(r)||Gd(t,e,r,n))&&(!fn(r)||zd(t,e,r,n))&&(!ti(r)||Qd(t,e,r,n))&&(!eo(r)||Xh(t,e,r,n))&&(!oi(r)||ky(t,e,r,n)))&&(!s.IsString(n)||(!kd(r)||Vd(t,e,r,n))&&(!$a(r)||Yd(t,e,r,n))&&(!Ca(r)||Wd(t,e,r,n))&&(!Oa(r)||tl(t,e,r,n)))&&(!(s.IsNumber(n)||s.IsBigInt(n))||(!fd(r)||Fd(t,e,r,n))&&(!Yn(r)||Nd(t,e,r,n))&&(!yd(r)||jd(t,e,r,n))&&(!Xn(r)||Jd(t,e,r,n))&&(!xd(r)||Xd(t,e,r,n)))&&(!Ad(r)||ay(t,e,r,n))&&(!bd(r)||iy(t,e,r,n))&&(!ld(r)||gh(t,e,r,n))&&(!rd(r)||Bg(t,e,r,n))&&(!ad(r)||Md(t,e,r,n))&&(!cd(r)||Ld(t,e,r,n))&&(!gd(r)||Mh(t,e,r,n))&&(!Pd(r)||el(t,e,r,n))&&(!id(r)||rh(t,e,r,n))&&(!sd(r)||oh(t,e,r,n))&&(!wd(r)||zh(t,e,r,n))&&(!Da(r)||!s.IsArray(n)||fy(t,e,r,n))&&(!La(r)||!s.IsObject(n)||hy(t,e,r,n))&&(!nd(r)||zg(t,e,r,n));return t.Pop(r),o}function bt(t,e,r,n,o,i){return e.Push()&&pe(t,e,r,n,o,i)&&e.Pop()}function pe(t,e,r,n,o,i){t.Push(o);let a=Ra(o)?sh(t,e,r,n,o,i):!!(+(!Rd(o)||cy(t,e,r,n,o,i))&+(!(s.IsObject(i)&&!s.IsArray(i))||!!(+(!gn(o)||dy(t,e,r,n,o,i))&+(!sr(o)||th(t,e,r,n,o,i))&+(!ud(o)||dh(t,e,r,n,o,i))&+(!pd(o)||mh(t,e,r,n,o,i))&+(!dd(o)||fh(t,e,r,n,o,i))&+(!ri(o)||Zh(t,e,r,n,o,i))&+(!ni(o)||ry(t,e,r,n,o,i))&+(!vd(o)||oy(t,e,r,n,o,i))&+(!Ma(o)||Gh(t,e,r,n,o,i))&+(!Id(o)||Bh(t,e,r,n,o,i))))&+(!s.IsArray(i)||!!(+(!od(o)||Zg(t,e,r,n,o,i))&+(!cn(o)||uh(t,e,r,n,o,i))&+(!Zn(o)||Dh(t,e,r,n,o,i))&+(!Sd(o)||Lh(t,e,r,n,o,i))&+(!Ea(o)||Nh(t,e,r,n,o,i))&+(!fn(o)||Uh(t,e,r,n,o,i))&+(!ti(o)||Kh(t,e,r,n,o,i))&+(!eo(o)||ey(t,e,r,n,o,i))&+(!oi(o)||Iy(t,e,r,n,o,i))))&+(!s.IsString(i)||!!(+(!kd(o)||qh(t,e,r,n,o,i))&+(!$a(o)||jh(t,e,r,n,o,i))&+(!Ca(o)||$h(t,e,r,n,o,i))&+(!Oa(o)||Qh(t,e,r,n,o,i))))&+(!(s.IsNumber(i)||s.IsBigInt(i))||!!(+(!fd(o)||Sh(t,e,r,n,o,i))&+(!Yn(o)||kh(t,e,r,n,o,i))&+(!yd(o)||Fh(t,e,r,n,o,i))&+(!Xn(o)||Wh(t,e,r,n,o,i))&+(!xd(o)||Vh(t,e,r,n,o,i))))&+(!Ad(o)||uy(t,e,r,n,o,i))&+(!bd(o)||sy(t,e,r,n,o,i))&+(!ld(o)||hh(t,e,r,n,o,i))&+(!rd(o)||Ug(t,e,r,n,o,i))&+(!ad(o)||ah(t,e,r,n,o,i))&+(!cd(o)||yh(t,e,r,n,o,i))&+(!gd(o)||Oh(t,e,r,n,o,i))&+(!Pd(o)||Hh(t,e,r,n,o,i))&+(!id(o)||nh(t,e,r,n,o,i))&+(!sd(o)||ih(t,e,r,n,o,i))&+(!wd(o)||Jh(t,e,r,n,o,i))&+(!Da(o)||!s.IsArray(i)||gy(t,e,r,n,o,i))&+(!La(o)||!s.IsObject(i)||yy(t,e,r,n,o,i)))&&(!nd(o)||Jg(t,e,r,n,o,i));return t.Pop(o),a}var Dr={};Ct(Dr,{DynamicRef:()=>WE,Ref:()=>sl});var pr={};Ct(pr,{Delete:()=>DE,Get:()=>OE,Has:()=>ME,Indices:()=>ai,Set:()=>_E});function xy(t){if(t.length===0)throw Error("Cannot set root")}function Py(t){if(!s.IsObject(t))throw Error("Cannot set value")}function RE(t){if(s.IsUnsafePropertyKey(t))throw Error("Pointer contains unsafe property key")}function wy(t){for(let e of t)RE(e)}function CE(t){return/^(0|[1-9]\d*)$/.test(t)}function vy(t){return[t.slice(0,t.length-1),t.slice(t.length-1)[0]]}function EE(t,e){return s.IsObject(e)&&s.HasPropertyKey(e,t)}function $E(t,e){return s.IsObject(e)&&!s.IsUnsafePropertyKey(t)?e[t]:void 0}function il(t,e){return t.reduce((r,n)=>$E(n,r),e)}function ai(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 ME(t,e){let r=t;return ai(e).every(n=>EE(n,r)?(r=r[n],!0):!1)}function OE(t,e){let r=ai(e);return il(r,t)}function _E(t,e,r){let n=ai(e);xy(n),wy(n);let[o,i]=vy(n),a=il(o,t);return Py(a),a[i]=r,t}function DE(t,e){let r=ai(e);xy(r),wy(r);let[n,o]=vy(r),i=il(n,t);return Py(i),s.IsArray(i)&&CE(o)?i.splice(+o,1):delete i[o],t}function LE(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("#")?by(t,e,r):t}function FE(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 NE(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 by(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 qE(t,e,r){if(ur(t)){let n=LE(t,e,r);if(!s.IsUndefined(n))return n}if(ei(t)){let n=FE(t,e,r);if(!s.IsUndefined(n))return n}if(Er(t)){let n=NE(t,e,r);if(!s.IsUndefined(n))return n}return by(t,e,r)}function BE(t,e,r){return t.reduce((n,o)=>{let i=al(o,e,r);return s.IsUndefined(i)?n:i},void 0)}function UE(t,e,r){return s.Keys(t).reduce((n,o)=>{let i=al(t[o],e,r);return s.IsUndefined(i)?n:i},void 0)}function al(t,e,r){let n=Mt(t)&&ur(t)?new URL(t.$id,e.href):e;if(Mt(t)){let o=qE(t,n,r);if(!s.IsUndefined(o))return o}if(s.IsArray(t))return BE(t,n,r);if(s.IsObject(t))return UE(t,n,r)}function sl(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 al(t,n,o)}function WE(t,e,r,n){let o=r.$dynamicRef.startsWith("#")?sl(e,r.$dynamicRef):sl(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 io=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,Ay,Ty,Ry,Cy,Sn=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),io(this,Lr,"m",Ay).call(this,e)),ei(e)&&this.anchors.push(e),_a(e)&&this.recursiveAnchors.push(e),Er(e)&&this.dynamicAnchors.push(e))}Pop(e){Mt(e)&&(ur(e)&&(this.ids.pop(),io(this,Lr,"m",Ty).call(this,e)),ei(e)&&this.anchors.pop(),_a(e)&&this.recursiveAnchors.pop(),Er(e)&&this.dynamicAnchors.pop())}Ref(e){return io(this,Lr,"m",Ry).call(this,e)??io(this,Lr,"m",Cy).call(this,e)}RecursiveRef(e){return _a(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,Ay=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))io(this,Lr,"m",t).call(this,n[o],!1)}},Ty=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))io(this,Lr,"m",t).call(this,n[o],!1)}},Ry=function(e){return s.HasPropertyKey(this.context,e.$ref)?this.context[e.$ref]:void 0},Cy=function(e){let r=this.schema;return e.$ref.startsWith("#")?Dr.Ref(this.Base(),e.$ref):Dr.Ref(r,e.$ref)};function $y(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 jE=$y;function My(){return jE}function nu(...t){let[e,r,n]=ee.Match(t,{3:(l,m,c)=>[l,m,c],2:(l,m)=>[{},l,m]}),o=St.Get(),i=My(),a=[],u=new Sn(e,r),p=new ii(l=>{if(!s.IsGreaterEqualThan(a.length,o.maxErrors))return a.push({...l,message:i(l)})});return[pe(u,p,"#","",r,n),a]}function pl(...t){let[e,r,n]=ee.Match(t,{3:(a,u,p)=>[a,u,p],2:(a,u)=>[{},a,u]}),o=new Sn(e,r),i=new ot;return z(o,i,r,n)}var g={};Ct(g,{Assign:()=>VE,Clone:()=>ui,Create:()=>ZE,Discard:()=>XE,Metrics:()=>Nt,Update:()=>e$});var Nt={assign:0,create:0,clone:0,discard:0,update:0};function VE(t,e){return Nt.assign+=1,{...t,...e}}function HE(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~guard")}function zE(t){return t.map(e=>dl(e))}function JE(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:dl(o.value)})}return e}function QE(t){return new RegExp(t.source,t.flags)}function dl(t){return t instanceof RegExp?QE(t):HE(t)?t:s.IsArray(t)?zE(t):s.IsObject(t)?JE(t):t}function ui(t){return Nt.clone+=1,dl(t)}function YE(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 _y(t,e){return{...t,...e}}function ZE(t,e,r={}){Nt.create+=1;let n=St.Get(),o=_y(e,r),i=n.enumerableKind?_y(o,t):YE(o,t);return n.immutableTypes?Object.freeze(i):i}function XE(t,e){Nt.discard+=1;let r={},n=Object.getOwnPropertyDescriptors(ui(t)),o=new Set(e);for(let i of Object.keys(n))o.has(i)||Object.defineProperty(r,i,n[i]);return r}function e$(t,e,r){Nt.update+=1;let n=St.Get(),o=ui(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 de(t){return s.IsObject(t)}function Dy(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"OptionalAddAction")&&de(t.type)}function Ly(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"OptionalRemoveAction")&&de(t.type)}function Fy(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"ReadonlyAddAction")&&de(t.type)}function Ny(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"ReadonlyRemoveAction")&&de(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 qy(t){return g.Discard(t,["~kind","type","item"])}function By(t){return g.Update(t,{"~immutable":!0},{})}function so(t){return By(t)}function pi(t){return de(t)&&s.HasPropertyKey(t,"~immutable")}function ao(t){return g.Discard(t,["~optional"])}function kn(t){return g.Update(t,{"~optional":!0},{})}function Uy(t){return kn(t)}function We(t){return de(t)&&s.HasPropertyKey(t,"~optional")}function ou(t){return g.Discard(t,["~readonly"])}function In(t){return g.Update(t,{"~readonly":!0},{})}function Wy(t){return In(t)}function di(t){return de(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 iu(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 Ky(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 Le(t){return v(t,"Constructor")}function jy(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 Fe(t){return v(t,"Function")}function Gy(t){return g.Discard(t,["~kind","type","parameters","returnType"])}function kt(t,e){return g.Create({"~kind":"Ref"},{$ref:t},e)}function se(t){return v(t,"Ref")}function ll(t,e){return g.Create({"~kind":"Generic"},{type:"generic",parameters:t,expression:e})}function su(t){return v(t,"Generic")}function ml(t){return g.Create({"~kind":"Any"},{},t)}function Ve(t){return v(t,"Any")}var Vy="(?!)";function oe(t){return g.Create({"~kind":"Never"},{not:{}},t)}function Nr(t){return v(t,"Never")}function Hy(t){return s.Keys(t).filter(e=>!We(t[e]))}function au(t){return s.Keys(t)}function uu(t){return s.Values(t)}function O(t,e={}){let r=Hy(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 zy(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 Jy(t){return g.Discard(t,["~kind","anyOf"])}function Yt(t){return g.Create({"~kind":"Unknown"},{},t)}function Ye(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 ge(t){return v(t,"Cyclic")}function Qy(t){return s.IsObjectNotArray(t)&&s.HasPropertyKey(t,"~unsafe")&&s.IsNull(t["~unsafe"])}function $e(t){return v(t,"Infer")}function Ne(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 Yy(t){return g.Discard(t,["~kind","allOf"])}function cl(t){return de(t)&&s.HasPropertyKey(t,"~codec")&&s.IsObject(t["~codec"])&&s.HasPropertyKey(t["~codec"],"encode")&&s.HasPropertyKey(t["~codec"],"decode")}var Xy="-?(?:0|[1-9][0-9]*)n";function eS(t){return g.Create({"~kind":"BigInt"},{type:"bigint"},t)}function Bt(t){return v(t,"BigInt")}function At(t){return v(t,"Boolean")}var pu="-?(?:0|[1-9][0-9]*)";function du(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 tS(t){return g.Discard(t,["~kind","type","iteratorItems"])}var fl=class extends Error{constructor(e){super("Invalid Literal value"),Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}};function r$(t){return s.IsBigInt(t)?"bigint":s.IsBoolean(t)?"boolean":s.IsNumber(t)?"number":s.IsString(t)?"string":(()=>{throw new fl(t)})()}function Z(t,e){return g.Create({"~kind":"Literal"},{type:r$(t),const:t},e)}function gl(t){return s.IsBigInt(t)||s.IsBoolean(t)||s.IsNumber(t)||s.IsString(t)}function rS(t){return G(t)&&s.IsBigInt(t.const)}function nS(t){return G(t)&&s.IsBoolean(t.const)}function lu(t){return G(t)&&s.IsNumber(t.const)}function mu(t){return G(t)&&s.IsString(t.const)}function G(t){return v(t,"Literal")}function li(t){return g.Create({"~kind":"Null"},{type:"null"},t)}function wn(t){return v(t,"Null")}var cu="-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?";function Ut(t){return g.Create({"~kind":"Number"},{type:"number"},t)}function be(t){return v(t,"Number")}function hl(t){return g.Create({"~kind":"Symbol"},{type:"symbol"},t)}function uo(t){return v(t,"Symbol")}var fu=".*";function Tt(t){return g.Create({"~kind":"String"},{type:"string"},t)}function Ze(t){return v(t,"String")}function mi(t){let e=oS(t);return s.IsEqual(e.length,2)?e[0]:[]}function n$(t){return!0}function iS(t){return s.TakeLeft(t,(e,r)=>o$(e)?iS(r):!1,()=>!0)}function sS(t){return s.IsEqual(t.length,0)?!1:iS(t)}function o$(t){return b(t)?sS(t.anyOf):G(t)?n$(t.const):!1}function gu(t){return sS(t)}function hu(t){return g.Create({"~kind":"TemplateLiteral"},{type:"string",pattern:t},{})}function aS(t,e,r=[]){return s.TakeLeft(t,(n,o)=>aS(o,e,[...r,`${n}${e}`]),()=>r)}function i$(t,e){return s.IsEqual(t.length,0)?[`${e}`]:aS(t,e)}function uS(t,e,r=[]){return s.TakeLeft(e,(n,o)=>uS(t,o,[...r,...pS(t,n)]),()=>r)}function pS(t,e){return b(e)?uS(t,e.anyOf):G(e)?i$(t,e.const):Y()}function dS(t,e){return s.TakeLeft(e,(r,n)=>dS(pS(t,r),n),()=>t)}function s$(t){return t.map(e=>Z(e))}function a$(t){let e=dS([],t),r=s$(e);return B(r)}function u$(t){return s.IsEqual(t.length,0)?Y():s.IsEqual(t.length,1)&&G(t[0])?t[0]:a$(t)}function yl(t){let e=mi(t);return s.IsEqual(e.length,0)?Tt():gu(e)?u$(e):hu(t)}function He(t){let e=yl(t);return Ae(e)?Tt():e}function mt(t,e){let r="object",n={[t]:e};return g.Create({"~kind":"Record"},{type:r,patternProperties:n})}function lS(t){return mt(Br,t)}function mS(t){return O({true:t,false:t})}function p$(t){return s.IsString(t)||s.IsNumber(t)?Z(t):s.IsNull(t)?li():oe()}function Wt(t){return t.map(r=>p$(r))}function ci(t){let e=Wt(t);return B(e)}function po(t){return ci(t.enum)}function cS(t,e){let r=ci(t);return Ur(r,e)}function fS(t,e){return mt(lo,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 gS(t){return g.Discard(t,["~kind","type","items","minItems","additionalItems"])}function Sl(t){return t.reduceRight((r,n,o)=>({[o]:n,...r}),{})}function hS(t){let e=Sl(t.items);return O(e)}function d$(t,e){return di(t)?!!di(e):!1}function l$(t,e){return We(t)?!!We(e):!1}function m$(t,e){let r=d$(t,e),n=l$(t,e),o=Se([t,e]),i=ou(ao(o));return r&&n?In(kn(i)):r&&!n?In(i):!r&&n?kn(i):i}function c$(t,e,r){return r in t?r in e?m$(t[r],e[r]):t[r]:r in e?e[r]:oe()}function f$(t,e){return[...new Set([...s.Keys(e),...s.Keys(t)])].reduce((n,o)=>({...n,[o]:c$(t,e,o)}),{})}function yS(t){return N(t)?t.properties:V(t)?Sl(t.items):Y()}function SS(t,e){let r=yS(t),n=yS(e),o=f$(r,n);return O(o)}function kS(t,e){let r=vn(t,e);return s.IsEqual(r,gi)?t:s.IsEqual(r,hi)||s.IsEqual(r,fi)?e:oe()}function IS(t){return N(t)||V(t)}function g$(t,e){let r=b(t),n=b(e);return r||n}function h$(t,e){let r=bn(t),n=bn(e),o=g$(r,n),i=IS(r),a=IS(n);return o?Se([r,n]):i&&a?SS(r,n):i&&!a?r:!i&&a?n:kS(r,n)}function xS(t,e,r=[]){return s.TakeLeft(e,(n,o)=>xS(t,o,[...r,h$(t,n)]),()=>s.IsEqual(r.length,0)?[t]:r)}function PS(t,e,r=[]){return s.TakeLeft(t,(n,o)=>PS(o,e,[...r,...yi([n],e)]),()=>r)}function yi(t,e=[]){return s.TakeLeft(t,(r,n)=>b(r)?yi(n,PS(r.anyOf,e)):yi(n,xS(r,e)),()=>e)}function Se(t){let e=yi(t);return kl(e)}function Ot(t){return kl(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 wS(t,e){let r=Se(t);return Ur(r,e)}function vS(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 bS(t,e){return mt(yu,e)}function AS(t,e){return s.HasPropertyKey(t,"pattern")&&(s.IsString(t.pattern)||t.pattern instanceof RegExp)?mt(t.pattern.toString(),e):mt(Br,e)}function TS(t,e){let r=mi(t);return gu(r)?Ur(He(t),e):mt(t,e)}function y$(t){return b(t)?Zt(t.anyOf):[t]}function Zt(t){return t.reduce((e,r)=>[...e,...y$(r)],[])}function S$(t){return t.some(e=>Ze(e)||be(e)||at(e))}function k$(t,e){return s.IsEqual(S$(t),!0)?mt(Br,e):void 0}function I$(t,e){return t.reduce((r,n)=>G(n)&&(s.IsString(n.const)||s.IsNumber(n.const))?{...r,[n.const]:e}:r,{})}function x$(t,e){let r=I$(t,e);return O(r)}function RS(t,e){let r=Zt(t),n=k$(r,e);return de(n)?n:x$(r,e)}function Ur(t,e){return Ve(t)?lS(e):At(t)?mS(e):Ne(t)?cS(t.enum,e):at(t)?fS(t,e):D(t)?wS(t.allOf,e):G(t)?vS(t.const,e):be(t)?bS(t,e):b(t)?RS(t.anyOf,e):Ze(t)?AS(t,e):Ae(t)?TS(t.pattern,e):O({})}function Il(t,e,r){return L([t])?g.Update(Ur(t,e),{},r):xl(t,e,r)}function CS(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return Il(i,a,o)}var lo=`^${pu}$`,yu=`^${cu}$`,Br=`^${fu}$`;function xl(t,e,r={}){return E("Record",[t,e],r)}function ES(t,e,r={}){return Il(t,e,r)}function $S(t,e){return mt(t,e)}function _t(t){return s.Keys(t.patternProperties)[0]}function Su(t){let e=_t(t);return s.IsEqual(e,Br)?Tt():s.IsEqual(e,lo)?du():s.IsEqual(e,yu)?Ut():yl(e)}function Xe(t){return t.patternProperties[_t(t)]}function Me(t){return v(t,"Record")}function Pl(t){return g.Create({"~kind":"Rest"},{type:"rest",items:t},{})}function mo(t){return v(t,"Rest")}function MS(t){return v(t,"This")}function wl(t){return g.Create({"~kind":"Undefined"},{type:"undefined"},t)}function Tn(t){return v(t,"Undefined")}function Kt(t){return v(t,"Void")}function OS(t){return eS()}function _S(t){return Tt()}function DS(t){return Ut()}function LS(t){return du()}function FS(t){return oe()}function NS(t){return Z(t)}function qS(t){return B(t[1])}function BS(t){return t.length===3?[...t[0],...t[2]]:t.length===1?[...t[0]]:[]}function US(t){return[t[0],...t[1]]}function WS(t){return t[1]}function Iu(t){return J(t.length,2)}function It(t,e,r){return Iu(t)?e(t[0],t[1]):r()}function b$(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=b$(t[r],e);if(Iu(n))return n}return[]}function zl(t,e){return Array.from({length:e-t+1},(r,n)=>String.fromCharCode(t+n))}var KS=[...zl(97,122),...zl(65,90)],jS="0",GS=zl(49,57),co=[jS,...GS],VS=" ",Si=`
227
- `;var fo="_";var HS="$";var zS="//",JS="/*",T$="*/";function QS(t){let e=t.indexOf(T$);return J(e,-1)?"":t.slice(e+2)}function YS(t){let e=t.indexOf(Si);return J(e,-1)?"":t.slice(e)}function R$(t){return t.replace(/^[ \t\r\f\v]+/,"")}function xu(t){let e=R$(t);return e.startsWith(JS)?xu(QS(e.slice(2))):e.startsWith(zS)?xu(YS(e.slice(2))):e}function jt(t){let e=t.trimStart();return e.startsWith(JS)?jt(QS(e.slice(2))):e.startsWith(zS)?jt(YS(e.slice(2))):e}var IX=[...co,fo];function Jl(t,e){return Xt([t],e)}function Gt(t,e){return J(t,"")?["",e]:t.startsWith(Si)?Jl(t,xu(e)):t.startsWith(VS)?Jl(t,e):Jl(t,jt(e))}var O$=[...KS,fo,HS];var HX=[...O$,...co];var oee=[...co,fo];function _$(t){return J(t,"")?[]:[t.slice(0,1),t.slice(1)]}function ZS(t,e){return Ta(t,(r,n)=>e.startsWith(r)?!0:ZS(n,e),()=>!1)}function ki(t,e,r=""){return It(_$(e),(n,o)=>ZS(t,e)?[r,e]:ki(t,o,`${r}${n}`),()=>[])}function XS(t,e){return It(ki(t,e),(r,n)=>J(r,"")?[]:[r,n],()=>[])}var X=(t,e,r=()=>[])=>t.length===2?e(t):r();var L$=t=>X(Gt("-?(?:0|[1-9][0-9]*)n",t),([e,r])=>[OS(e),r]),F$=t=>X(Gt(".*",t),([e,r])=>[_S(e),r]),N$=t=>X(Gt("-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?",t),([e,r])=>[DS(e),r]),q$=t=>X(Gt("-?(?:0|[1-9][0-9]*)",t),([e,r])=>[LS(e),r]),B$=t=>X(Gt("(?!)",t),([e,r])=>[FS(e),r]),U$=t=>X(XS(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],t),([e,r])=>[NS(e),r]),W$=t=>X(X(L$(t),([e,r])=>[e,r],()=>X(F$(t),([e,r])=>[e,r],()=>X(N$(t),([e,r])=>[e,r],()=>X(q$(t),([e,r])=>[e,r],()=>X(B$(t),([e,r])=>[e,r],()=>X(K$(t),([e,r])=>[e,r],()=>X(U$(t),([e,r])=>[e,r],()=>[]))))))),([e,r])=>[e,r]),K$=t=>X(X(Gt("(",t),([e,r])=>X(Yl(r),([n,o])=>X(Gt(")",o),([i,a])=>[[e,n,i],a]))),([e,r])=>[qS(e),r]),ek=t=>X(X(X(Ql(t),([e,r])=>X(Gt("|",r),([n,o])=>X(ek(o),([i,a])=>[[e,n,i],a]))),([e,r])=>[e,r],()=>X(X(Ql(t),([e,r])=>[[e],r]),([e,r])=>[e,r],()=>X([[],t],([e,r])=>[e,r],()=>[]))),([e,r])=>[BS(e),r]),Ql=t=>X(X(W$(t),([e,r])=>X(Yl(r),([n,o])=>[[e,n],o])),([e,r])=>[US(e),r]),Yl=t=>X(X(ek(t),([e,r])=>[e,r],()=>X(Ql(t),([e,r])=>[e,r],()=>[])),([e,r])=>[e,r]),oS=t=>X(X(Gt("^",t),([e,r])=>X(Yl(r),([n,o])=>X(Gt("$",o),([i,a])=>[[e,n,i],a]))),([e,r])=>[WS(e),r]);function G$(t){return t.join("|")}function V$(t){return t.slice(1,t.length-1)}function H$(t,e,r){return Wr(e,`${r}${t}`)}function z$(t,e){return Wr(t,`${e}${Xy}`)}function J$(t,e){return Wr(t,`${e}${pu}`)}function Q$(t,e){return Wr(t,`${e}${cu}`)}function Y$(t,e){return Pu(B([Z("false"),Z("true")]),t,e)}function Z$(t,e){return Wr(t,`${e}${fu}`)}function X$(t,e,r){return Wr(e,`${r}${V$(t)}`)}function eM(t,e,r){let n=wu(t,{});return Pu(n,e,r)}function tM(t,e,r){let n=Wt(t);return Zl(n,e,r)}function Zl(t,e,r,n=[]){return s.TakeLeft(t,(o,i)=>Zl(i,e,r,[...n,Pu(o,[],"")]),()=>Wr(e,`${r}(${G$(n)})`))}function Pu(t,e,r){return Ne(t)?tM(t.enum,e,r):at(t)?J$(e,r):G(t)?H$(t.const,e,r):Bt(t)?z$(e,r):At(t)?Y$(e,r):be(t)?Q$(e,r):Ze(t)?Z$(e,r):Ae(t)?X$(t.pattern,e,r):rk(t)?eM(t.parameters[0],e,r):b(t)?Zl(t.anyOf,e,r):Vy}function Wr(t,e){return s.TakeLeft(t,(r,n)=>Pu(r,n,e),()=>e)}function rM(t){return`^${Wr(t,"")}$`}function tk(t){let e=rM(t);return hu(e)}function wu(t,e){return L(t)?g.Update(tk(t),{},e):vl(t,e)}function nk(t,e,r,n){let o=Rt(t,e,r);return wu(o,n)}function vl(t,e={}){return E("TemplateLiteral",[t],e)}function rk(t){return de(t)&&s.HasPropertyKey(t,"action")&&s.IsEqual(t.action,"TemplateLiteral")}function Ae(t){return v(t,"TemplateLiteral")}var F={};Ct(F,{ExtendsFalse:()=>U,ExtendsTrue:()=>A,ExtendsUnion:()=>Xl,IsExtendsFalse:()=>nM,IsExtendsTrue:()=>ik,IsExtendsTrueLike:()=>go,IsExtendsUnion:()=>ok,Match:()=>Oe});function Xl(t){return g.Create({"~kind":"ExtendsUnion"},{inferred:t})}function ok(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 ik(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"inferred")&&s.IsEqual(t["~kind"],"ExtendsTrue")&&s.IsObject(t.inferred)}function U(){return g.Create({"~kind":"ExtendsFalse"},{})}function nM(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.IsEqual(t["~kind"],"ExtendsFalse")}function go(t){return ok(t)||ik(t)}function Oe(t,e,r){return go(t)?e(t.inferred):r()}function oM(t,e,r,n){return Oe(re(t,r,n),o=>A(g.Assign(g.Assign(t,o),{[e]:r})),()=>U())}function iM(t,e){return A(t)}function sM(t,e,r){let n=ci(r);return re(t,e,n)}function sk(t,e,r){return s.TakeLeft(r,(n,o)=>Oe(re(t,e,n),i=>sk(i,e,o),()=>U()),()=>A(t))}function aM(t,e,r){let n=He(r);return re(t,e,n)}function ak(t,e,r){return s.TakeLeft(r,(n,o)=>Oe(re(t,e,n),i=>A(i),()=>ak(t,e,o)),()=>U())}function W(t,e,r){return Ve(r)?iM(t,e):Ne(r)?sM(t,e,r.enum):$e(r)?oM(t,r.name,e,r.extends):D(r)?sk(t,e,r.allOf):Ae(r)?aM(t,e,r.pattern):b(r)?ak(t,e,r.anyOf):Ye(r)?A(t):U()}function uk(t,e,r){return $e(r)?W(t,e,r):Ve(r)?A(t):Ye(r)?A(t):Xl(t)}function uM(t,e){let r=pi(t),n=pi(e);return r&&n||!r&&n?!0:!(r&&!n)}function pk(t,e,r,n){return te(n)?uM(e,n)?re(t,r,n.items):U():W(t,e,n)}function dk(t,e,r){return st(r)?re(t,e,r.iteratorItems):W(t,mr(e),r)}function lk(t,e,r){return Bt(r)?A(t):W(t,e,r)}function mk(t,e,r){return At(r)?A(t):W(t,e,r)}function pM(t,e,r,n,o){let i=$e(n)?e:n,a=$e(n)?n:e,u=We(e),p=We(n);return!u&&p?U():Oe(re(t,i,a),d=>Ii(d,r,o),()=>U())}function dM(t,e,r,n){return s.TakeLeft(n,(o,i)=>pM(t,e,r,o,i),()=>We(e)?A(t):U())}function lM(t,e,r){return s.TakeLeft(e,(n,o)=>dM(t,n,o,r),()=>A(t))}function Ii(t,e,r){return lM(t,e,r)}function vu(t,e,r){return Kt(r)?A(t):re(t,e,r)}function ck(t,e,r,n){return Ve(n)?A(t):Ye(n)?A(t):Le(n)?Oe(Ii(t,e,n.parameters),o=>vu(o,r,n.instanceType),()=>U()):U()}function fk(t,e,r){return re(t,po(e),r)}function gk(t,e,r,n){return Ve(n)?A(t):Ye(n)?A(t):Fe(n)?Oe(Ii(t,e,n.parameters),o=>vu(o,r,n.returnType),()=>U()):U()}function hk(t,e,r){return at(r)?A(t):be(r)?A(t):W(t,e,r)}function yk(t,e,r){let n=Se(e);return re(t,n,r)}function Sk(t,e,r){return ut(r)?re(t,e,r.iteratorItems):W(t,cr(e),r)}function bu(t,e,r){return e===r?A(t):U()}function mM(t,e,r){return G(r)?bu(t,e,r.const):Bt(r)?A(t):W(t,Z(e),r)}function cM(t,e,r){return G(r)?bu(t,e,r.const):At(r)?A(t):W(t,Z(e),r)}function fM(t,e,r){return G(r)?bu(t,e,r.const):be(r)?A(t):W(t,Z(e),r)}function gM(t,e,r){return G(r)?bu(t,e,r.const):Ze(r)?A(t):W(t,Z(e),r)}function kk(t,e,r){return s.IsBigInt(e.const)?mM(t,e.const,r):s.IsBoolean(e.const)?cM(t,e.const,r):s.IsNumber(e.const)?fM(t,e.const,r):s.IsString(e.const)?gM(t,e.const,r):Y()}function Ik(t,e,r){return $e(r)?W(t,e,r):A(t)}function xk(t,e,r){return wn(r)?A(t):W(t,e,r)}function Pk(t,e,r){return be(r)?A(t):W(t,e,r)}function hM(t,e,r){return We(e)?We(r)?A(t):U():A(t)}function yM(t,e,r){return $e(r)&&Nr(r.extends)?U():Oe(re(t,e,r),n=>hM(n,e,r),()=>U())}function SM(t,e){return t.reduce((r,n)=>n in e?go(e[n])?{...r,...e[n].inferred}:Y():Y(),{})}function kM(t,e,r){let n={};for(let a of s.Keys(r))n[a]=a in e?yM({},e[a],r[a]):We(r[a])?$e(r[a])?A(g.Assign(t,{[r[a].name]:r[a].extends})):A(t):U();let o=s.Values(n).every(a=>go(a)),i=o?SM(s.Keys(n),n):{};return o?A(i):U()}function IM(t,e,r){let n=kM(t,e,r);return go(n)?A(g.Assign(t,n.inferred)):U()}function xM(t,e,r){return IM(t,e,r)}function wk(t,e,r){return N(r)?xM(t,e,r.properties):W(t,O(e),r)}function vk(t,e,r){return Ge(r)?re(t,e,r.item):W(t,dr(e),r)}function bk(t,e,r){return Ze(r)?A(t):W(t,e,r)}function Ak(t,e,r){return uo(r)?A(t):W(t,e,r)}function Tk(t,e,r){let n=He(e);return re(t,n,r)}function em(t,e){return g.Create({"~kind":"Inferrable"},{name:t,type:e},{})}function xi(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 tm(t){return mo(t)?$e(t.items)?te(t.items.extends)?em(t.items.name,t.items.extends.items):Ye(t.items.extends)?em(t.items.name,t.items.extends):void 0:Y():void 0}function Au(t){return $e(t)?em(t.name,t.extends):void 0}function rm(t,e,r=[]){return s.TakeLeft(t,(n,o)=>Oe(re({},n,e),()=>rm(o,e,[...r,n]),()=>{}),()=>r)}function Rk(t,e,r,n){let o=rm(r,n);return s.IsArray(o)?A(g.Assign(t,{[e]:Ke(o)})):U()}function Tu(t,e,r,n){let o=rm(r,n);return s.IsArray(o)?A(g.Assign(t,{[e]:B(o)})):U()}function PM(t){return[...t].reverse()}function nm(t,e){return e?PM(t):t}function wM(t){let e=t.length>0?t[0]:void 0,r=de(e)?tm(e):void 0;return de(r)}function vM(t,e,r,n,o,i){return Oe(re(t,r,o),a=>Ck(a,e,n,i),()=>U())}function bM(t,e,r,n,o){let i=tm(n);return xi(i)?Rk(t,i.name,nm(r,e),i.type):s.TakeLeft(r,(a,u)=>vM(t,e,a,u,n,o),()=>U())}function AM(t,e,r,n){return s.TakeLeft(n,(o,i)=>bM(t,e,r,o,i),()=>s.IsEqual(r.length,0)?A(t):U())}function Ck(t,e,r,n){return AM(t,e,r,n)}function TM(t,e,r){let n=Kr(t,{callstack:[]},r),o=wM(n);return Ck(t,o,nm(e,o),nm(n,o))}function Ek(t,e,r){let n=Au(r);return xi(n)?Tu(t,n.name,e,n.type):s.TakeLeft(e,(o,i)=>Oe(re(t,o,r),a=>Ek(a,i,r),()=>U()),()=>A(t))}function $k(t,e,r){let n=Kr(t,{callstack:[]},e);return V(r)?TM(t,n,r.items):te(r)?Ek(t,n,r.items):W(t,Ke(n),r)}function Mk(t,e,r){return Kt(r)?A(t):Tn(r)?A(t):W(t,e,r)}function Ok(t,e,r){return s.TakeLeft(r,(n,o)=>Oe(re(t,e,n),i=>A(i),()=>Ok(t,e,o)),()=>U())}function om(t,e,r){return s.TakeLeft(e,(n,o)=>Oe(Ok(t,n,r),i=>om(i,o,r),()=>U()),()=>A(t))}function _k(t,e,r){let n=Au(r);return xi(n)?Tu(t,n.name,e,n.type):b(r)?om(t,e,r.anyOf):om(t,e,[r])}function Dk(t,e,r){return $e(r)?W(t,e,r):Ve(r)?A(t):Ye(r)?A(t):U()}function Lk(t,e,r){return Kt(r)?A(t):W(t,e,r)}function re(t,e,r){return Ve(e)?uk(t,e,r):te(e)?pk(t,e,e.items,r):st(e)?dk(t,e.iteratorItems,r):Bt(e)?lk(t,e,r):At(e)?mk(t,e,r):Le(e)?ck(t,e.parameters,e.instanceType,r):Ne(e)?fk(t,e,r):Fe(e)?gk(t,e.parameters,e.returnType,r):at(e)?hk(t,e,r):D(e)?yk(t,e.allOf,r):ut(e)?Sk(t,e.iteratorItems,r):G(e)?kk(t,e,r):Nr(e)?Ik(t,e,r):wn(e)?xk(t,e,r):be(e)?Pk(t,e,r):N(e)?wk(t,e.properties,r):Ge(e)?vk(t,e.item,r):Ze(e)?bk(t,e,r):uo(e)?Ak(t,e,r):Ae(e)?Tk(t,e.pattern,r):V(e)?$k(t,e.items,r):Tn(e)?Mk(t,e,r):b(e)?_k(t,e.anyOf,r):Ye(e)?Dk(t,e,r):Kt(e)?Lk(t,e,r):U()}function RM(t,e){return Se([...t,O(e)])}function Fk(t,e,r){return L(t)?g.Update(RM(t,e),{},r):bl(t,e,r)}function Nk(t,e,r,n,o){let i=Rt(t,e,r),a=Pi(t,e,n);return Fk(i,a,o)}function bl(t,e,r={}){return E("Interface",[t,e],r)}function ho(t){return de(t)&&s.HasPropertyKey(t,"action")&&s.IsEqual(t.action,"Interface")}function CM(t,e,r){return t.includes(r)?!0:jr([...t,r],e,e[r])}function qk(t,e,r){let n=uu(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)?CM(t,e,r.$ref):te(r)?jr(t,e,r.items):st(r)?jr(t,e,r.iteratorItems):Le(r)?Rn(t,e,[...r.parameters,r.instanceType]):Fe(r)?Rn(t,e,[...r.parameters,r.returnType]):ho(r)?qk(t,e,r.parameters[1]):D(r)?Rn(t,e,r.allOf):ut(r)?jr(t,e,r.iteratorItems):N(r)?qk(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,Xe(r)):!1}function Ru(t,e,r){return jr(t,e,r)}function EM(t,e){return e.reduce((r,n)=>n in t?Ru([n],t,t[n])?[...r,n]:r:Y(),[])}function Bk(t){let e=au(t);return EM(t,e)}function $M(t,e,r){return r.includes(e)?r:e in t?Gr(t,t[e],[...r,e]):Y()}function Uk(t,e,r){let n=uu(e);return yo(t,n,r)}function yo(t,e,r){return e.reduce((n,o)=>Gr(t,o,n),r)}function Gr(t,e,r){return se(e)?$M(t,e.$ref,r):te(e)?Gr(t,e.items,r):st(e)?Gr(t,e.iteratorItems,r):Le(e)?yo(t,[...e.parameters,e.instanceType],r):Fe(e)?yo(t,[...e.parameters,e.returnType],r):ho(e)?Uk(t,e.parameters[1],r):D(e)?yo(t,e.allOf,r):ut(e)?Gr(t,e.iteratorItems,r):N(e)?Uk(t,e.properties,r):Ge(e)?Gr(t,e.item,r):b(e)?yo(t,e.anyOf,r):V(e)?yo(t,e.items,r):Me(e)?Gr(t,Xe(e),r):r}function Wk(t,e,r){return Gr(t,r,[e])}function MM(t){return ml()}function OM(t){return s.Keys(t).reduce((e,r)=>({...e,[r]:er(t[r])}),{})}function wi(t){return t.reduce((e,r)=>[...e,er(r)],[])}function er(t){return se(t)?MM(t.$ref):te(t)?lr(er(t.items),iu(t)):st(t)?mr(er(t.iteratorItems)):Le(t)?xn(wi(t.parameters),er(t.instanceType)):Fe(t)?Pn(wi(t.parameters),er(t.returnType)):D(t)?qt(wi(t.allOf)):ut(t)?cr(er(t.iteratorItems)):N(t)?O(OM(t.properties)):Ge(t)?dr(er(t.item)):Me(t)?ES(Su(t),er(Xe(t))):b(t)?B(wi(t.anyOf)):V(t)?Ke(wi(t.items)):t}function _M(t,e){return e in t?er(t[e]):Yt()}function Kk(t){return _M(t.$defs,t.$ref)}function DM(t,e,r){let n=Rt(t,{callstack:[]},e),o=Pi({},{callstack:[]},r);return Se([...n,O(o)])}function LM(t,e){return s.Keys(t).filter(n=>e.includes(n)).reduce((n,o)=>{let i=t[o],a=ho(i)?DM(t,i.parameters[0],i.parameters[1]):i;return{...n,[o]:a}},{})}function jk(t,e,r){let n=Wk(t,e,r),o=LM(t,n);return qr(o,e)}function Gk(t,e){return e in t?se(t[e])?Gk(t,t[e].$ref):t[e]:oe()}function tr(t,e){return Gk(t,e)}function Vk(t){return ge(t)?Kk(t):Qy(t)?Yt():t}function pt(t,e,r){let n=Vk(e),o=Vk(r);return re(t,n,o)}var fi="equal",FM="disjoint",gi="left-inside",hi="right-inside";function vn(t,e){let r=[Ye(t)?F.ExtendsFalse():pt({},t,e),Ye(t)?F.ExtendsTrue({}):pt({},e,t)];return F.IsExtendsTrueLike(r[0])&&F.IsExtendsTrueLike(r[1])?fi:F.IsExtendsTrueLike(r[0])&&F.IsExtendsFalse(r[1])?gi:F.IsExtendsFalse(r[0])&&F.IsExtendsTrueLike(r[1])?hi:FM}function NM(t,e){return e.filter(r=>vn(t,r)!==hi)}function qM(t,e){let r=e.some(n=>{let o=vn(t,n);return s.IsEqual(o,gi)||s.IsEqual(o,fi)});return s.IsEqual(r,!1)}function BM(t,e){let r=bn(t);return Ve(r)?[r]:qM(r,e)?[...NM(r,e),r]:e}function UM(t){return t.reduce((e,r)=>N(r)?[...e,r]:Nr(r)?e:BM(r,e),[])}function kl(t){let e=UM(t),r=Zt(e);return r.length===0?oe():r.length===1?r[0]:B(r)}function im(t,e){return g.Update(bn(t),{},e)}function Hk(t,e,r,n){let o=P(t,e,r);return im(o,n)}function vi(t,e=[]){return Fr(t)&&s.IsEqual(t.action,"Conditional")?se(t.parameters[0])?vi(t.parameters[2],vi(t.parameters[3],[...e,t.parameters[0].$ref])):vi(t.parameters[2],vi(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 WM(t,e){return t.reduce((r,n)=>[...r,e.includes(n.name)],[])}function Qk(t,e,r=[]){return s.TakeLeft(t,(n,o)=>s.TakeLeft(e,(i,a)=>Qk(o,a,[...r,[i,n]]),()=>r),()=>r)}function KM(t){return b(t)?[...t.anyOf]:[t]}function jM(t,e){return t.reduce((r,n)=>[...r,[...n,e]],[])}function zk(t,e){return e.reduce((r,n)=>[...r,...jM(t,n)],[])}function Jk(t){return t.reduce((e,r)=>s.IsEqual(r[0],!0)?zk(e,KM(r[1])):zk(e,[r[1]]),[[]])}function Yk(t,e,r){let n=vi(r),o=WM(t,n),i=Qk(e,o);return Fr(r)&&s.IsEqual(r.action,"Conditional")||Fr(r)&&s.IsEqual(r.action,"Mapped")?Jk(i):[e]}function GM(){return["(not-resolvable)",oe()]}function VM(){return["(not-generic)",oe()]}function HM(t,e,r){return[t,ll(e,r)]}function zM(t,e,r){return e in t?Zk(t,e,t[e],r):GM()}function Zk(t,e,r,n){return su(r)?HM(e,r.parameters,r.expression):se(r)?zM(t,r.$ref,n):VM()}function Xk(t,e,r){return Zk(t,"(anonymous)",e,r)}function JM(t,e,r){if($e(e)||Cu(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 eI(t,e,r,n,o){let i=P(t,e,o);return JM(r,i,n),g.Assign(t,{[r]:i})}function QM(t,e,r,n,o){let i=P(t,e,r.extends),a=P(t,e,r.equals);return s.TakeLeft(o,(u,p)=>sm(eI(t,e,r.name,i,u),e,n,p),()=>sm(eI(t,e,r.name,i,a),e,n,[]))}function sm(t,e,r,n){return s.TakeLeft(r,(o,i)=>QM(t,e,o,i,n),()=>t)}function tI(t,e,r,n){return sm(t,e,r,n)}function YM(t){return s.IsGreaterThan(t.callstack.length,0)?t.callstack[t.callstack.length-1]:""}function ZM(t,e){return s.IsEqual(YM(t),e)}function XM(t,e,r,n,o,i){let a=tI(t,e,n,i),u=P(a,{callstack:[...e.callstack,r.$ref]},o);return P(t,e,u)}function eO(t,e,r,n,o,i){return i.reduce((a,u)=>[...a,XM(t,e,r,n,o,u)],[])}function tO(t,e,r,n,o,i){let a=Yk(n,i,o),u=eO(t,e,r,n,o,a);return s.IsEqual(u.length,1)?u[0]:Ot(u)}function am(t,e,r,n){let o=Rt(t,e,n),i=Xk(t,r,n),a=i[0],u=i[1];return su(u)?ZM(e,a)?ku(kt(a),o):tO(t,e,kt(a),u.parameters,u.expression,o):ku(r,o)}function ku(t,e){return g.Create({"~kind":"Call"},{target:t,arguments:e},{})}function Cu(t){return v(t,"Call")}function rI(t,e){return t(e)}function nI(t,e){return s.IsString(e)?Z(rI(t,e)):Z(e)}function oI(t,e){let r=He(e);return fr(t,r)}function iI(t,e){let r=e.map(n=>fr(t,n));return B(r)}function fr(t,e){return G(e)?nI(t,e.const):Ae(e)?oI(t,e.pattern):b(e)?iI(t,e.anyOf):e}function Al(t,e={}){return E("Capitalize",[t],e)}function Tl(t,e={}){return E("Lowercase",[t],e)}function Rl(t,e={}){return E("Uncapitalize",[t],e)}function Cl(t,e={}){return E("Uppercase",[t],e)}var rO=t=>t[0].toUpperCase()+t.slice(1),nO=t=>t.toLowerCase(),oO=t=>t[0].toLowerCase()+t.slice(1),iO=t=>t.toUpperCase();function sI(t,e){return L([t])?g.Update(fr(rO,t),{},e):Al(t,e)}function aI(t,e){return L([t])?g.Update(fr(nO,t),{},e):Tl(t,e)}function uI(t,e){return L([t])?g.Update(fr(oO,t),{},e):Rl(t,e)}function pI(t,e){return L([t])?g.Update(fr(iO,t),{},e):Cl(t,e)}function dI(t,e,r,n){let o=P(t,e,r);return sI(o,n)}function lI(t,e,r,n){let o=P(t,e,r);return aI(o,n)}function mI(t,e,r,n){let o=P(t,e,r);return uI(o,n)}function cI(t,e,r,n){let o=P(t,e,r);return pI(o,n)}function El(t,e,r,n,o={}){return E("Conditional",[t,e,r,n],o)}function sO(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 fI(t,e,r,n,o,i,a){return L([r,n])?g.Update(sO(t,e,r,n,o,i),{},a):El(r,n,o,i,a)}function gI(t,e,r,n,o,i,a){let u=P(t,e,r),p=P(t,e,n);return fI(t,e,u,p,o,i,a)}function $l(t,e={}){return E("ConstructorParameters",[t],e)}function aO(t){let e=Le(t)?t.parameters:[],r=Kr({},{callstack:[]},e);return Ke(r)}function hI(t,e){return L([t])?g.Update(aO(t),{},e):$l(t,e)}function yI(t,e,r,n){let o=P(t,e,r);return hI(o,n)}function Ml(t,e,r={}){return E("Exclude",[t,e],r)}function SI(t,e){return t.reduce((r,n)=>[...r,...kI(n,e)],[])}function kI(t,e){let r=pt({},t,e);return F.IsExtendsTrueLike(r)?[]:[t]}function II(t,e){let r=Ne(t)?SI(Wt(t.enum),e):b(t)?SI(Zt(t.anyOf),e):kI(t,e);return Ot(r)}function Eu(t,e,r){return L([t,e])?g.Update(II(t,e),{},r):Ml(t,e,r)}function xI(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return Eu(i,a,o)}function Ol(t,e,r={}){return E("Extract",[t,e],r)}function wI(t,e){return t.reduce((r,n)=>[...r,...vI(n,e)],[])}function vI(t,e){let r=pt({},t,e);return F.IsExtendsTrueLike(r)?[t]:[]}function bI(t,e){let r=Ne(t)?wI(Wt(t.enum),e):b(t)?wI(Zt(t.anyOf),e):vI(t,e);return Ot(r)}function PI(t,e,r){return L([t,e])?g.Update(bI(t,e),{},r):Ol(t,e,r)}function AI(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return PI(i,a,o)}function _l(t,e,r={}){return E("Index",[t,e],r)}function CI(t,e){let r=tr(t,e);return Vt(r)}function uO(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 EI(t){return t.reduce((e,r)=>uO(e,Vt(r)),{})}function $I(t){let e=hS(Ke(t));return Vt(e)}function pO(t,e){return s.Keys(t).filter(o=>o in e).reduce((o,i)=>({...o,[i]:Ot([t[i],e[i]])}),{})}function MI(t,e){return s.TakeLeft(t,(r,n)=>MI(n,pO(e,Vt(r))),()=>e)}function OI(t){return s.TakeLeft(t,(e,r)=>MI(r,Vt(e)),()=>Y())}function Vt(t){return ge(t)?CI(t.$defs,t.$ref):D(t)?EI(t.allOf):b(t)?OI(t.anyOf):V(t)?$I(t.items):N(t)?t.properties:{}}function So(t){let e=Vt(t);return O(e)}var dO=new RegExp("^(?:0|[1-9][0-9]*)$");function ko(t){let e=`${t}`;return dO.test(e)?parseInt(e):t}function lO(t){return Z(ko(t))}function _I(t){return t.map(e=>DI(e))}function DI(t){return D(t)?qt(_I(t.allOf)):b(t)?B(_I(t.anyOf)):G(t)?lO(t.const):t}function LI(t,e){let r=DI(e),n=pt({},r,Ut());return F.IsExtendsTrueLike(n)?t:G(e)&&s.IsEqual(e.const,"length")?Ut():oe()}function FI(t,e){let r=tr(t,e);return rr(r)}function $u(t){return t.reduce((e,r)=>[...e,...rr(r)],[])}function NI(t){let e=Wt(t);return $u(e)}function qI(t){let e=Se(t);return rr(e)}function BI(t){return[`${t}`]}function UI(t){let e=He(t);return rr(e)}function rr(t){return ge(t)?FI(t.$defs,t.$ref):Ne(t)?NI(t.enum):D(t)?qI(t.allOf):G(t)?BI(t.const):Ae(t)?UI(t.pattern):b(t)?$u(t.anyOf):[]}function Io(t){return rr(t)}function bi(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)):Le(e)?xn(bi(t,e.parameters),Vr(t,e.instanceType)):Fe(e)?Pn(bi(t,e.parameters),Vr(t,e.returnType)):ut(e)?cr(Vr(t,e.iteratorItems)):Ge(e)?dr(Vr(t,e.item)):V(e)?Ke(bi(t,e.items)):b(e)?B(bi(t,e.anyOf)):D(e)?qt(bi(t,e.allOf)):MS(e)?O(t):e}function WI(t,e){return Vr(t,e)}function mO(t,e){let r=e in t?t[e]:oe();return WI(t,r)}function KI(t,e){return e.reduce((r,n)=>[...r,mO(t,n)],[])}function cO(t,e){let r=Io(e),n=KI(t,r);return Ot(n)}var fO=new RegExp(lo);function gO(t){return t.filter(r=>fO.test(r))}function hO(t){let e=au(t),r=gO(e),n=KI(t,r);return Ot(n)}function jI(t,e){return be(e)?hO(t):cO(t,e)}function yO(t){return Z(ko(t))}function GI(t){return t.map(e=>um(e))}function um(t){return D(t)?qt(GI(t.allOf)):b(t)?B(GI(t.anyOf)):G(t)?yO(t.const):t}function SO(t,e){return t.reduceRight((r,n,o)=>{let i=pt({},Z(o),e);return F.IsExtendsTrueLike(i)?[n,...r]:r},[])}function kO(t,e){let r=um(e),n=SO(t,r);return An(n)}function IO(t){return An(t)}function VI(t,e){return G(e)&&s.IsEqual(e.const,"length")?Z(t.length):be(e)||at(e)?IO(t):kO(t,e)}function HI(t,e){return te(t)?LI(t.items,e):N(t)?jI(t.properties,e):V(t)?VI(t.items,e):oe()}function xO(t){return ge(t)||D(t)||b(t)?So(t):t}function RI(t,e,r){return L([t,e])?g.Update(HI(xO(t),e),{},r):_l(t,e,r)}function zI(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return RI(i,a,o)}function Dl(t,e={}){return E("InstanceType",[t],e)}function PO(t){return Le(t)?t.instanceType:oe()}function JI(t,e){return L([t])?g.Update(PO(t),{},e):Dl(t,e)}function QI(t,e,r,n={}){let o=P(t,e,r);return JI(o,n)}function Ll(t,e={}){return E("KeyOf",[t],e)}function ZI(){return B([Ut(),Tt(),hl()])}function XI(t){return Ut()}function wO(t){return t.reduce((r,n)=>gl(n)?[...r,Z(ko(n))]:Y(),[])}function ex(t){let e=s.Keys(t),r=wO(e);return An(r)}function tx(t){return Su(t)}function rx(t){let e=t.map((r,n)=>Z(n));return An(e)}function nx(t){return Ve(t)?ZI():te(t)?XI(t.items):N(t)?ex(t.properties):Me(t)?tx(t):V(t)?rx(t.items):oe()}function vO(t){return ge(t)||D(t)||b(t)?So(t):t}function YI(t,e){return L([t])?g.Update(nx(vO(t)),{},e):Ll(t,e)}function ox(t,e,r,n){let o=P(t,e,r);return YI(o,n)}function Fl(t,e,r,n,o={}){return E("Mapped",[t,e,r,n],o)}function bO(t){let e=He(t);return pm(e)}function sx(t){return t.reduce((e,r)=>[...e,...pm(r)],[])}function AO(t){return s.IsNumber(t)?[Z(`${t}`)]:[Z(t)]}function pm(t){return Ne(t)?sx(Wt(t.enum)):G(t)?AO(t.const):Ae(t)?bO(t.pattern):b(t)?sx(t.anyOf):[t]}function ax(t){return pm(t)}function TO(t){return Ae(t)?He(t.pattern):t}function RO(t,e,r,n,o,i){let a=g.Assign(t,{[r.name]:n}),u=P(a,e,o),p=TO(u),d=P(a,e,i);return lu(p)||mu(p)?{[p.const]:d}:{}}function CO(t,e,r,n,o,i){return n.reduce((a,u)=>[...a,RO(t,e,r,u,o,i)],[])}function EO(t){return t.reduce((e,r)=>[...e,O(r)],[])}function ux(t,e,r,n,o,i){let a=ax(n),u=CO(t,e,r,a,o,i),p=EO(u);return Se(p)}function ix(t,e,r,n,o,i,a){return L([n])?g.Update(ux(t,e,r,n,o,i),{},a):Fl(r,n,o,i,a)}function px(t,e,r,n,o,i,a){let u=P(t,e,n);return ix(t,e,r,u,o,i,a)}function $O(t,e){return s.Keys(t).filter(n=>e.includes(n)).reduce((n,o)=>({...n,[o]:jk(t,o,t[o])}),{})}function MO(t,e){return s.Keys(t).filter(n=>!e.includes(n)).reduce((n,o)=>({...n,[o]:P(t,{callstack:[]},t[o])}),{})}function OO(t,e){let r=Bk(t),n=$O(t,r),o=MO(t,r),i={...n,...o};return g.Update(i,{},e)}function dx(t,e,r,n){let o=g.Assign(t,r);return OO(o,n)}function Nl(t,e={}){return E("NonNullable",[t],e)}function _O(t){let e=B([li(),wl()]);return Eu(t,e,{})}function lx(t,e){return L([t])?g.Update(_O(t),{},e):Nl(t,e)}function mx(t,e,r,n){let o=P(t,e,r);return lx(o,n)}function ql(t,e,r={}){return E("Omit",[t,e],r)}function Mu(t){let e=So(t);return N(e)?e.properties:Y()}function DO(t,e){return s.Keys(t).reduce((n,o)=>e.includes(o)?n:{...n,[o]:t[o]},{})}function fx(t,e){let r=Mu(t),n=Io(e),o=DO(r,n);return O(o)}function cx(t,e,r){return L([t,e])?g.Update(fx(t,e),{},r):ql(t,e,r)}function gx(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return cx(i,a,o)}function Bl(t,e){return E("Options",[t,e],{})}function hx(t,e){return dm(t,e)}function dm(t,e){return L([t])?g.Update(t,{},e):Bl(t,e)}function yx(t,e,r,n){let o=P(t,e,r);return dm(o,n)}function Ul(t,e={}){return E("Parameters",[t],e)}function LO(t){let e=Fe(t)?t.parameters:[],r=Kr({},{callstack:[]},e);return Ke(r)}function Sx(t,e){return L([t])?g.Update(LO(t),{},e):Ul(t,e)}function kx(t,e,r,n){let o=P(t,e,r);return Sx(o,n)}function Wl(t,e={}){return E("Partial",[t],e)}function xx(t,e){let r=tr(t,e),n=Hr(r);return qr(g.Assign(t,{[e]:n}),e)}function Px(t){let e=t.map(r=>Hr(r));return Se(e)}function wx(t){let e=t.map(r=>Hr(r));return B(e)}function vx(t){let e=s.Keys(t).reduce((n,o)=>({...n,[o]:Uy(t[o])}),{});return O(e)}function Hr(t){return ge(t)?xx(t.$defs,t.$ref):D(t)?Px(t.allOf):b(t)?wx(t.anyOf):N(t)?vx(t.properties):O({})}function Ix(t,e){return L([t])?g.Update(Hr(t),{},e):Wl(t,e)}function bx(t,e,r,n){let o=P(t,e,r);return Ix(o,n)}function Kl(t,e,r={}){return E("Pick",[t,e],r)}function FO(t,e){return s.Keys(t).reduce((n,o)=>e.includes(o)?g.Assign(n,{[o]:t[o]}):n,{})}function Tx(t,e){let r=Mu(t),n=Io(e),o=FO(r,n);return O(o)}function Ax(t,e,r){return L([t,e])?g.Update(Tx(t,e),{},r):Kl(t,e,r)}function Rx(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return Ax(i,a,o)}function jl(t,e={}){return E("ReadonlyObject",[t],e)}function Ex(t){return so(lr(t))}function $x(t,e){let r=tr(t,e),n=zr(r);return qr(g.Assign(t,{[e]:n}),e)}function Mx(t){let e=t.map(r=>zr(r));return Se(e)}function Ox(t){let e=s.Keys(t).reduce((n,o)=>({...n,[o]:Wy(t[o])}),{});return O(e)}function _x(t){return so(Ke(t))}function Dx(t){let e=t.map(r=>zr(r));return B(e)}function zr(t){return te(t)?Ex(t.items):ge(t)?$x(t.$defs,t.$ref):D(t)?Mx(t.allOf):N(t)?Ox(t.properties):V(t)?_x(t.items):b(t)?Dx(t.anyOf):t}function Cx(t,e){return L([t])?g.Update(zr(t),{},e):jl(t)}function Lx(t,e,r,n){let o=P(t,e,r);return Cx(o,n)}function Fx(t,e,r,n){return n in t?Ru([n],t,t[n])?r:P(t,e,t[n]):r}function Nx(t,e){let r=tr(t,e),n=Jr(r);return qr(g.Assign(t,{[e]:n}),e)}function qx(t){let e=t.map(r=>Jr(r));return Se(e)}function Bx(t){let e=t.map(r=>Jr(r));return B(e)}function Ux(t){let e=s.Keys(t).reduce((n,o)=>({...n,[o]:ao(t[o])}),{});return O(e)}function Jr(t){return ge(t)?Nx(t.$defs,t.$ref):D(t)?qx(t.allOf):b(t)?Bx(t.anyOf):N(t)?Ux(t.properties):O({})}function Gl(t,e={}){return E("Required",[t],e)}function Wx(t,e){return L([t])?g.Update(Jr(t),{},e):Gl(t,e)}function Kx(t,e,r,n){let o=P(t,e,r);return Wx(o,n)}function Vl(t,e={}){return E("ReturnType",[t],e)}function NO(t){return Fe(t)?t.returnType:oe()}function jx(t,e){return L([t])?g.Update(NO(t),{},e):Vl(t,e)}function Gx(t,e,r,n={}){let o=P(t,e,r);return jx(o,n)}function qO(t){return mo(t)?V(t.items)?lm(t.items.items):$e(t.items)?[t]:se(t.items)?[t]:[oe()]:[t]}function lm(t){return t.reduce((r,n)=>[...r,...qO(n)],[])}function L(t){return s.TakeLeft(t,(e,r)=>se(e)?!1:L(r),()=>!0)}function Ai(t,e,r){return Ny(t)?Ai(t.type,"remove",r):Ly(t)?Ai(t.type,e,"remove"):Fy(t)?Ai(t.type,"add",r):Dy(t)?Ai(t.type,e,"add"):[t,e,r]}function BO(t,e){return s.IsEqual(t,"remove")?ou(e):s.IsEqual(t,"add")?In(e):e}function UO(t,e){return s.IsEqual(t,"remove")?ao(e):s.IsEqual(t,"add")?kn(e):e}function Pi(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 lm(n)}function Rt(t,e,r){return r.map(n=>P(t,e,n))}function WO(t,e,r,n,o){return s.IsEqual(r,"Awaited")?Vx(t,e,n[0],o):s.IsEqual(r,"Capitalize")?dI(t,e,n[0],o):s.IsEqual(r,"Conditional")?gI(t,e,n[0],n[1],n[2],n[3],o):s.IsEqual(r,"ConstructorParameters")?yI(t,e,n[0],o):s.IsEqual(r,"Evaluate")?Hk(t,e,n[0],o):s.IsEqual(r,"Exclude")?xI(t,e,n[0],n[1],o):s.IsEqual(r,"Extract")?AI(t,e,n[0],n[1],o):s.IsEqual(r,"Index")?zI(t,e,n[0],n[1],o):s.IsEqual(r,"InstanceType")?QI(t,e,n[0],o):s.IsEqual(r,"Interface")?Nk(t,e,n[0],n[1],o):s.IsEqual(r,"KeyOf")?ox(t,e,n[0],o):s.IsEqual(r,"Lowercase")?lI(t,e,n[0],o):s.IsEqual(r,"Mapped")?px(t,e,n[0],n[1],n[2],n[3],o):s.IsEqual(r,"Module")?dx(t,e,n[0],o):s.IsEqual(r,"NonNullable")?mx(t,e,n[0],o):s.IsEqual(r,"Pick")?Rx(t,e,n[0],n[1],o):s.IsEqual(r,"Options")?yx(t,e,n[0],n[1]):s.IsEqual(r,"Parameters")?kx(t,e,n[0],o):s.IsEqual(r,"Partial")?bx(t,e,n[0],o):s.IsEqual(r,"Omit")?gx(t,e,n[0],n[1],o):s.IsEqual(r,"ReadonlyObject")?Lx(t,e,n[0],o):s.IsEqual(r,"Record")?CS(t,e,n[0],n[1],o):s.IsEqual(r,"Required")?Kx(t,e,n[0],o):s.IsEqual(r,"ReturnType")?Gx(t,e,n[0],o):s.IsEqual(r,"TemplateLiteral")?nk(t,e,n[0],o):s.IsEqual(r,"Uncapitalize")?mI(t,e,n[0],o):s.IsEqual(r,"Uppercase")?cI(t,e,n[0],o):E(r,n,o)}function P(t,e,r){let n=pi(r),o=Ai(r,di(r)?"add":"none",We(r)?"add":"none"),i=Qt(o[0])?o[0].Clone():o[0],a=se(i)?Fx(t,e,i,i.$ref):te(i)?lr(P(t,e,i.items),iu(i)):st(i)?mr(P(t,e,i.iteratorItems),Ky(i)):Cu(i)?am(t,e,i.target,i.arguments):Le(i)?xn(Rt(t,e,i.parameters),P(t,e,i.instanceType),jy(i)):Fr(i)?WO(t,e,i.action,i.parameters,i.options):Fe(i)?Pn(Rt(t,e,i.parameters),P(t,e,i.returnType),Gy(i)):D(i)?qt(Rt(t,e,i.allOf),Yy(i)):ut(i)?cr(P(t,e,i.iteratorItems),tS(i)):N(i)?O(Pi(t,e,i.properties),zy(i)):Ge(i)?dr(P(t,e,i.item),qy(i)):Me(i)?$S(_t(i),P(t,e,Xe(i))):mo(i)?Pl(P(t,e,i.items)):V(i)?Ke(Kr(t,e,i.items),gS(i)):b(i)?B(Rt(t,e,i.anyOf),Jy(i)):i,u=n?so(a):a;return BO(o[1],UO(o[2],u))}function nr(t,e){return P(t,{callstack:[]},e)}function Hx(t){return Ge(t)?Hx(t.item):t}function zx(t,e){return L([t])?g.Update(Hx(t),{},e):Hl(t,e)}function Vx(t,e,r,n){let o=P(t,e,r);return zx(o,n)}function Hl(t,e={}){return E("Awaited",[t],e)}function Qr(t,e={}){return im(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 pl(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]=nu(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 Jx(t,e,r){return s.IsArray(r)?r.map(n=>qe(t,e.items,n)):r}function Qx(t,e,r){return e.Clean(r)}function Yx(t,e,r){return qe({...t,...e.$defs},kt(e.$ref),r)}function KO(t,e){let r=s.HasPropertyKey(e,"unevaluatedProperties")?{additionalProperties:e.unevaluatedProperties}:{},n=nr(t,e),o=Qr(n);return N(o)?hx(o,r):o}function Zx(t,e,r){let n=KO(t,e);return qe(t,n,r)}function Ou(t){return s.HasPropertyKey(t,"additionalProperties")?t.additionalProperties:void 0}function Xx(t,e,r){if(!s.IsObject(r)||s.IsArray(r))return r;let n=Ou(e);for(let o of s.Keys(r)){if(s.HasPropertyKey(e.properties,o)){r[o]=qe(t,e.properties[o],r[o]);continue}if(s.IsBoolean(n)&&s.IsEqual(n,!0)||de(n)&&ae(t,n,r[o])){r[o]=qe(t,n,r[o]);continue}delete r[o]}return r}function eP(t,e,r){if(!s.IsObject(r))return r;let n=Ou(e),[o,i]=[new RegExp(_t(e)),Xe(e)];for(let a of s.Keys(r)){if(o.test(a)){r[a]=qe(t,i,r[a]);continue}if(s.IsBoolean(n)&&s.IsEqual(n,!0)||de(n)&&ae(t,n,r[a])){r[a]=qe(t,n,r[a]);continue}delete r[a]}return r}function tP(t,e,r){return s.HasPropertyKey(t,e.$ref)?qe(t,t[e.$ref],r):r}function rP(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]=qe(t,e.items[o],r[o]);return s.IsGreaterThan(r.length,n)?r.slice(0,n):r}function jO(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 GO(t){return s.IsClassInstance(t)?t:jO(t)}function VO(t){return t.map(e=>ue(e))}function HO(t){return t.slice()}function zO(t){return new Map(ue([...t.entries()]))}function JO(t){return new Set(ue([...t.values()]))}function ue(t){return nt.IsTypeArray(t)?HO(t):nt.IsMap(t)?zO(t):nt.IsSet(t)?JO(t):s.IsArray(t)?VO(t):s.IsObject(t)?GO(t):t}function nP(t,e){return JSON.stringify(t).localeCompare(JSON.stringify(e))}function Ti(t,e=1){return t.sort((r,n)=>{let o=vn(r,n);return(s.IsEqual(o,"disjoint")?nP(r,n):s.IsEqual(o,"right-inside")?1:s.IsEqual(o,"left-inside")?-1:nP(r,n))*e})}function oP(t,e,r){for(let n of Ti(e.anyOf)){let o=qe(t,n,ue(r));if(ae(t,n,o))return o}return r}function qe(t,e,r){return te(e)?Jx(t,e,r):Qt(e)?Qx(t,e,r):ge(e)?Yx(t,e,r):D(e)?Zx(t,e,r):N(e)?Xx(t,e,r):Me(e)?eP(t,e,r):se(e)?tP(t,e,r):V(e)?rP(t,e,r):b(e)?oP(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 qe(e,r,n)}var Q={};Ct(Q,{Fail:()=>En,IsOk:()=>mm,Ok:()=>T,TryArray:()=>QO,TryBigInt:()=>cm,TryBoolean:()=>u_,TryNull:()=>c_,TryNumber:()=>y_,TryString:()=>S_,TryUndefined:()=>w_});function mm(t){return s.IsObject(t)&&s.HasPropertyKey(t,"value")}function T(t){return{value:t}}function En(){}function QO(t){return s.IsArray(t)?T(t):T([t])}function YO(t){return s.IsEqual(t,!0)?T(BigInt(1)):T(BigInt(0))}var ZO=/^-?(0|[1-9]\d*)n$/,XO=/^-?(0|[1-9]\d*)\.\d+$/,e_=/^-?(0|[1-9]\d*)$/;function t_(t){return ZO.test(t)}function r_(t){return XO.test(t)}function n_(t){return e_.test(t)}function o_(t){let e=t.toLowerCase();return t_(t)?T(BigInt(t.slice(0,t.length-1))):r_(t)?T(BigInt(t.split(".")[0])):n_(t)?T(BigInt(t)):s.IsEqual(e,"false")?T(BigInt(0)):s.IsEqual(e,"true")?T(BigInt(1)):void 0}function cm(t){return s.IsBigInt(t)?T(t):s.IsBoolean(t)?YO(t):s.IsNumber(t)?T(BigInt(Math.trunc(t))):s.IsNull(t)?T(BigInt(0)):s.IsString(t)?o_(t):s.IsUndefined(t)?T(BigInt(0)):void 0}function i_(t){return s.IsEqual(t,BigInt(0))?T(!1):s.IsEqual(t,BigInt(1))?T(!0):void 0}function s_(t){return s.IsEqual(t,0)?T(!1):s.IsEqual(t,1)?T(!0):void 0}function a_(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 u_(t){return s.IsBigInt(t)?i_(t):s.IsBoolean(t)?T(t):s.IsNumber(t)?s_(t):s.IsNull(t)?T(!1):s.IsString(t)?a_(t):s.IsUndefined(t)?T(!1):void 0}function p_(t){return s.IsEqual(t,BigInt(0))?T(null):void 0}function d_(t){return s.IsEqual(t,!1)?T(null):void 0}function l_(t){return s.IsEqual(t,0)?T(null):void 0}function m_(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 c_(t){return s.IsBigInt(t)?p_(t):s.IsBoolean(t)?d_(t):s.IsNumber(t)?l_(t):s.IsNull(t)?T(null):s.IsString(t)?m_(t):s.IsUndefined(t)?T(null):void 0}var iP=BigInt(Number.MAX_SAFE_INTEGER),sP=BigInt(Number.MIN_SAFE_INTEGER);function f_(t){return t<=iP&&t>=sP?T(Number(t)):void 0}function g_(t){return T(t?1:0)}function h_(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=cm(t);return mm(n)?n.value<=iP&&n.value>=sP?T(Number(n.value)):void 0:void 0}function y_(t){return s.IsBigInt(t)?f_(t):s.IsBoolean(t)?g_(t):s.IsNumber(t)?T(t):s.IsNull(t)?T(0):s.IsString(t)?h_(t):s.IsUndefined(t)?T(0):void 0}function S_(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 k_(t){return s.IsEqual(t,BigInt(0))?T(void 0):void 0}function I_(t){return s.IsEqual(t,!1)?T(void 0):void 0}function x_(t){return s.IsEqual(t,0)?T(void 0):void 0}function P_(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 w_(t){return s.IsBigInt(t)?k_(t):s.IsBoolean(t)?I_(t):s.IsNumber(t)?x_(t):s.IsNull(t)?T(void 0):s.IsString(t)?P_(t):s.IsUndefined(t)?T(t):void 0}function aP(t,e,r){return Q.TryArray(r).value.map(o=>Te(t,e.items,o))}function uP(t,e,r){return e.Convert(r)}function pP(t,e,r){let n=Q.TryBigInt(r);return Q.IsOk(n)?n.value:r}function dP(t,e,r){let n=Q.TryBoolean(r);return Q.IsOk(n)?n.value:r}function lP(t,e,r){return Te({...t,...e.$defs},kt(e.$ref),r)}function _u(t,e,r){if(e.anyOf.some(a=>ae(t,a,r)))return r;let i=e.anyOf.map(a=>Te(t,a,ue(r))).find(a=>ae(t,e,a));return s.IsUndefined(i)?r:i}function mP(t,e,r){let n=po(e);return _u(t,n,r)}function cP(t,e,r){let n=Q.TryNumber(r);return Q.IsOk(n)?Math.trunc(n.value):r}function fP(t,e,r){let n=nr(t,e),o=Qr(n);return Te(t,o,r)}function v_(t,e,r){let n=Q.TryBigInt(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function b_(t,e,r){let n=Q.TryBoolean(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function A_(t,e,r){let n=Q.TryNumber(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function T_(t,e,r){let n=Q.TryString(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function gP(t,e,r){return s.IsEqual(e.const,r)?r:rS(e)?v_(t,e,r):nS(e)?b_(t,e,r):lu(e)?A_(t,e,r):mu(e)?T_(t,e,r):Y()}function hP(t,e,r){let n=Q.TryNull(r);return Q.IsOk(n)?n.value:r}function yP(t,e,r){let n=Q.TryNumber(r);return Q.IsOk(n)?n.value:r}function Du(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]=Te(t,r,n[u]));return n}function Ri(t,e,r){return We(t)&&s.IsUndefined(r[e])}function R_(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)||Ri(a,u,r)||(r[u]=Te(t,a,r[u]));return s.HasPropertyKey(e,"additionalProperties")&&s.IsObject(e.additionalProperties)?Du(t,n,e.additionalProperties,r):r}function SP(t,e,r){return s.IsObjectNotArray(r)?R_(t,e,r):r}function C_(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]=Te(t,a,r[u]));return s.HasPropertyKey(e,"additionalProperties")&&s.IsObject(e.additionalProperties)?Du(t,n,e.additionalProperties,r):r}function kP(t,e,r){return s.IsObjectNotArray(r)?C_(t,e,r):r}function IP(t,e,r){return s.HasPropertyKey(t,e.$ref)?Te(t,t[e.$ref],r):r}function xP(t,e,r){let n=Q.TryString(r);return Q.IsOk(n)?n.value:r}function PP(t,e,r){let n=He(e.pattern);return Te(t,n,r)}function wP(t,e,r){if(!s.IsArray(r))return r;for(let n=0;n<Math.min(e.items.length,r.length);n++)r[n]=Te(t,e.items[n],r[n]);return r}function vP(t,e,r){let n=Q.TryUndefined(r);return Q.IsOk(n)?n.value:r}function bP(t,e,r){let n=Q.TryUndefined(r);return Q.IsOk(n)?void 0:r}function Te(t,e,r){return te(e)?aP(t,e,r):Qt(e)?uP(t,e,r):Bt(e)?pP(t,e,r):At(e)?dP(t,e,r):ge(e)?lP(t,e,r):Ne(e)?mP(t,e,r):at(e)?cP(t,e,r):D(e)?fP(t,e,r):G(e)?gP(t,e,r):wn(e)?hP(t,e,r):be(e)?yP(t,e,r):N(e)?SP(t,e,r):Me(e)?kP(t,e,r):se(e)?IP(t,e,r):Ze(e)?xP(t,e,r):Ae(e)?PP(t,e,r):V(e)?wP(t,e,r):Tn(e)?vP(t,e,r):b(e)?_u(t,e,r):Kt(e)?bP(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 Te(e,r,n)}function AP(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 TP(t,e,r){return e.Default(r)}function RP(t,e,r){return _e({...t,...e.$defs},kt(e.$ref),r)}function CP(t,e){return s.IsUndefined(e)?s.IsFunction(t.default)?t.default():ue(t.default):e}function EP(t,e,r){let n=nr(t,e),o=Qr(n);return _e(t,o,r)}function $P(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)&&(We(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 MP(t,e,r){if(!s.IsObject(r))return r;let[n,o]=[new RegExp(_t(e)),Xe(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 OP(t,e,r){return s.HasPropertyKey(t,e.$ref)?_e(t,t[e.$ref],r):r}function _P(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 DP(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)?CP(e,r):r;return te(e)?AP(t,e,n):Qt(e)?TP(t,e,n):ge(e)?RP(t,e,n):D(e)?EP(t,e,n):N(e)?$P(t,e,n):Me(e)?MP(t,e,n):se(e)?OP(t,e,n):V(e)?_P(t,e,n):b(e)?DP(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 xo(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 E_(t,e,r){return e["~codec"].decode(r)}function $_(t,e,r){return e["~codec"].encode(r)}function fe(t,e,r,n){return cl(r)?s.IsEqual(t,"Decode")?E_(e,r,n):$_(e,r,n):n}function M_(t,e,r,n){if(!s.IsArray(n))return Y();for(let o=0;o<n.length;o++)n[o]=he(t,e,r.items,n[o]);return fe(t,e,r,n)}function O_(t,e,r,n){let o=fe(t,e,r,n);if(!s.IsArray(o))return o;for(let i=0;i<o.length;i++)o[i]=he(t,e,r.items,o[i]);return o}function LP(t,e,r,n){return s.IsEqual(t,"Decode")?M_(t,e,r,n):O_(t,e,r,n)}function FP(t,e,r,n){return n=he(t,{...e,...r.$defs},kt(r.$ref),n),fe(t,e,r,n)}function NP(t){return t.reduce((e,r)=>({...e,...r}),{})}function qP(t,e){for(let r of e)if(!s.IsDeepEqual(t,r))return r;return t}function __(t,e,r,n){if(s.IsEqual(r.allOf.length,0))return fe(t,e,r,n);let o=r.allOf.map(u=>he(t,e,u,Ht(u,ue(n)))),a=o.every(u=>s.IsObject(u))?NP(o):qP(n,o);return fe(t,e,r,a)}function D_(t,e,r,n){if(s.IsEqual(r.allOf.length,0))return fe(t,e,r,n);let o=fe(t,e,r,n),i=r.allOf.map(u=>he(t,e,u,Ht(u,ue(o))));return i.every(u=>s.IsObject(u))?NP(i):qP(o,i)}function BP(t,e,r,n){return s.IsEqual(t,"Decode")?__(t,e,r,n):D_(t,e,r,n)}function L_(t,e,r,n){if(!s.IsObjectNotArray(n))return Y();for(let o of s.Keys(r.properties))!s.HasPropertyKey(n,o)||Ri(r.properties[o],o,n)||(n[o]=he(t,e,r.properties[o],n[o]));return fe(t,e,r,n)}function F_(t,e,r,n){let o=fe(t,e,r,n);if(!s.IsObjectNotArray(o))return o;for(let i of s.Keys(r.properties))!s.HasPropertyKey(o,i)||Ri(r.properties[i],i,o)||(o[i]=he(t,e,r.properties[i],o[i]));return o}function UP(t,e,r,n){return s.IsEqual(t,"Decode")?L_(t,e,r,n):F_(t,e,r,n)}function N_(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]=he(t,e,Xe(r),n[i]);return fe(t,e,r,n)}function q_(t,e,r,n){let o=fe(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]=he(t,e,Xe(r),o[a]));return o}function WP(t,e,r,n){return s.IsEqual(t,"Decode")?N_(t,e,r,n):q_(t,e,r,n)}function KP(t,e,r,n){return s.HasPropertyKey(e,r.$ref)?he(t,e,e[r.$ref],n):n}function jP(t,e,r,n){return s.IsEqual(t,"Decode")?fe(t,e,r,KP(t,e,r,n)):KP(t,e,r,fe(t,e,r,n))}function B_(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]=he(t,e,r.items[o],n[o]);return fe(t,e,r,n)}function U_(t,e,r,n){let o=fe(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]=he(t,e,r.items[i],o[i]);return o}function GP(t,e,r,n){return s.IsEqual(t,"Decode")?B_(t,e,r,n):U_(t,e,r,n)}function W_(t,e,r,n){for(let o of Ti(r.anyOf,1)){if(!ae(e,o,n))continue;let i=he(t,e,o,n);return fe(t,e,r,i)}return n}function K_(t,e,r,n){let o=fe(t,e,r,n);for(let i of Ti(r.anyOf,-1)){let a=he(t,e,i,ue(o));if(ae(e,i,a))return a}return o}function VP(t,e,r,n){return s.IsEqual(t,"Decode")?W_(t,e,r,n):K_(t,e,r,n)}function he(t,e,r,n){return te(r)?LP(t,e,r,n):ge(r)?FP(t,e,r,n):D(r)?BP(t,e,r,n):N(r)?UP(t,e,r,n):Me(r)?WP(t,e,r,n):se(r)?jP(t,e,r,n):V(r)?GP(t,e,r,n):b(r)?VP(t,e,r,n):fe(t,e,r,n)}var fm=class extends Yr{constructor(e,r){super("Decode",e,r)}};function j_(t,e,r){if(!ae(t,e,r))throw new fm(r,gr(t,e,r));return r}function G_(t,e,r){return he("Decode",t,e,r)}var FRe=xo([(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)=>j_(t,e,r),(t,e,r)=>G_(t,e,r)]);var gm=class extends Yr{constructor(e,r){super("Encode",e,r)}};function V_(t,e,r){if(!ae(t,e,r))throw new gm(r,gr(t,e,r));return r}function H_(t,e,r){return he("Encode",t,e,r)}var JRe=xo([(t,e,r)=>ue(r),(t,e,r)=>H_(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)=>V_(t,e,r)]);var Fu=class extends Yr{constructor(e,r){super("Parse",e,r)}};function z_(t,e,r){if(!ae(t,e,r))throw new Fu(r,gr(t,e,r));return r}var J_=xo([(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)=>z_(t,e,r)]);var Y_=O({type:Z("insert"),path:Tt(),value:Yt()}),Z_=Object({type:Z("update"),path:Tt(),value:Yt()}),X_=O({type:Z("delete"),path:Tt()}),MMe=B([Y_,Z_,X_]);var Q0e=new Rg(512);function YP(t){return{success:!1,error:{issues:[{path:[],message:t}]}}}function hm(){return{safeParse(t){return t===void 0?{success:!0,data:void 0}:!t||typeof t!="object"||Array.isArray(t)?YP("expected config object"):Object.keys(t).length>0?YP("config must be empty"):{success:!0,data:t}},jsonSchema:{type:"object",additionalProperties:!1,properties:{}}}}function u0(t,e){let r=!1,n;return()=>(r||(n=(typeof t=="function"?t():t)??e,r=!0),n)}function Nu({id:t,name:e,description:r,kind:n,configSchema:o=hm,reload:i,nodeHostCommands:a,securityAuditCollectors:u,register:p}){let d=u0(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 c0(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=m0("git",["rev-parse","--show-toplevel"],{cwd:p.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();d&&i.add(ZP(d,".worktrees"))}catch{}if(i.size===0)return;let u=0;for(let p of i)try{let d=p0(p);for(let l of d){if(!l.startsWith("openclaw-worktree-"))continue;let m=ZP(p,l);try{let c=d0(m);if(!c.isDirectory()||c.mtimeMs>n||o.has(m))continue;l0(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 f0(t){let e=null,r=null,n=!1,o=!1,i=t.registerTool;Nn(t.runtime);let a=m=>{if(n){m&&!o&&(Nn(t.runtime,m.config),o=!0);return}let c=t.pluginConfig??{};Pm(c),m?(Nn(t.runtime,m.config),o=!0):(Nn(t.runtime),o=!1),e=new xa(K.maxSessions,K.maxPersistedSessions),r=new qs(e),Bu(e),Uu(r),r.start(),c0(e),e.bootstrapMaintenanceSchedules(),n=!0},u=()=>{r&&r.stop(),e&&e.killAll("shutdown"),e&&e.dispose(),r=null,e=null,n=!1,o=!1,Nn(void 0),Uu(null),Bu(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=gf(m);t.registerInteractiveHandler({...c,handler:async h=>(a(),c.handler(h))})};p(m=>uc(m),{optional:!1,name:"agent_launch"}),p(m=>Dc(m),{optional:!1,name:"agent_sessions"}),p(m=>Lc(m),{optional:!1,name:"agent_kill"}),p(m=>ws(m),{optional:!1,name:"agent_output"}),p(m=>Wc(m),{optional:!1,name:"agent_respond"}),p(m=>Kc(m),{optional:!1,name:"agent_request_plan_approval"}),p(m=>Gc(m),{optional:!1,name:"agent_send_plan_offer"}),p(m=>Vc(m),{optional:!1,name:"agent_stats"}),p(m=>$s(m),{optional:!1,name:"agent_merge"}),p(m=>jo(m),{optional:!1,name:"agent_pr"}),p(m=>nf(m),{optional:!1,name:"agent_worktree_cleanup"}),p(m=>of(m),{optional:!1,name:"agent_worktree_status"}),p(m=>sf(m),{optional:!1,name:"goal_launch"}),p(m=>uf(m),{optional:!1,name:"goal_status"}),p(m=>pf(m),{optional:!1,name:"goal_stop"}),l("telegram"),l("discord"),yf(d),Sf(d),kf(d),If(d),xf(d),Pf(d),vf(d),bf(d),Af(d),t.registerService({id:"openclaw-code-agent",start:a,stop:u})}var GDe=Nu({id:"openclaw-code-agent",name:"OpenClaw Code Agent",description:"Multi-session coding-agent orchestration from OpenClaw chat",register:f0});export{GDe as default,f0 as register};
227
+ `)}}buildDelegateNotification(e){let{session:r,branchName:n,baseBranch:o,diffSummary:i,originThreadLine:a}=e,u=i.commitMessages.slice(0,5).map(l=>`\u2022 ${l.hash} ${l.message} (${l.author})`),p=i.commits>5?`...and ${i.commits-5} more`:void 0,d=r.prompt?r.prompt.slice(0,500):"(no prompt)";return{label:"worktree-delegate",wakeMessage:Wp({sessionName:r.name,sessionId:r.id,branchName:n,baseBranch:o,promptSnippet:d,commitLines:u,moreNote:p,originThreadLine:a,diffSummary:i}),notifyUser:"never"}}};function _g(t,e=1e3){let r=!Number.isFinite(e),n=typeof t.getOutput=="function"?t.getOutput():[],o=r?n.join(`
228
+ `):_R(t);return r?o:o.length>e?Dg(t)?es(o,e):uc(o,e):o}function _R(t){let e=typeof t.getOutput=="function"?t.getOutput():[],r=e.join(`
229
+ `).trim();return r?Dg(t)?DR(r)??r:e.slice(-20).join(`
230
+ `):""}function Dg(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 DR(t){let r=t.split(/\n\s*\n+/).map(n=>n.trim()).filter(n=>/[A-Za-z0-9]/.test(n)).at(-1);if(r)return r.length>=120||r.includes(`
231
+ `)?r:void 0}ir();Pt();ze();import{unlinkSync as LR}from"fs";var Aa=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();Uo();Pt();var Lg=10080*60*1e3,FR=300*1e3,Fg="tmp-output:cleanup";function NR(t){return t instanceof Error?t.message:String(t)}var Ta=class{constructor(e){this.deps=e}deps;scheduler=new Aa;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+Lg,()=>{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<Lg))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}: ${NR(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(Fg);let r=this.deps.store.getNextTmpOutputCleanupAt(e);r!=null&&this.schedule(Fg,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()+FR))})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.deps.store.hasOutputPathReference(e)))try{LR(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"}};Ns();var Ng=new Set(["completed","failed","killed"]),qR=new Set(["starting","running"]),BR=5e3,Ra=class{registry;sessions;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueue=new Jn;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 wa,this.sessions=this.registry.sessions,this.store=new aa(n.store),this.metrics=new ua,this.wakeDispatcher=new fa,this.interactions=new ga(this.store.actionTokenStore,Pr),this.references=new Ys(this.sessions,this.store),this.stateSync=new Qs({store:this.store,sessions:this.sessions,resolveSession:o=>this.references.resolveActive(o)}),this.notifications=new ha(this.wakeDispatcher,(o,i)=>this.stateSync.applySessionPatch(o,i)),this.worktrees=new ya,this.restore=new Js(o=>this.store.getPersistedSession(o)),this.worktreeMessages=new ba,this.worktreeStrategy=new ea({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:ks,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(()=>(Bs(),df));return{success:(await a().execute("auto-pr",{session:o.id,base_branch:i}))?.meta?.success===!0}}}),this.questions=new ka(this.pendingAskUserQuestions,(o,i)=>this.dispatchSessionNotification(o,i),o=>{this.lastWaitingEventTimestamps.delete(o)},(o,i)=>this.interactions.getQuestionButtons(o,i)),this.reminders=new Sa(o=>this.buildRoutingProxy(o),(o,i)=>this.notifications.dispatch(o,i),(o,i)=>this.updatePersistedSession(o,i),o=>this.getWorktreeDecisionButtons(o)),this.maintenance=new Ta({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 xa({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 Pa({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 va({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||sc(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 xs({...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(Ng.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}Ng.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 Oi({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 ei(n,r)}dispatchPlanApprovalFallback(e,r,n){let o=new Date().toISOString();this.notifications.dispatch(e,{label:"plan-approval-fallback",userMessage:Qo({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:Qn(e,r,!0),wakeMessageOnNotifyFailed:Ia({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=Hp(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=ye(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(Xo(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(`
232
+ `);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:Qn({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:ye(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||!zs(e,r))||!r?e:fs(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,Ls({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(`
233
+ `),buttons:[[this.makeActionButton(r,"worktree-create-pr","Open PR")]]})}getStoppedStatusLabel(e){return Jo(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=>qp({sessionId:o,sessionName:e.sessionName,taskName:e.name,summary:r,originThreadLine:vo(i),canonicalStatusDelivered:p});this.dispatchSessionNotification(i,{label:n,userMessage:r,notifyUser:"always",completionWakeSummaryRequired:a,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<BR?!1:(this.lastWaitingEventTimestamps.set(e,r),!0)}originThreadLine(e){return vo(e)}extractLastOutputLine(e){return e.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(e,r=1e3){return _g(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())qR.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()}};le();ze();var Bg=class{#t;#r;#e=new Map;constructor(t){this.#t=qg(t,1),this.#r=this.#t}get maxEntries(){return this.#r}get size(){return this.#e.size}setMaxEntriesForTest(t){this.#r=typeof t=="number"?qg(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 qg(t,e){return!Number.isFinite(t)||t<=0?e:Math.max(1,Math.floor(t))}var UR="\\x1b\\[[\\x20-\\x3f]*[\\x40-\\x7e]",WR="\\x1b\\][^\\x07\\x1b]*(?:\\x1b\\\\|\\x07)",RW=new RegExp(UR,"g"),CW=new RegExp(WR,"g"),EW=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;var ee={};Ct(ee,{Match:()=>KR});function KR(t,e){return e[t.length]?.(...t)??(()=>{throw Error("Invalid Arguments")})()}var s={};Ct(s,{Entries:()=>mC,EntriesRegExp:()=>lC,Every:()=>uC,EveryAll:()=>pC,GraphemeCount:()=>iC,HasPropertyKey:()=>dC,IsArray:()=>ri,IsAsyncIterator:()=>JR,IsBigInt:()=>ti,IsBoolean:()=>Hg,IsClassInstance:()=>nC,IsConstructor:()=>QR,IsDeepEqual:()=>ud,IsEqual:()=>J,IsFunction:()=>zg,IsGreaterEqualThan:()=>Qg,IsGreaterThan:()=>eC,IsInteger:()=>sd,IsIterator:()=>YR,IsLessEqualThan:()=>Jg,IsLessThan:()=>tC,IsMaxLength:()=>sC,IsMinLength:()=>aC,IsMultipleOf:()=>rC,IsNull:()=>$a,IsNumber:()=>Ma,IsObject:()=>mn,IsObjectNotArray:()=>ZR,IsString:()=>Oa,IsSymbol:()=>XR,IsUndefined:()=>ad,IsUnsafePropertyKey:()=>Yg,IsValueLike:()=>oC,Keys:()=>Ea,Symbols:()=>cC,TakeLeft:()=>_a,Values:()=>fC});function Cr(t,e,r){return t>=e&&t<=r}function Ug(t){return Cr(t,127462,127487)}function jR(t){return Cr(t,65024,65039)}function GR(t){return Cr(t,768,879)||Cr(t,6832,6911)||Cr(t,7616,7679)||Cr(t,65056,65071)}function Ca(t){return t>65535?2:1}function Wg(t,e){for(;e<t.length;){let r=t.codePointAt(e);if(GR(r)||jR(r))e+=Ca(r);else break}return e}function id(t,e){let r=t.codePointAt(e),n=e+Ca(r);for(n=Wg(t,n);n<t.length-1&&t[n]==="\u200D";){let o=t.codePointAt(n+1);n+=1+Ca(o),n=Wg(t,n)}return Ug(r)&&n<t.length&&Ug(t.codePointAt(n))&&(n+=Ca(t.codePointAt(n))),n}function Kg(t){return Cr(t,55296,56319)||Cr(t,768,879)||t===8205}function jg(t){let e=0,r=0;for(;r<t.length;)r=id(t,r),e++;return e}function VR(t,e){if(e===0)return!0;let r=0,n=0;for(;n<t.length;)if(n=id(t,n),r++,r>=e)return!0;return!1}function HR(t,e){let r=0,n=0;for(;n<t.length;)if(n=id(t,n),r++,r>e)return!1;return!0}function Gg(t,e){if(e===0)return!0;let r=0;for(;r<t.length;){if(Kg(t.charCodeAt(r)))return VR(t,e);if(r++,r>=e)return!0}return!1}function Vg(t,e){let r=0;for(;r<t.length;){if(Kg(t.charCodeAt(r)))return HR(t,e);if(r++,r>e)return!1}return!0}function ri(t){return Array.isArray(t)}function JR(t){return mn(t)&&Symbol.asyncIterator in t}function ti(t){return J(typeof t,"bigint")}function Hg(t){return J(typeof t,"boolean")}function QR(t){if(ad(t)||!zg(t))return!1;let e=Function.prototype.toString.call(t);return!!(/^class\s/.test(e)||/\[native code\]/.test(e))}function zg(t){return J(typeof t,"function")}function sd(t){return Number.isInteger(t)}function YR(t){return mn(t)&&Symbol.iterator in t}function $a(t){return J(t,null)}function Ma(t){return Number.isFinite(t)}function ZR(t){return mn(t)&&!ri(t)}function mn(t){return J(typeof t,"object")&&!$a(t)}function Oa(t){return J(typeof t,"string")}function XR(t){return J(typeof t,"symbol")}function ad(t){return J(t,void 0)}function J(t,e){return t===e}function eC(t,e){return t>e}function tC(t,e){return t<e}function Jg(t,e){return t<=e}function Qg(t,e){return t>=e}function rC(t,e){if(ti(t)||ti(e))return BigInt(t)%BigInt(e)===0n;let r=1e-10;if(!Ma(t)||sd(t)&&1/e%1===0)return!0;let n=t%e;return Math.min(Math.abs(n),Math.abs(n-e))<r}function nC(t){if(!mn(t))return!1;let e=globalThis.Object.getPrototypeOf(t);return $a(e)?!1:J(typeof e.constructor,"function")&&!(J(e.constructor,globalThis.Object)||J(e.constructor.name,"Object"))}function oC(t){return ti(t)||Hg(t)||$a(t)||Ma(t)||Oa(t)||ad(t)}function iC(t){return jg(t)}function sC(t,e){return Vg(t,e)}function aC(t,e){return Gg(t,e)}function uC(t,e,r){for(let n=e;n<t.length;n++)if(!r(t[n],n))return!1;return!0}function pC(t,e,r){let n=!0;for(let o=e;o<t.length;o++)r(t[o],o)||(n=!1);return n}function _a(t,e,r){return J(t.length,0)?r():e(t[0],t.slice(1))}function Yg(t){return J(t,"__proto__")||J(t,"constructor")||J(t,"prototype")}function dC(t,e){return Yg(e)?Object.prototype.hasOwnProperty.call(t,e):e in t}function lC(t){return Ea(t).map(e=>[new RegExp(`^${e}$`),t[e]])}function mC(t){return Object.entries(t)}function Ea(t){return Object.getOwnPropertyNames(t)}function cC(t){return Object.getOwnPropertySymbols(t)}function fC(t){return Object.values(t)}function gC(t,e){if(!mn(e))return!1;let r=Ea(t);return J(r.length,Ea(e).length)&&r.every(n=>ud(t[n],e[n]))}function hC(t,e){return ri(e)&&J(t.length,e.length)&&t.every((r,n)=>ud(t[n],e[n]))}function ud(t,e){return ri(t)?hC(t,e):mn(t)?gC(t,e):J(t,e)}var nt={};Ct(nt,{IsBigInt64Array:()=>EC,IsBigUint64Array:()=>$C,IsBoolean:()=>yC,IsDate:()=>OC,IsFloat32Array:()=>RC,IsFloat64Array:()=>CC,IsInt16Array:()=>vC,IsInt32Array:()=>AC,IsInt8Array:()=>xC,IsMap:()=>DC,IsNumber:()=>kC,IsRegExp:()=>MC,IsSet:()=>_C,IsString:()=>SC,IsTypeArray:()=>IC,IsUint16Array:()=>bC,IsUint32Array:()=>TC,IsUint8Array:()=>PC,IsUint8ClampedArray:()=>wC});function yC(t){return t instanceof Boolean}function kC(t){return t instanceof Number}function SC(t){return t instanceof String}function IC(t){return globalThis.ArrayBuffer.isView(t)}function xC(t){return t instanceof globalThis.Int8Array}function PC(t){return t instanceof globalThis.Uint8Array}function wC(t){return t instanceof globalThis.Uint8ClampedArray}function vC(t){return t instanceof globalThis.Int16Array}function bC(t){return t instanceof globalThis.Uint16Array}function AC(t){return t instanceof globalThis.Int32Array}function TC(t){return t instanceof globalThis.Uint32Array}function RC(t){return t instanceof globalThis.Float32Array}function CC(t){return t instanceof globalThis.Float64Array}function EC(t){return t instanceof globalThis.BigInt64Array}function $C(t){return t instanceof globalThis.BigUint64Array}function MC(t){return t instanceof globalThis.RegExp}function OC(t){return t instanceof globalThis.Date}function _C(t){return t instanceof globalThis.Set}function DC(t){return t instanceof globalThis.Map}function FC(t){return s.IsObject(t)&&s.HasPropertyKey(t,"check")&&s.HasPropertyKey(t,"errors")&&s.IsFunction(t.check)&&s.IsFunction(t.errors)}function pd(t){return s.HasPropertyKey(t,"~guard")&&FC(t["~guard"])}function dd(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 Da(t){return s.IsBoolean(t)}function M(t){return Mt(t)||Da(t)}function ld(t){return s.HasPropertyKey(t,"additionalItems")&&M(t.additionalItems)}function sr(t){return s.HasPropertyKey(t,"additionalProperties")&&M(t.additionalProperties)}function md(t){return s.HasPropertyKey(t,"allOf")&&s.IsArray(t.allOf)&&t.allOf.every(e=>M(e))}function ni(t){return s.HasPropertyKey(t,"$anchor")&&s.IsString(t.$anchor)}function cd(t){return s.HasPropertyKey(t,"anyOf")&&s.IsArray(t.anyOf)&&t.anyOf.every(e=>M(e))}function fd(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 gd(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 hd(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 yd(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 kd(t){return s.HasPropertyKey(t,"$dynamicRef")&&s.IsString(t.$dynamicRef)}function Sd(t){return s.HasPropertyKey(t,"else")&&M(t.else)}function Id(t){return s.HasPropertyKey(t,"enum")&&s.IsArray(t.enum)}function xd(t){return s.HasPropertyKey(t,"exclusiveMaximum")&&(s.IsNumber(t.exclusiveMaximum)||s.IsBigInt(t.exclusiveMaximum))}function Yn(t){return s.HasPropertyKey(t,"exclusiveMinimum")&&(s.IsNumber(t.exclusiveMinimum)||s.IsBigInt(t.exclusiveMinimum))}function La(t){return s.HasPropertyKey(t,"format")&&s.IsString(t.format)}function ur(t){return s.HasPropertyKey(t,"$id")&&s.IsString(t.$id)}function Pd(t){return s.HasPropertyKey(t,"if")&&M(t.if)}function Zn(t){return s.HasPropertyKey(t,"items")&&(M(t.items)||s.IsArray(t.items)&&t.items.every(e=>M(e)))}function wd(t){return Zn(t)&&s.IsArray(t.items)}function vd(t){return s.HasPropertyKey(t,"maximum")&&(s.IsNumber(t.maximum)||s.IsBigInt(t.maximum))}function bd(t){return s.HasPropertyKey(t,"maxContains")&&s.IsNumber(t.maxContains)}function Fa(t){return s.HasPropertyKey(t,"maxItems")&&s.IsNumber(t.maxItems)}function Ad(t){return s.HasPropertyKey(t,"maxLength")&&s.IsNumber(t.maxLength)}function Td(t){return s.HasPropertyKey(t,"maxProperties")&&s.IsNumber(t.maxProperties)}function Xn(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 oi(t){return s.HasPropertyKey(t,"minItems")&&s.IsNumber(t.minItems)}function Na(t){return s.HasPropertyKey(t,"minLength")&&s.IsNumber(t.minLength)}function qa(t){return s.HasPropertyKey(t,"minProperties")&&s.IsNumber(t.minProperties)}function Rd(t){return s.HasPropertyKey(t,"multipleOf")&&(s.IsNumber(t.multipleOf)||s.IsBigInt(t.multipleOf))}function Cd(t){return s.HasPropertyKey(t,"not")&&M(t.not)}function Ed(t){return s.HasPropertyKey(t,"oneOf")&&s.IsArray(t.oneOf)&&t.oneOf.every(e=>M(e))}function Ba(t){return s.HasPropertyKey(t,"pattern")&&(s.IsString(t.pattern)||t.pattern instanceof RegExp)}function ii(t){return s.HasPropertyKey(t,"patternProperties")&&s.IsObject(t.patternProperties)&&Object.values(t.patternProperties).every(e=>M(e))}function eo(t){return s.HasPropertyKey(t,"prefixItems")&&s.IsArray(t.prefixItems)&&t.prefixItems.every(e=>M(e))}function si(t){return s.HasPropertyKey(t,"properties")&&s.IsObject(t.properties)&&Object.values(t.properties).every(e=>M(e))}function $d(t){return s.HasPropertyKey(t,"propertyNames")&&(s.IsObject(t.propertyNames)||M(t.propertyNames))}function NC(t){return s.HasPropertyKey(t,"$recursiveAnchor")&&s.IsBoolean(t.$recursiveAnchor)}function Ua(t){return NC(t)&&s.IsEqual(t.$recursiveAnchor,!0)}function Md(t){return s.HasPropertyKey(t,"$recursiveRef")&&s.IsString(t.$recursiveRef)}function Od(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 _d(t){return s.HasPropertyKey(t,"then")&&M(t.then)}function Dd(t){return s.HasPropertyKey(t,"type")&&(s.IsString(t.type)||s.IsArray(t.type)&&t.type.every(e=>s.IsString(e)))}function ai(t){return s.HasPropertyKey(t,"uniqueItems")&&s.IsBoolean(t.uniqueItems)}function Wa(t){return s.HasPropertyKey(t,"unevaluatedItems")&&M(t.unevaluatedItems)}function Ka(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}},ui=class extends ot{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},Le=class extends ui{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};function Zg(t,e,r,n){return r["~guard"].check(n)}function Xg(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:()=>rE,HashCode:()=>ih});function Y(){throw new Error("Unreachable")}function qC(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 BC(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 ro=BigInt("14695981039346656037"),[UC,WC]=[BigInt("1099511628211"),BigInt("18446744073709551616")],KC=Array.from({length:256}).map((t,e)=>BigInt(e)),rh=new Float64Array(1),nh=new DataView(rh.buffer),oh=new Uint8Array(rh.buffer);function Ue(t){ro=ro^KC[t],ro=ro*UC%WC}function jC(t){Ue(it.Array);for(let e of t)$r(e)}function GC(t){Ue(it.BigInt),nh.setBigInt64(0,t);for(let e of oh)Ue(e)}function eh(t){Ue(it.Boolean),Ue(t?1:0)}function VC(t){Ue(it.Constructor),$r(t.toString())}function HC(t){Ue(it.Date),$r(t.getTime())}function zC(t){Ue(it.Function),$r(t.toString())}function JC(t){Ue(it.Null)}function th(t){Ue(it.Number),nh.setFloat64(0,t,!0);for(let e of oh)Ue(e)}function QC(t){Ue(it.Object);for(let e of qC(t).sort())$r(e),$r(t[e])}function YC(t){Ue(it.RegExp),Ld(t.toString())}var ZC=new TextEncoder;function Ld(t){Ue(it.String);for(let e of ZC.encode(t))Ue(e)}function XC(t){Ue(it.Symbol),$r(t.toString())}function eE(t){Ue(it.TypeArray);let e=new Uint8Array(t.buffer);for(let r=0;r<e.length;r++)Ue(e[r])}function tE(t){return Ue(it.Undefined)}function $r(t){return nt.IsTypeArray(t)?eE(t):nt.IsDate(t)?HC(t):nt.IsRegExp(t)?YC(t):nt.IsBoolean(t)?eh(t.valueOf()):nt.IsString(t)?Ld(t.valueOf()):nt.IsNumber(t)?th(t.valueOf()):BC(t)?th(t):s.IsArray(t)?jC(t):s.IsBoolean(t)?eh(t):s.IsBigInt(t)?GC(t):s.IsConstructor(t)?VC(t):s.IsNull(t)?JC(t):s.IsObject(t)?QC(t):s.IsString(t)?Ld(t):s.IsSymbol(t)?XC(t):s.IsUndefined(t)?tE(t):s.IsFunction(t)?zC(t):Y()}function ih(t){return ro=BigInt("14695981039346656037"),$r(t),ro}function rE(t){return ih(t).toString(16).padStart(16,"0")}function sh(t,e,r,n){return s.Every(r["~refine"],0,(o,i)=>o.check(n))}function ah(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 uh(t){return Zn(t)&&s.IsArray(t.items)}function ph(t,e,r,n){return uh(r)?n.every((i,a)=>s.IsLessThan(a,r.items.length)||vt(t,e,r.additionalItems,i)&&e.AddIndex(a)):!0}function dh(t,e,r,n,o,i){return uh(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 nE(t){return`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function lh(t){let e=[];return ii(t)&&e.push(...s.Keys(t.patternProperties)),si(t)&&e.push(...s.Keys(t.properties).map(nE)),s.IsEqual(e.length,0)?"(?!)":`(${e.join("|")})`}function mh(t,e,r,n){let o=new RegExp(lh(r));return s.Every(s.Keys(n),0,(a,u)=>o.test(a)||vt(t,e,r.additionalProperties,n[a])&&e.AddKey(a))}function ch(t,e,r,n,o,i){let a=new RegExp(lh(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 fh(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 gh(t,e,r,n,o,i){let a=[],u=o.allOf.reduce((d,l,m)=>{let c=`${r}/allOf/${m}`,h=new Le,y=pe(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 hh(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 yh(t,e,r,n,o,i){let a=[],u=o.anyOf.reduce((d,l,m)=>{let c=new Le,h=`${r}/anyOf/${m}`,y=pe(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 Nd(t,e,r,n){return r}function kh(t,e,r,n,o,i){return Nd(t,e,o,i)||e.AddError({keyword:"boolean",schemaPath:r,instancePath:n,params:{}})}function qd(t,e,r,n){return s.IsValueLike(r.const)?s.IsEqual(n,r.const):s.IsDeepEqual(n,r.const)}function Sh(t,e,r,n,o,i){return qd(t,e,o,i)||e.AddError({keyword:"const",schemaPath:r,instancePath:n,params:{allowedValue:o.const}})}function oE(t){return!(fn(t)&&s.IsEqual(t.minContains,0))}function Bd(t,e,r,n){return oE(r)?!s.IsEqual(n.length,0)&&n.some(o=>z(t,e,r.contains,o)):!0}function Ih(t,e,r,n,o,i){return Bd(t,e,o,i)||e.AddError({keyword:"contains",schemaPath:r,instancePath:n,params:{minContains:1}})}function xh(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 Ph(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}})):pe(t,e,l,n,d,i))});return a||u}function wh(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 vh(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 bh(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 Ah(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)||pe(t,e,l,n,d,i)});return a||u}function Th(t,e,r,n){let o=t.DynamicRef(r)??!1;return M(o)&&z(t,e,o,n)}function Rh(t,e,r,n,o,i){let a=t.DynamicRef(o)??!1;return M(a)&&pe(t,e,"#",n,a,i)}function Kd(t,e,r,n){return r.enum.some(o=>s.IsValueLike(o)?s.IsEqual(n,o):s.IsDeepEqual(n,o))}function Ch(t,e,r,n,o,i){return Kd(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 Eh(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 Gd(t,e,r,n){return s.IsGreaterThan(n,r.exclusiveMinimum)}function $h(t,e,r,n,o,i){return Gd(t,e,o,i)||e.AddError({keyword:"exclusiveMinimum",schemaPath:r,instancePath:n,params:{comparison:">",limit:o.exclusiveMinimum}})}var yn={};Ct(yn,{Clear:()=>Uh,Entries:()=>BE,Get:()=>KE,Has:()=>WE,IsDate:()=>no,IsDateTime:()=>ja,IsDuration:()=>Ga,IsEmail:()=>Va,IsHostname:()=>Ha,IsIPv4:()=>Qa,IsIPv6:()=>Ya,IsIdnEmail:()=>za,IsIdnHostname:()=>Ja,IsIri:()=>Xa,IsIriReference:()=>Za,IsJsonPointer:()=>tu,IsJsonPointerUriFragment:()=>eu,IsRegex:()=>ru,IsRelativeJsonPointer:()=>nu,IsTime:()=>oo,IsUri:()=>au,IsUriReference:()=>ou,IsUriTemplate:()=>iu,IsUrl:()=>uu,IsUuid:()=>pu,Reset:()=>Wh,Set:()=>UE,Test:()=>jE});var iE=[0,31,28,31,30,31,30,31,31,30,31,30,31],sE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function aE(t){return t%4===0&&(t%100!==0||t%400===0)}function no(t){let e=sE.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&&aE(r)?29:iE[n])}var uE=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function oo(t,e=!0){let r=uE.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 ja(t,e=!0){let r=t.split(/T/i);return r.length===2&&no(r[0])&&oo(r[1],e)}var pE=/^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 Ga(t){return pE.test(t)}var dE=/^(?!.*\.\.)[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 Va(t){return dE.test(t)}function lE(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 Mh(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=lE(n-u,l,u===0),r+=Math.floor(n/l),n%=l,e.splice(n,0,r),n++}return globalThis.String.fromCodePoint(...e)}function cE(t){return new RegExp("\\p{Mn}","u").test(String.fromCodePoint(t))}function fE(t){return new RegExp("\\p{Mc}","u").test(String.fromCodePoint(t))}function gE(t){return new RegExp("\\p{Me}","u").test(String.fromCodePoint(t))}function hE(t){return cE(t)||fE(t)||gE(t)}var yE=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),kE=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 SE(t){return new RegExp("\\p{Script=Greek}","u").test(String.fromCodePoint(t))}function IE(t){return new RegExp("\\p{Script=Hebrew}","u").test(String.fromCodePoint(t))}function xE(t){return new RegExp("\\p{Script=Hiragana}","u").test(String.fromCodePoint(t))}function PE(t){return new RegExp("\\p{Script=Katakana}","u").test(String.fromCodePoint(t))}function wE(t){return new RegExp("\\p{Script=Han}","u").test(String.fromCodePoint(t))}function vE(t){return t>=1632&&t<=1641}function bE(t){return t>=1776&&t<=1785}function AE(t){return kE.has(t)}function Oh(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||hE(e[0]))return!1;let n=!1,o=!1,i=!1;for(let a=0;a<r;a++){let u=e[a];if(yE.has(u))return!1;(xE(u)||PE(u)||wE(u))&&(n=!0),vE(u)&&(o=!0),bE(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||!SE(d))return!1;break;case 1523:case 1524:if(p===void 0||!IE(p))return!1;break;case 8205:if(p===void 0||!AE(p))return!1;break;case 12539:break}}return!(t.includes("\u30FB")&&!n||o&&i)}function TE(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 _h(t){return t.toLowerCase().startsWith("xn--")}function Dh(t){try{return Oh(Mh(t.slice(4)))}catch{return!1}}function Lh(t){return t.length===0||t.length>63?!1:_h(t)?Dh(t):Oh(t)}function Fh(t){return t.length===0||t.length>63?!1:_h(t)?Dh(t):TE(t)}function Ha(t){if(t.length===0||t.length>253||t.charCodeAt(t.length-1)===46)return!1;for(let e of t.split("."))if(!Fh(e))return!1;return!0}var CE=/^(?!.*\.\.)[\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 za(t){return CE.test(t)}function Ja(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(!Lh(r))return!1;return!0}function Vd(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 Qa(t){return Vd(t,0,t.length)}function EE(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function Ya(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&&EE(t.charCodeAt(o));)o++,i++;if(i===0)return!1;let u=t.charCodeAt(o);if(u===46){if(!Vd(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 Nh(t){try{return new URL(t,"http://example.com"),!0}catch{return!1}}function Za(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))?Nh(t):t.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&e===-1?!1:Nh(t)}function Xa(t){try{return new URL(t),!0}catch{return!1}}var $E=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function eu(t){return $E.test(t)}var ME=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function tu(t){return ME.test(t)}function ru(t){if(t.length===0)return!1;try{return new RegExp(t),!0}catch{return!1}}var OE=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function nu(t){return OE.test(t)}var _E=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function ou(t){return _E.test(t)}var DE=/^(?:(?:[^\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 iu(t){return DE.test(t)}function qh(t){return t>=97&&t<=122||t>=65&&t<=90}function Bh(t){return qh(t)||t>=48&&t<=57}function su(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function LE(t){return Bh(t)||t===43||t===45||t===46}function Hd(t){return Bh(t)||t===45||t===46||t===95||t===126}function zd(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 FE(t){return Hd(t)||zd(t)||t===58||t===64}function au(t){let e=t.length;if(e===0||!qh(t.charCodeAt(0)))return!1;let r=1;for(;r<e;){let n=t.charCodeAt(r);if(n===58)break;if(!LE(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||!su(t.charCodeAt(i+1))||!su(t.charCodeAt(i+2)))return!1;i+=2}else if(!Hd(a)&&!zd(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&&!Hd(i)&&!zd(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||!su(t.charCodeAt(r+1))||!su(t.charCodeAt(r+2)))return!1;r+=2}else{if(n>127)return!1;if(!(FE(n)||n===47||n===63||n===35))return!1}r++}return!0}var NE=/^(?: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 uu(t){return NE.test(t)}var qE=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function pu(t){return qE.test(t)}var ce=new Map;function Uh(){ce.clear()}function BE(){return[...ce.entries()]}function UE(t,e){ce.set(t,e)}function WE(t){return ce.has(t)}function KE(t){return ce.get(t)}function jE(t,e){return ce.get(t)?.(e)??!0}function Wh(){Uh(),ce.set("date-time",ja),ce.set("date",no),ce.set("duration",Ga),ce.set("email",Va),ce.set("hostname",Ha),ce.set("idn-email",za),ce.set("idn-hostname",Ja),ce.set("ipv4",Qa),ce.set("ipv6",Ya),ce.set("iri-reference",Za),ce.set("iri",Xa),ce.set("json-pointer-uri-fragment",eu),ce.set("json-pointer",tu),ce.set("regex",ru),ce.set("relative-json-pointer",nu),ce.set("time",oo),ce.set("uri-reference",ou),ce.set("uri-template",iu),ce.set("uri",au),ce.set("url",uu),ce.set("uuid",pu)}Wh();function Jd(t,e,r,n){return yn.Test(r.format,n)}function Kh(t,e,r,n,o,i){return Jd(t,e,o,i)||e.AddError({keyword:"format",schemaPath:r,instancePath:n,params:{format:o.format}})}function jh(t,e,r,n){let o=_d(r)?r.then:!0,i=Sd(r)?r.else:!0;return z(t,e,r.if,n)?z(t,e,o,n):z(t,e,i,n)}function Gh(t,e,r,n,o,i){let a=_d(o)?o.then:!0,u=Sd(o)?o.else:!0,p=new Le,d=pe(t,p,`${r}/if`,n,o.if,i)?pe(t,p,`${r}/then`,n,a,i)||e.AddError({keyword:"if",schemaPath:r,instancePath:n,params:{failingKeyword:"then"}}):pe(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 GE(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 VE(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 HE(t,e,r,n){let o=eo(r)?r.prefixItems.length:0;return s.Every(n,o,(i,a)=>vt(t,e,r.items,i)&&e.AddIndex(a))}function zE(t,e,r,n,o,i){let a=eo(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 Vh(t,e,r,n){return wd(r)?GE(t,e,r,n):HE(t,e,r,n)}function Hh(t,e,r,n,o,i){return wd(o)?VE(t,e,r,n,o,i):zE(t,e,r,n,o,i)}function JE(t){return cn(t)}function Qd(t,e,r,n){if(!JE(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 zh(t,e,r,n,o,i){let a=fn(o)?o.minContains:1;return Qd(t,e,o,i)||e.AddError({keyword:"contains",schemaPath:r,instancePath:n,params:{minContains:a,maxContains:o.maxContains}})}function Yd(t,e,r,n){return s.IsLessEqualThan(n,r.maximum)}function Jh(t,e,r,n,o,i){return Yd(t,e,o,i)||e.AddError({keyword:"maximum",schemaPath:r,instancePath:n,params:{comparison:"<=",limit:o.maximum}})}function Zd(t,e,r,n){return s.IsLessEqualThan(n.length,r.maxItems)}function Qh(t,e,r,n,o,i){return Zd(t,e,o,i)||e.AddError({keyword:"maxItems",schemaPath:r,instancePath:n,params:{limit:o.maxItems}})}function Xd(t,e,r,n){return s.IsMaxLength(n,r.maxLength)}function Yh(t,e,r,n,o,i){return Xd(t,e,o,i)||e.AddError({keyword:"maxLength",schemaPath:r,instancePath:n,params:{limit:o.maxLength}})}function el(t,e,r,n){return s.IsLessEqualThan(s.Keys(n).length,r.maxProperties)}function Zh(t,e,r,n,o,i){return el(t,e,o,i)||e.AddError({keyword:"maxProperties",schemaPath:r,instancePath:n,params:{limit:o.maxProperties}})}function QE(t){return cn(t)}function tl(t,e,r,n){if(!QE(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 Xh(t,e,r,n,o,i){return tl(t,e,o,i)||e.AddError({keyword:"contains",schemaPath:r,instancePath:n,params:{minContains:o.minContains}})}function rl(t,e,r,n){return s.IsGreaterEqualThan(n,r.minimum)}function ey(t,e,r,n,o,i){return rl(t,e,o,i)||e.AddError({keyword:"minimum",schemaPath:r,instancePath:n,params:{comparison:">=",limit:o.minimum}})}function nl(t,e,r,n){return s.IsGreaterEqualThan(n.length,r.minItems)}function ty(t,e,r,n,o,i){return nl(t,e,o,i)||e.AddError({keyword:"minItems",schemaPath:r,instancePath:n,params:{limit:o.minItems}})}function ol(t,e,r,n){return s.IsMinLength(n,r.minLength)}function ry(t,e,r,n,o,i){return ol(t,e,o,i)||e.AddError({keyword:"minLength",schemaPath:r,instancePath:n,params:{limit:o.minLength}})}function il(t,e,r,n){return s.IsGreaterEqualThan(s.Keys(n).length,r.minProperties)}function ny(t,e,r,n,o,i){return il(t,e,o,i)||e.AddError({keyword:"minProperties",schemaPath:r,instancePath:n,params:{limit:o.minProperties}})}function sl(t,e,r,n){return s.IsMultipleOf(n,r.multipleOf)}function oy(t,e,r,n,o,i){return sl(t,e,o,i)||e.AddError({keyword:"multipleOf",schemaPath:r,instancePath:n,params:{multipleOf:o.multipleOf}})}function al(t,e,r,n){let o=new ot;return!z(t,o,r.not,n)&&e.Merge([o])}function iy(t,e,r,n,o,i){return al(t,e,o,i)||e.AddError({keyword:"not",schemaPath:r,instancePath:n,params:{}})}function sy(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 ay(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=pe(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 ul(t,e,r,n){return(s.IsString(r.pattern)?new RegExp(r.pattern,"u"):r.pattern).test(n)}function uy(t,e,r,n,o,i){return ul(t,e,o,i)||e.AddError({keyword:"pattern",schemaPath:r,instancePath:n,params:{pattern:o.pattern}})}function py(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 dy(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 ly(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 my(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:()=>XE,Reset:()=>YE,Set:()=>ZE});var _r={immutableTypes:!1,maxErrors:8,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1};function YE(){_r.immutableTypes=!1,_r.maxErrors=8,_r.useAcceleration=!0,_r.exactOptionalPropertyTypes=!1,_r.enumerableKind=!1,_r.correctiveParse=!1}function ZE(t){for(let e of s.Keys(t)){let r=t[e];r!==void 0&&Object.defineProperty(_r,e,{value:r})}}function XE(){return _r}function pl(t,e){return t.includes(e)||kt.Get().exactOptionalPropertyTypes}function dl(t,e){return s.IsUndefined(t[e])}function cy(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 pl(o,a)?p:dl(n,a)||p})}function fy(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 pl(a,p)?c():dl(i,p)||c()})}function gy(t,e,r,n){return s.Every(s.Keys(n),0,(o,i)=>z(t,e,r.propertyNames,o))}function hy(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=pe(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 yy(t,e,r,n){let o=t.RecursiveRef(r)??!1;return M(o)&&z(t,e,o,n)}function ky(t,e,r,n,o,i){let a=t.RecursiveRef(o)??!1;return M(a)&&pe(t,e,"#",n,a,i)}function Sy(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 Iy(t,e,r,n,o,i){let a=t.Ref(o)??!1,u=new Le,p=M(a)&&pe(t,u,"#",n,a,i);return p&&e.Merge([u]),p||u.GetErrors().forEach(d=>e.AddError(d)),p}function xy(t,e,r,n){return s.Every(r.required,0,o=>s.HasPropertyKey(n,o))}function Py(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 ll(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 wy(t,e,r,n,o){return r.some(i=>ll(t,e,i,n,o))}function vy(t,e,r,n){return s.IsArray(r.type)?wy(t,e,r.type,r,n):ll(t,e,r.type,r,n)}function by(t,e,r,n,o,i){return(s.IsArray(o.type)?wy(t,e,o.type,o,i):ll(t,e,o.type,o,i))||e.AddError({keyword:"type",schemaPath:r,instancePath:n,params:{type:o.type}})}function Ay(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 Ty(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)||pe(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 Ry(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 Cy(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)||pe(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 Ey(t){return!s.IsEqual(t.uniqueItems,!1)}function $y(t,e,r,n){if(!Ey(r))return!0;let o=new Set(n.map(Mr.Hash)).size,i=n.length;return s.IsEqual(o,i)}function My(t,e,r,n,o,i){if(!Ey(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=Da(r)?Nd(t,e,r,n):(!Dd(r)||vy(t,e,r,n))&&(!(s.IsObject(n)&&!s.IsArray(n))||(!gn(r)||xy(t,e,r,n))&&(!sr(r)||mh(t,e,r,n))&&(!gd(r)||xh(t,e,r,n))&&(!hd(r)||wh(t,e,r,n))&&(!yd(r)||bh(t,e,r,n))&&(!ii(r)||py(t,e,r,n))&&(!si(r)||cy(t,e,r,n))&&(!$d(r)||gy(t,e,r,n))&&(!qa(r)||il(t,e,r,n))&&(!Td(r)||el(t,e,r,n)))&&(!s.IsArray(n)||(!ld(r)||ph(t,e,r,n))&&(!cn(r)||Bd(t,e,r,n))&&(!Zn(r)||Vh(t,e,r,n))&&(!bd(r)||Qd(t,e,r,n))&&(!Fa(r)||Zd(t,e,r,n))&&(!fn(r)||tl(t,e,r,n))&&(!oi(r)||nl(t,e,r,n))&&(!eo(r)||ly(t,e,r,n))&&(!ai(r)||$y(t,e,r,n)))&&(!s.IsString(n)||(!Ad(r)||Xd(t,e,r,n))&&(!Na(r)||ol(t,e,r,n))&&(!La(r)||Jd(t,e,r,n))&&(!Ba(r)||ul(t,e,r,n)))&&(!(s.IsNumber(n)||s.IsBigInt(n))||(!xd(r)||jd(t,e,r,n))&&(!Yn(r)||Gd(t,e,r,n))&&(!vd(r)||Yd(t,e,r,n))&&(!Xn(r)||rl(t,e,r,n))&&(!Rd(r)||sl(t,e,r,n)))&&(!Od(r)||Sy(t,e,r,n))&&(!Md(r)||yy(t,e,r,n))&&(!kd(r)||Th(t,e,r,n))&&(!pd(r)||Zg(t,e,r,n))&&(!fd(r)||qd(t,e,r,n))&&(!Id(r)||Kd(t,e,r,n))&&(!Pd(r)||jh(t,e,r,n))&&(!Cd(r)||al(t,e,r,n))&&(!md(r)||fh(t,e,r,n))&&(!cd(r)||hh(t,e,r,n))&&(!Ed(r)||sy(t,e,r,n))&&(!Wa(r)||!s.IsArray(n)||Ay(t,e,r,n))&&(!Ka(r)||!s.IsObject(n)||Ry(t,e,r,n))&&(!dd(r)||sh(t,e,r,n));return t.Pop(r),o}function bt(t,e,r,n,o,i){return e.Push()&&pe(t,e,r,n,o,i)&&e.Pop()}function pe(t,e,r,n,o,i){t.Push(o);let a=Da(o)?kh(t,e,r,n,o,i):!!(+(!Dd(o)||by(t,e,r,n,o,i))&+(!(s.IsObject(i)&&!s.IsArray(i))||!!(+(!gn(o)||Py(t,e,r,n,o,i))&+(!sr(o)||ch(t,e,r,n,o,i))&+(!gd(o)||Ph(t,e,r,n,o,i))&+(!hd(o)||vh(t,e,r,n,o,i))&+(!yd(o)||Ah(t,e,r,n,o,i))&+(!ii(o)||dy(t,e,r,n,o,i))&+(!si(o)||fy(t,e,r,n,o,i))&+(!$d(o)||hy(t,e,r,n,o,i))&+(!qa(o)||ny(t,e,r,n,o,i))&+(!Td(o)||Zh(t,e,r,n,o,i))))&+(!s.IsArray(i)||!!(+(!ld(o)||dh(t,e,r,n,o,i))&+(!cn(o)||Ih(t,e,r,n,o,i))&+(!Zn(o)||Hh(t,e,r,n,o,i))&+(!bd(o)||zh(t,e,r,n,o,i))&+(!Fa(o)||Qh(t,e,r,n,o,i))&+(!fn(o)||Xh(t,e,r,n,o,i))&+(!oi(o)||ty(t,e,r,n,o,i))&+(!eo(o)||my(t,e,r,n,o,i))&+(!ai(o)||My(t,e,r,n,o,i))))&+(!s.IsString(i)||!!(+(!Ad(o)||Yh(t,e,r,n,o,i))&+(!Na(o)||ry(t,e,r,n,o,i))&+(!La(o)||Kh(t,e,r,n,o,i))&+(!Ba(o)||uy(t,e,r,n,o,i))))&+(!(s.IsNumber(i)||s.IsBigInt(i))||!!(+(!xd(o)||Eh(t,e,r,n,o,i))&+(!Yn(o)||$h(t,e,r,n,o,i))&+(!vd(o)||Jh(t,e,r,n,o,i))&+(!Xn(o)||ey(t,e,r,n,o,i))&+(!Rd(o)||oy(t,e,r,n,o,i))))&+(!Od(o)||Iy(t,e,r,n,o,i))&+(!Md(o)||ky(t,e,r,n,o,i))&+(!kd(o)||Rh(t,e,r,n,o,i))&+(!pd(o)||Xg(t,e,r,n,o,i))&+(!fd(o)||Sh(t,e,r,n,o,i))&+(!Id(o)||Ch(t,e,r,n,o,i))&+(!Pd(o)||Gh(t,e,r,n,o,i))&+(!Cd(o)||iy(t,e,r,n,o,i))&+(!md(o)||gh(t,e,r,n,o,i))&+(!cd(o)||yh(t,e,r,n,o,i))&+(!Ed(o)||ay(t,e,r,n,o,i))&+(!Wa(o)||!s.IsArray(i)||Ty(t,e,r,n,o,i))&+(!Ka(o)||!s.IsObject(i)||Cy(t,e,r,n,o,i)))&&(!dd(o)||ah(t,e,r,n,o,i));return t.Pop(o),a}var Dr={};Ct(Dr,{DynamicRef:()=>f$,Ref:()=>cl});var pr={};Ct(pr,{Delete:()=>a$,Get:()=>i$,Has:()=>o$,Indices:()=>di,Set:()=>s$});function Oy(t){if(t.length===0)throw Error("Cannot set root")}function _y(t){if(!s.IsObject(t))throw Error("Cannot set value")}function e$(t){if(s.IsUnsafePropertyKey(t))throw Error("Pointer contains unsafe property key")}function Dy(t){for(let e of t)e$(e)}function t$(t){return/^(0|[1-9]\d*)$/.test(t)}function Ly(t){return[t.slice(0,t.length-1),t.slice(t.length-1)[0]]}function r$(t,e){return s.IsObject(e)&&s.HasPropertyKey(e,t)}function n$(t,e){return s.IsObject(e)&&!s.IsUnsafePropertyKey(t)?e[t]:void 0}function ml(t,e){return t.reduce((r,n)=>n$(n,r),e)}function di(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 o$(t,e){let r=t;return di(e).every(n=>r$(n,r)?(r=r[n],!0):!1)}function i$(t,e){let r=di(e);return ml(r,t)}function s$(t,e,r){let n=di(e);Oy(n),Dy(n);let[o,i]=Ly(n),a=ml(o,t);return _y(a),a[i]=r,t}function a$(t,e){let r=di(e);Oy(r),Dy(r);let[n,o]=Ly(r),i=ml(n,t);return _y(i),s.IsArray(i)&&t$(o)?i.splice(+o,1):delete i[o],t}function u$(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("#")?Fy(t,e,r):t}function p$(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 d$(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 Fy(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 l$(t,e,r){if(ur(t)){let n=u$(t,e,r);if(!s.IsUndefined(n))return n}if(ni(t)){let n=p$(t,e,r);if(!s.IsUndefined(n))return n}if(Er(t)){let n=d$(t,e,r);if(!s.IsUndefined(n))return n}return Fy(t,e,r)}function m$(t,e,r){return t.reduce((n,o)=>{let i=fl(o,e,r);return s.IsUndefined(i)?n:i},void 0)}function c$(t,e,r){return s.Keys(t).reduce((n,o)=>{let i=fl(t[o],e,r);return s.IsUndefined(i)?n:i},void 0)}function fl(t,e,r){let n=Mt(t)&&ur(t)?new URL(t.$id,e.href):e;if(Mt(t)){let o=l$(t,n,r);if(!s.IsUndefined(o))return o}if(s.IsArray(t))return m$(t,n,r);if(s.IsObject(t))return c$(t,n,r)}function cl(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 fl(t,n,o)}function f$(t,e,r,n){let o=r.$dynamicRef.startsWith("#")?cl(e,r.$dynamicRef):cl(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 io=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,Ny,qy,By,Uy,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),io(this,Lr,"m",Ny).call(this,e)),ni(e)&&this.anchors.push(e),Ua(e)&&this.recursiveAnchors.push(e),Er(e)&&this.dynamicAnchors.push(e))}Pop(e){Mt(e)&&(ur(e)&&(this.ids.pop(),io(this,Lr,"m",qy).call(this,e)),ni(e)&&this.anchors.pop(),Ua(e)&&this.recursiveAnchors.pop(),Er(e)&&this.dynamicAnchors.pop())}Ref(e){return io(this,Lr,"m",By).call(this,e)??io(this,Lr,"m",Uy).call(this,e)}RecursiveRef(e){return Ua(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,Ny=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))io(this,Lr,"m",t).call(this,n[o],!1)}},qy=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))io(this,Lr,"m",t).call(this,n[o],!1)}},By=function(e){return s.HasPropertyKey(this.context,e.$ref)?this.context[e.$ref]:void 0},Uy=function(e){let r=this.schema;return e.$ref.startsWith("#")?Dr.Ref(this.Base(),e.$ref):Dr.Ref(r,e.$ref)};function Ky(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 h$=Ky;function jy(){return h$}function du(...t){let[e,r,n]=ee.Match(t,{3:(l,m,c)=>[l,m,c],2:(l,m)=>[{},l,m]}),o=kt.Get(),i=jy(),a=[],u=new kn(e,r),p=new ui(l=>{if(!s.IsGreaterEqualThan(a.length,o.maxErrors))return a.push({...l,message:i(l)})});return[pe(u,p,"#","",r,n),a]}function hl(...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:()=>k$,Clone:()=>li,Create:()=>v$,Discard:()=>b$,Metrics:()=>Nt,Update:()=>A$});var Nt={assign:0,create:0,clone:0,discard:0,update:0};function k$(t,e){return Nt.assign+=1,{...t,...e}}function S$(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~guard")}function I$(t){return t.map(e=>yl(e))}function x$(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:yl(o.value)})}return e}function P$(t){return new RegExp(t.source,t.flags)}function yl(t){return t instanceof RegExp?P$(t):S$(t)?t:s.IsArray(t)?I$(t):s.IsObject(t)?x$(t):t}function li(t){return Nt.clone+=1,yl(t)}function w$(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 Vy(t,e){return{...t,...e}}function v$(t,e,r={}){Nt.create+=1;let n=kt.Get(),o=Vy(e,r),i=n.enumerableKind?Vy(o,t):w$(o,t);return n.immutableTypes?Object.freeze(i):i}function b$(t,e){Nt.discard+=1;let r={},n=Object.getOwnPropertyDescriptors(li(t)),o=new Set(e);for(let i of Object.keys(n))o.has(i)||Object.defineProperty(r,i,n[i]);return r}function A$(t,e,r){Nt.update+=1;let n=kt.Get(),o=li(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 de(t){return s.IsObject(t)}function Hy(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"OptionalAddAction")&&de(t.type)}function zy(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"OptionalRemoveAction")&&de(t.type)}function Jy(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"ReadonlyAddAction")&&de(t.type)}function Qy(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"type")&&s.IsEqual(t["~kind"],"ReadonlyRemoveAction")&&de(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 Yy(t){return g.Discard(t,["~kind","type","item"])}function Zy(t){return g.Update(t,{"~immutable":!0},{})}function so(t){return Zy(t)}function mi(t){return de(t)&&s.HasPropertyKey(t,"~immutable")}function ao(t){return g.Discard(t,["~optional"])}function Sn(t){return g.Update(t,{"~optional":!0},{})}function Xy(t){return Sn(t)}function We(t){return de(t)&&s.HasPropertyKey(t,"~optional")}function lu(t){return g.Discard(t,["~readonly"])}function In(t){return g.Update(t,{"~readonly":!0},{})}function ek(t){return In(t)}function ci(t){return de(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 mu(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 tk(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 rk(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 nk(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 kl(t,e){return g.Create({"~kind":"Generic"},{type:"generic",parameters:t,expression:e})}function cu(t){return v(t,"Generic")}function Sl(t){return g.Create({"~kind":"Any"},{},t)}function Ve(t){return v(t,"Any")}var ok="(?!)";function oe(t){return g.Create({"~kind":"Never"},{not:{}},t)}function Nr(t){return v(t,"Never")}function ik(t){return s.Keys(t).filter(e=>!We(t[e]))}function fu(t){return s.Keys(t)}function gu(t){return s.Values(t)}function O(t,e={}){let r=ik(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 sk(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 ak(t){return g.Discard(t,["~kind","anyOf"])}function Yt(t){return g.Create({"~kind":"Unknown"},{},t)}function Ye(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 ge(t){return v(t,"Cyclic")}function uk(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 pk(t){return g.Discard(t,["~kind","allOf"])}function Il(t){return de(t)&&s.HasPropertyKey(t,"~codec")&&s.IsObject(t["~codec"])&&s.HasPropertyKey(t["~codec"],"encode")&&s.HasPropertyKey(t["~codec"],"decode")}var lk="-?(?:0|[1-9][0-9]*)n";function mk(t){return g.Create({"~kind":"BigInt"},{type:"bigint"},t)}function Bt(t){return v(t,"BigInt")}function At(t){return v(t,"Boolean")}var hu="-?(?:0|[1-9][0-9]*)";function yu(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 ck(t){return g.Discard(t,["~kind","type","iteratorItems"])}var xl=class extends Error{constructor(e){super("Invalid Literal value"),Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}};function R$(t){return s.IsBigInt(t)?"bigint":s.IsBoolean(t)?"boolean":s.IsNumber(t)?"number":s.IsString(t)?"string":(()=>{throw new xl(t)})()}function Z(t,e){return g.Create({"~kind":"Literal"},{type:R$(t),const:t},e)}function Pl(t){return s.IsBigInt(t)||s.IsBoolean(t)||s.IsNumber(t)||s.IsString(t)}function fk(t){return G(t)&&s.IsBigInt(t.const)}function gk(t){return G(t)&&s.IsBoolean(t.const)}function ku(t){return G(t)&&s.IsNumber(t.const)}function Su(t){return G(t)&&s.IsString(t.const)}function G(t){return v(t,"Literal")}function fi(t){return g.Create({"~kind":"Null"},{type:"null"},t)}function wn(t){return v(t,"Null")}var Iu="-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?";function Ut(t){return g.Create({"~kind":"Number"},{type:"number"},t)}function be(t){return v(t,"Number")}function wl(t){return g.Create({"~kind":"Symbol"},{type:"symbol"},t)}function uo(t){return v(t,"Symbol")}var xu=".*";function Tt(t){return g.Create({"~kind":"String"},{type:"string"},t)}function Ze(t){return v(t,"String")}function gi(t){let e=hk(t);return s.IsEqual(e.length,2)?e[0]:[]}function C$(t){return!0}function yk(t){return s.TakeLeft(t,(e,r)=>E$(e)?yk(r):!1,()=>!0)}function kk(t){return s.IsEqual(t.length,0)?!1:yk(t)}function E$(t){return b(t)?kk(t.anyOf):G(t)?C$(t.const):!1}function Pu(t){return kk(t)}function wu(t){return g.Create({"~kind":"TemplateLiteral"},{type:"string",pattern:t},{})}function Sk(t,e,r=[]){return s.TakeLeft(t,(n,o)=>Sk(o,e,[...r,`${n}${e}`]),()=>r)}function $$(t,e){return s.IsEqual(t.length,0)?[`${e}`]:Sk(t,e)}function Ik(t,e,r=[]){return s.TakeLeft(e,(n,o)=>Ik(t,o,[...r,...xk(t,n)]),()=>r)}function xk(t,e){return b(e)?Ik(t,e.anyOf):G(e)?$$(t,e.const):Y()}function Pk(t,e){return s.TakeLeft(e,(r,n)=>Pk(xk(t,r),n),()=>t)}function M$(t){return t.map(e=>Z(e))}function O$(t){let e=Pk([],t),r=M$(e);return B(r)}function _$(t){return s.IsEqual(t.length,0)?Y():s.IsEqual(t.length,1)&&G(t[0])?t[0]:O$(t)}function vl(t){let e=gi(t);return s.IsEqual(e.length,0)?Tt():Pu(e)?_$(e):wu(t)}function He(t){let e=vl(t);return Ae(e)?Tt():e}function ft(t,e){let r="object",n={[t]:e};return g.Create({"~kind":"Record"},{type:r,patternProperties:n})}function wk(t){return ft(Br,t)}function vk(t){return O({true:t,false:t})}function D$(t){return s.IsString(t)||s.IsNumber(t)?Z(t):s.IsNull(t)?fi():oe()}function Wt(t){return t.map(r=>D$(r))}function hi(t){let e=Wt(t);return B(e)}function po(t){return hi(t.enum)}function bk(t,e){let r=hi(t);return Ur(r,e)}function Ak(t,e){return ft(lo,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 Tk(t){return g.Discard(t,["~kind","type","items","minItems","additionalItems"])}function bl(t){return t.reduceRight((r,n,o)=>({[o]:n,...r}),{})}function Rk(t){let e=bl(t.items);return O(e)}function L$(t,e){return ci(t)?!!ci(e):!1}function F$(t,e){return We(t)?!!We(e):!1}function N$(t,e){let r=L$(t,e),n=F$(t,e),o=ke([t,e]),i=lu(ao(o));return r&&n?In(Sn(i)):r&&!n?In(i):!r&&n?Sn(i):i}function q$(t,e,r){return r in t?r in e?N$(t[r],e[r]):t[r]:r in e?e[r]:oe()}function B$(t,e){return[...new Set([...s.Keys(e),...s.Keys(t)])].reduce((n,o)=>({...n,[o]:q$(t,e,o)}),{})}function Ck(t){return N(t)?t.properties:V(t)?bl(t.items):Y()}function Ek(t,e){let r=Ck(t),n=Ck(e),o=B$(r,n);return O(o)}function $k(t,e){let r=vn(t,e);return s.IsEqual(r,ki)?t:s.IsEqual(r,Si)||s.IsEqual(r,yi)?e:oe()}function Mk(t){return N(t)||V(t)}function U$(t,e){let r=b(t),n=b(e);return r||n}function W$(t,e){let r=bn(t),n=bn(e),o=U$(r,n),i=Mk(r),a=Mk(n);return o?ke([r,n]):i&&a?Ek(r,n):i&&!a?r:!i&&a?n:$k(r,n)}function Ok(t,e,r=[]){return s.TakeLeft(e,(n,o)=>Ok(t,o,[...r,W$(t,n)]),()=>s.IsEqual(r.length,0)?[t]:r)}function _k(t,e,r=[]){return s.TakeLeft(t,(n,o)=>_k(o,e,[...r,...Ii([n],e)]),()=>r)}function Ii(t,e=[]){return s.TakeLeft(t,(r,n)=>b(r)?Ii(n,_k(r.anyOf,e)):Ii(n,Ok(r,e)),()=>e)}function ke(t){let e=Ii(t);return Al(e)}function Ot(t){return Al(t)}function bn(t){return D(t)?ke(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 Dk(t,e){let r=ke(t);return Ur(r,e)}function Lk(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 Fk(t,e){return ft(vu,e)}function Nk(t,e){return s.HasPropertyKey(t,"pattern")&&(s.IsString(t.pattern)||t.pattern instanceof RegExp)?ft(t.pattern.toString(),e):ft(Br,e)}function qk(t,e){let r=gi(t);return Pu(r)?Ur(He(t),e):ft(t,e)}function K$(t){return b(t)?Zt(t.anyOf):[t]}function Zt(t){return t.reduce((e,r)=>[...e,...K$(r)],[])}function j$(t){return t.some(e=>Ze(e)||be(e)||at(e))}function G$(t,e){return s.IsEqual(j$(t),!0)?ft(Br,e):void 0}function V$(t,e){return t.reduce((r,n)=>G(n)&&(s.IsString(n.const)||s.IsNumber(n.const))?{...r,[n.const]:e}:r,{})}function H$(t,e){let r=V$(t,e);return O(r)}function Bk(t,e){let r=Zt(t),n=G$(r,e);return de(n)?n:H$(r,e)}function Ur(t,e){return Ve(t)?wk(e):At(t)?vk(e):qe(t)?bk(t.enum,e):at(t)?Ak(t,e):D(t)?Dk(t.allOf,e):G(t)?Lk(t.const,e):be(t)?Fk(t,e):b(t)?Bk(t.anyOf,e):Ze(t)?Nk(t,e):Ae(t)?qk(t.pattern,e):O({})}function Tl(t,e,r){return L([t])?g.Update(Ur(t,e),{},r):Rl(t,e,r)}function Uk(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return Tl(i,a,o)}var lo=`^${hu}$`,vu=`^${Iu}$`,Br=`^${xu}$`;function Rl(t,e,r={}){return E("Record",[t,e],r)}function Wk(t,e,r={}){return Tl(t,e,r)}function Kk(t,e){return ft(t,e)}function _t(t){return s.Keys(t.patternProperties)[0]}function bu(t){let e=_t(t);return s.IsEqual(e,Br)?Tt():s.IsEqual(e,lo)?yu():s.IsEqual(e,vu)?Ut():vl(e)}function Xe(t){return t.patternProperties[_t(t)]}function Me(t){return v(t,"Record")}function Cl(t){return g.Create({"~kind":"Rest"},{type:"rest",items:t},{})}function mo(t){return v(t,"Rest")}function jk(t){return v(t,"This")}function El(t){return g.Create({"~kind":"Undefined"},{type:"undefined"},t)}function Tn(t){return v(t,"Undefined")}function Kt(t){return v(t,"Void")}function Gk(t){return mk()}function Vk(t){return Tt()}function Hk(t){return Ut()}function zk(t){return yu()}function Jk(t){return oe()}function Qk(t){return Z(t)}function Yk(t){return B(t[1])}function Zk(t){return t.length===3?[...t[0],...t[2]]:t.length===1?[...t[0]]:[]}function Xk(t){return[t[0],...t[1]]}function eS(t){return t[1]}function Tu(t){return J(t.length,2)}function It(t,e,r){return Tu(t)?e(t[0],t[1]):r()}function Y$(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=Y$(t[r],e);if(Tu(n))return n}return[]}function tm(t,e){return Array.from({length:e-t+1},(r,n)=>String.fromCharCode(t+n))}var tS=[...tm(97,122),...tm(65,90)],rS="0",nS=tm(49,57),co=[rS,...nS],oS=" ",xi=`
234
+ `;var fo="_";var iS="$";var sS="//",aS="/*",X$="*/";function uS(t){let e=t.indexOf(X$);return J(e,-1)?"":t.slice(e+2)}function pS(t){let e=t.indexOf(xi);return J(e,-1)?"":t.slice(e)}function eM(t){return t.replace(/^[ \t\r\f\v]+/,"")}function Ru(t){let e=eM(t);return e.startsWith(aS)?Ru(uS(e.slice(2))):e.startsWith(sS)?Ru(pS(e.slice(2))):e}function jt(t){let e=t.trimStart();return e.startsWith(aS)?jt(uS(e.slice(2))):e.startsWith(sS)?jt(pS(e.slice(2))):e}var YX=[...co,fo];function rm(t,e){return Xt([t],e)}function Gt(t,e){return J(t,"")?["",e]:t.startsWith(xi)?rm(t,Ru(e)):t.startsWith(oS)?rm(t,e):rm(t,jt(e))}var iM=[...tS,fo,iS];var vee=[...iM,...co];var Dee=[...co,fo];function sM(t){return J(t,"")?[]:[t.slice(0,1),t.slice(1)]}function dS(t,e){return _a(t,(r,n)=>e.startsWith(r)?!0:dS(n,e),()=>!1)}function Pi(t,e,r=""){return It(sM(e),(n,o)=>dS(t,e)?[r,e]:Pi(t,o,`${r}${n}`),()=>[])}function lS(t,e){return It(Pi(t,e),(r,n)=>J(r,"")?[]:[r,n],()=>[])}var X=(t,e,r=()=>[])=>t.length===2?e(t):r();var uM=t=>X(Gt("-?(?:0|[1-9][0-9]*)n",t),([e,r])=>[Gk(e),r]),pM=t=>X(Gt(".*",t),([e,r])=>[Vk(e),r]),dM=t=>X(Gt("-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?",t),([e,r])=>[Hk(e),r]),lM=t=>X(Gt("-?(?:0|[1-9][0-9]*)",t),([e,r])=>[zk(e),r]),mM=t=>X(Gt("(?!)",t),([e,r])=>[Jk(e),r]),cM=t=>X(lS(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],t),([e,r])=>[Qk(e),r]),fM=t=>X(X(uM(t),([e,r])=>[e,r],()=>X(pM(t),([e,r])=>[e,r],()=>X(dM(t),([e,r])=>[e,r],()=>X(lM(t),([e,r])=>[e,r],()=>X(mM(t),([e,r])=>[e,r],()=>X(gM(t),([e,r])=>[e,r],()=>X(cM(t),([e,r])=>[e,r],()=>[]))))))),([e,r])=>[e,r]),gM=t=>X(X(Gt("(",t),([e,r])=>X(om(r),([n,o])=>X(Gt(")",o),([i,a])=>[[e,n,i],a]))),([e,r])=>[Yk(e),r]),mS=t=>X(X(X(nm(t),([e,r])=>X(Gt("|",r),([n,o])=>X(mS(o),([i,a])=>[[e,n,i],a]))),([e,r])=>[e,r],()=>X(X(nm(t),([e,r])=>[[e],r]),([e,r])=>[e,r],()=>X([[],t],([e,r])=>[e,r],()=>[]))),([e,r])=>[Zk(e),r]),nm=t=>X(X(fM(t),([e,r])=>X(om(r),([n,o])=>[[e,n],o])),([e,r])=>[Xk(e),r]),om=t=>X(X(mS(t),([e,r])=>[e,r],()=>X(nm(t),([e,r])=>[e,r],()=>[])),([e,r])=>[e,r]),hk=t=>X(X(Gt("^",t),([e,r])=>X(om(r),([n,o])=>X(Gt("$",o),([i,a])=>[[e,n,i],a]))),([e,r])=>[eS(e),r]);function yM(t){return t.join("|")}function kM(t){return t.slice(1,t.length-1)}function SM(t,e,r){return Wr(e,`${r}${t}`)}function IM(t,e){return Wr(t,`${e}${lk}`)}function xM(t,e){return Wr(t,`${e}${hu}`)}function PM(t,e){return Wr(t,`${e}${Iu}`)}function wM(t,e){return Cu(B([Z("false"),Z("true")]),t,e)}function vM(t,e){return Wr(t,`${e}${xu}`)}function bM(t,e,r){return Wr(e,`${r}${kM(t)}`)}function AM(t,e,r){let n=Eu(t,{});return Cu(n,e,r)}function TM(t,e,r){let n=Wt(t);return im(n,e,r)}function im(t,e,r,n=[]){return s.TakeLeft(t,(o,i)=>im(i,e,r,[...n,Cu(o,[],"")]),()=>Wr(e,`${r}(${yM(n)})`))}function Cu(t,e,r){return qe(t)?TM(t.enum,e,r):at(t)?xM(e,r):G(t)?SM(t.const,e,r):Bt(t)?IM(e,r):At(t)?wM(e,r):be(t)?PM(e,r):Ze(t)?vM(e,r):Ae(t)?bM(t.pattern,e,r):fS(t)?AM(t.parameters[0],e,r):b(t)?im(t.anyOf,e,r):ok}function Wr(t,e){return s.TakeLeft(t,(r,n)=>Cu(r,n,e),()=>e)}function RM(t){return`^${Wr(t,"")}$`}function cS(t){let e=RM(t);return wu(e)}function Eu(t,e){return L(t)?g.Update(cS(t),{},e):$l(t,e)}function gS(t,e,r,n){let o=Rt(t,e,r);return Eu(o,n)}function $l(t,e={}){return E("TemplateLiteral",[t],e)}function fS(t){return de(t)&&s.HasPropertyKey(t,"action")&&s.IsEqual(t.action,"TemplateLiteral")}function Ae(t){return v(t,"TemplateLiteral")}var F={};Ct(F,{ExtendsFalse:()=>U,ExtendsTrue:()=>A,ExtendsUnion:()=>sm,IsExtendsFalse:()=>CM,IsExtendsTrue:()=>yS,IsExtendsTrueLike:()=>go,IsExtendsUnion:()=>hS,Match:()=>Oe});function sm(t){return g.Create({"~kind":"ExtendsUnion"},{inferred:t})}function hS(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 yS(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.HasPropertyKey(t,"inferred")&&s.IsEqual(t["~kind"],"ExtendsTrue")&&s.IsObject(t.inferred)}function U(){return g.Create({"~kind":"ExtendsFalse"},{})}function CM(t){return s.IsObject(t)&&s.HasPropertyKey(t,"~kind")&&s.IsEqual(t["~kind"],"ExtendsFalse")}function go(t){return hS(t)||yS(t)}function Oe(t,e,r){return go(t)?e(t.inferred):r()}function EM(t,e,r,n){return Oe(re(t,r,n),o=>A(g.Assign(g.Assign(t,o),{[e]:r})),()=>U())}function $M(t,e){return A(t)}function MM(t,e,r){let n=hi(r);return re(t,e,n)}function kS(t,e,r){return s.TakeLeft(r,(n,o)=>Oe(re(t,e,n),i=>kS(i,e,o),()=>U()),()=>A(t))}function OM(t,e,r){let n=He(r);return re(t,e,n)}function SS(t,e,r){return s.TakeLeft(r,(n,o)=>Oe(re(t,e,n),i=>A(i),()=>SS(t,e,o)),()=>U())}function W(t,e,r){return Ve(r)?$M(t,e):qe(r)?MM(t,e,r.enum):$e(r)?EM(t,r.name,e,r.extends):D(r)?kS(t,e,r.allOf):Ae(r)?OM(t,e,r.pattern):b(r)?SS(t,e,r.anyOf):Ye(r)?A(t):U()}function IS(t,e,r){return $e(r)?W(t,e,r):Ve(r)?A(t):Ye(r)?A(t):sm(t)}function _M(t,e){let r=mi(t),n=mi(e);return r&&n||!r&&n?!0:!(r&&!n)}function xS(t,e,r,n){return te(n)?_M(e,n)?re(t,r,n.items):U():W(t,e,n)}function PS(t,e,r){return st(r)?re(t,e,r.iteratorItems):W(t,mr(e),r)}function wS(t,e,r){return Bt(r)?A(t):W(t,e,r)}function vS(t,e,r){return At(r)?A(t):W(t,e,r)}function DM(t,e,r,n,o){let i=$e(n)?e:n,a=$e(n)?n:e,u=We(e),p=We(n);return!u&&p?U():Oe(re(t,i,a),d=>wi(d,r,o),()=>U())}function LM(t,e,r,n){return s.TakeLeft(n,(o,i)=>DM(t,e,r,o,i),()=>We(e)?A(t):U())}function FM(t,e,r){return s.TakeLeft(e,(n,o)=>LM(t,n,o,r),()=>A(t))}function wi(t,e,r){return FM(t,e,r)}function $u(t,e,r){return Kt(r)?A(t):re(t,e,r)}function bS(t,e,r,n){return Ve(n)?A(t):Ye(n)?A(t):Fe(n)?Oe(wi(t,e,n.parameters),o=>$u(o,r,n.instanceType),()=>U()):U()}function AS(t,e,r){return re(t,po(e),r)}function TS(t,e,r,n){return Ve(n)?A(t):Ye(n)?A(t):Ne(n)?Oe(wi(t,e,n.parameters),o=>$u(o,r,n.returnType),()=>U()):U()}function RS(t,e,r){return at(r)?A(t):be(r)?A(t):W(t,e,r)}function CS(t,e,r){let n=ke(e);return re(t,n,r)}function ES(t,e,r){return ut(r)?re(t,e,r.iteratorItems):W(t,cr(e),r)}function Mu(t,e,r){return e===r?A(t):U()}function NM(t,e,r){return G(r)?Mu(t,e,r.const):Bt(r)?A(t):W(t,Z(e),r)}function qM(t,e,r){return G(r)?Mu(t,e,r.const):At(r)?A(t):W(t,Z(e),r)}function BM(t,e,r){return G(r)?Mu(t,e,r.const):be(r)?A(t):W(t,Z(e),r)}function UM(t,e,r){return G(r)?Mu(t,e,r.const):Ze(r)?A(t):W(t,Z(e),r)}function $S(t,e,r){return s.IsBigInt(e.const)?NM(t,e.const,r):s.IsBoolean(e.const)?qM(t,e.const,r):s.IsNumber(e.const)?BM(t,e.const,r):s.IsString(e.const)?UM(t,e.const,r):Y()}function MS(t,e,r){return $e(r)?W(t,e,r):A(t)}function OS(t,e,r){return wn(r)?A(t):W(t,e,r)}function _S(t,e,r){return be(r)?A(t):W(t,e,r)}function WM(t,e,r){return We(e)?We(r)?A(t):U():A(t)}function KM(t,e,r){return $e(r)&&Nr(r.extends)?U():Oe(re(t,e,r),n=>WM(n,e,r),()=>U())}function jM(t,e){return t.reduce((r,n)=>n in e?go(e[n])?{...r,...e[n].inferred}:Y():Y(),{})}function GM(t,e,r){let n={};for(let a of s.Keys(r))n[a]=a in e?KM({},e[a],r[a]):We(r[a])?$e(r[a])?A(g.Assign(t,{[r[a].name]:r[a].extends})):A(t):U();let o=s.Values(n).every(a=>go(a)),i=o?jM(s.Keys(n),n):{};return o?A(i):U()}function VM(t,e,r){let n=GM(t,e,r);return go(n)?A(g.Assign(t,n.inferred)):U()}function HM(t,e,r){return VM(t,e,r)}function DS(t,e,r){return N(r)?HM(t,e,r.properties):W(t,O(e),r)}function LS(t,e,r){return Ge(r)?re(t,e,r.item):W(t,dr(e),r)}function FS(t,e,r){return Ze(r)?A(t):W(t,e,r)}function NS(t,e,r){return uo(r)?A(t):W(t,e,r)}function qS(t,e,r){let n=He(e);return re(t,n,r)}function am(t,e){return g.Create({"~kind":"Inferrable"},{name:t,type:e},{})}function vi(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 um(t){return mo(t)?$e(t.items)?te(t.items.extends)?am(t.items.name,t.items.extends.items):Ye(t.items.extends)?am(t.items.name,t.items.extends):void 0:Y():void 0}function Ou(t){return $e(t)?am(t.name,t.extends):void 0}function pm(t,e,r=[]){return s.TakeLeft(t,(n,o)=>Oe(re({},n,e),()=>pm(o,e,[...r,n]),()=>{}),()=>r)}function BS(t,e,r,n){let o=pm(r,n);return s.IsArray(o)?A(g.Assign(t,{[e]:Ke(o)})):U()}function _u(t,e,r,n){let o=pm(r,n);return s.IsArray(o)?A(g.Assign(t,{[e]:B(o)})):U()}function zM(t){return[...t].reverse()}function dm(t,e){return e?zM(t):t}function JM(t){let e=t.length>0?t[0]:void 0,r=de(e)?um(e):void 0;return de(r)}function QM(t,e,r,n,o,i){return Oe(re(t,r,o),a=>US(a,e,n,i),()=>U())}function YM(t,e,r,n,o){let i=um(n);return vi(i)?BS(t,i.name,dm(r,e),i.type):s.TakeLeft(r,(a,u)=>QM(t,e,a,u,n,o),()=>U())}function ZM(t,e,r,n){return s.TakeLeft(n,(o,i)=>YM(t,e,r,o,i),()=>s.IsEqual(r.length,0)?A(t):U())}function US(t,e,r,n){return ZM(t,e,r,n)}function XM(t,e,r){let n=Kr(t,{callstack:[]},r),o=JM(n);return US(t,o,dm(e,o),dm(n,o))}function WS(t,e,r){let n=Ou(r);return vi(n)?_u(t,n.name,e,n.type):s.TakeLeft(e,(o,i)=>Oe(re(t,o,r),a=>WS(a,i,r),()=>U()),()=>A(t))}function KS(t,e,r){let n=Kr(t,{callstack:[]},e);return V(r)?XM(t,n,r.items):te(r)?WS(t,n,r.items):W(t,Ke(n),r)}function jS(t,e,r){return Kt(r)?A(t):Tn(r)?A(t):W(t,e,r)}function GS(t,e,r){return s.TakeLeft(r,(n,o)=>Oe(re(t,e,n),i=>A(i),()=>GS(t,e,o)),()=>U())}function lm(t,e,r){return s.TakeLeft(e,(n,o)=>Oe(GS(t,n,r),i=>lm(i,o,r),()=>U()),()=>A(t))}function VS(t,e,r){let n=Ou(r);return vi(n)?_u(t,n.name,e,n.type):b(r)?lm(t,e,r.anyOf):lm(t,e,[r])}function HS(t,e,r){return $e(r)?W(t,e,r):Ve(r)?A(t):Ye(r)?A(t):U()}function zS(t,e,r){return Kt(r)?A(t):W(t,e,r)}function re(t,e,r){return Ve(e)?IS(t,e,r):te(e)?xS(t,e,e.items,r):st(e)?PS(t,e.iteratorItems,r):Bt(e)?wS(t,e,r):At(e)?vS(t,e,r):Fe(e)?bS(t,e.parameters,e.instanceType,r):qe(e)?AS(t,e,r):Ne(e)?TS(t,e.parameters,e.returnType,r):at(e)?RS(t,e,r):D(e)?CS(t,e.allOf,r):ut(e)?ES(t,e.iteratorItems,r):G(e)?$S(t,e,r):Nr(e)?MS(t,e,r):wn(e)?OS(t,e,r):be(e)?_S(t,e,r):N(e)?DS(t,e.properties,r):Ge(e)?LS(t,e.item,r):Ze(e)?FS(t,e,r):uo(e)?NS(t,e,r):Ae(e)?qS(t,e.pattern,r):V(e)?KS(t,e.items,r):Tn(e)?jS(t,e,r):b(e)?VS(t,e.anyOf,r):Ye(e)?HS(t,e,r):Kt(e)?zS(t,e,r):U()}function eO(t,e){return ke([...t,O(e)])}function JS(t,e,r){return L(t)?g.Update(eO(t,e),{},r):Ml(t,e,r)}function QS(t,e,r,n,o){let i=Rt(t,e,r),a=bi(t,e,n);return JS(i,a,o)}function Ml(t,e,r={}){return E("Interface",[t,e],r)}function ho(t){return de(t)&&s.HasPropertyKey(t,"action")&&s.IsEqual(t.action,"Interface")}function tO(t,e,r){return t.includes(r)?!0:jr([...t,r],e,e[r])}function YS(t,e,r){let n=gu(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)?tO(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]):ho(r)?YS(t,e,r.parameters[1]):D(r)?Rn(t,e,r.allOf):ut(r)?jr(t,e,r.iteratorItems):N(r)?YS(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,Xe(r)):!1}function Du(t,e,r){return jr(t,e,r)}function rO(t,e){return e.reduce((r,n)=>n in t?Du([n],t,t[n])?[...r,n]:r:Y(),[])}function ZS(t){let e=fu(t);return rO(t,e)}function nO(t,e,r){return r.includes(e)?r:e in t?Gr(t,t[e],[...r,e]):Y()}function XS(t,e,r){let n=gu(e);return yo(t,n,r)}function yo(t,e,r){return e.reduce((n,o)=>Gr(t,o,n),r)}function Gr(t,e,r){return se(e)?nO(t,e.$ref,r):te(e)?Gr(t,e.items,r):st(e)?Gr(t,e.iteratorItems,r):Fe(e)?yo(t,[...e.parameters,e.instanceType],r):Ne(e)?yo(t,[...e.parameters,e.returnType],r):ho(e)?XS(t,e.parameters[1],r):D(e)?yo(t,e.allOf,r):ut(e)?Gr(t,e.iteratorItems,r):N(e)?XS(t,e.properties,r):Ge(e)?Gr(t,e.item,r):b(e)?yo(t,e.anyOf,r):V(e)?yo(t,e.items,r):Me(e)?Gr(t,Xe(e),r):r}function eI(t,e,r){return Gr(t,r,[e])}function oO(t){return Sl()}function iO(t){return s.Keys(t).reduce((e,r)=>({...e,[r]:er(t[r])}),{})}function Ai(t){return t.reduce((e,r)=>[...e,er(r)],[])}function er(t){return se(t)?oO(t.$ref):te(t)?lr(er(t.items),mu(t)):st(t)?mr(er(t.iteratorItems)):Fe(t)?xn(Ai(t.parameters),er(t.instanceType)):Ne(t)?Pn(Ai(t.parameters),er(t.returnType)):D(t)?qt(Ai(t.allOf)):ut(t)?cr(er(t.iteratorItems)):N(t)?O(iO(t.properties)):Ge(t)?dr(er(t.item)):Me(t)?Wk(bu(t),er(Xe(t))):b(t)?B(Ai(t.anyOf)):V(t)?Ke(Ai(t.items)):t}function sO(t,e){return e in t?er(t[e]):Yt()}function tI(t){return sO(t.$defs,t.$ref)}function aO(t,e,r){let n=Rt(t,{callstack:[]},e),o=bi({},{callstack:[]},r);return ke([...n,O(o)])}function uO(t,e){return s.Keys(t).filter(n=>e.includes(n)).reduce((n,o)=>{let i=t[o],a=ho(i)?aO(t,i.parameters[0],i.parameters[1]):i;return{...n,[o]:a}},{})}function rI(t,e,r){let n=eI(t,e,r),o=uO(t,n);return qr(o,e)}function nI(t,e){return e in t?se(t[e])?nI(t,t[e].$ref):t[e]:oe()}function tr(t,e){return nI(t,e)}function oI(t){return ge(t)?tI(t):uk(t)?Yt():t}function pt(t,e,r){let n=oI(e),o=oI(r);return re(t,n,o)}var yi="equal",pO="disjoint",ki="left-inside",Si="right-inside";function vn(t,e){let r=[Ye(t)?F.ExtendsFalse():pt({},t,e),Ye(t)?F.ExtendsTrue({}):pt({},e,t)];return F.IsExtendsTrueLike(r[0])&&F.IsExtendsTrueLike(r[1])?yi:F.IsExtendsTrueLike(r[0])&&F.IsExtendsFalse(r[1])?ki:F.IsExtendsFalse(r[0])&&F.IsExtendsTrueLike(r[1])?Si:pO}function dO(t,e){return e.filter(r=>vn(t,r)!==Si)}function lO(t,e){let r=e.some(n=>{let o=vn(t,n);return s.IsEqual(o,ki)||s.IsEqual(o,yi)});return s.IsEqual(r,!1)}function mO(t,e){let r=bn(t);return Ve(r)?[r]:lO(r,e)?[...dO(r,e),r]:e}function cO(t){return t.reduce((e,r)=>N(r)?[...e,r]:Nr(r)?e:mO(r,e),[])}function Al(t){let e=cO(t),r=Zt(e);return r.length===0?oe():r.length===1?r[0]:B(r)}function mm(t,e){return g.Update(bn(t),{},e)}function iI(t,e,r,n){let o=P(t,e,r);return mm(o,n)}function Ti(t,e=[]){return Fr(t)&&s.IsEqual(t.action,"Conditional")?se(t.parameters[0])?Ti(t.parameters[2],Ti(t.parameters[3],[...e,t.parameters[0].$ref])):Ti(t.parameters[2],Ti(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 fO(t,e){return t.reduce((r,n)=>[...r,e.includes(n.name)],[])}function uI(t,e,r=[]){return s.TakeLeft(t,(n,o)=>s.TakeLeft(e,(i,a)=>uI(o,a,[...r,[i,n]]),()=>r),()=>r)}function gO(t){return b(t)?[...t.anyOf]:[t]}function hO(t,e){return t.reduce((r,n)=>[...r,[...n,e]],[])}function sI(t,e){return e.reduce((r,n)=>[...r,...hO(t,n)],[])}function aI(t){return t.reduce((e,r)=>s.IsEqual(r[0],!0)?sI(e,gO(r[1])):sI(e,[r[1]]),[[]])}function pI(t,e,r){let n=Ti(r),o=fO(t,n),i=uI(e,o);return Fr(r)&&s.IsEqual(r.action,"Conditional")||Fr(r)&&s.IsEqual(r.action,"Mapped")?aI(i):[e]}function yO(){return["(not-resolvable)",oe()]}function kO(){return["(not-generic)",oe()]}function SO(t,e,r){return[t,kl(e,r)]}function IO(t,e,r){return e in t?dI(t,e,t[e],r):yO()}function dI(t,e,r,n){return cu(r)?SO(e,r.parameters,r.expression):se(r)?IO(t,r.$ref,n):kO()}function lI(t,e,r){return dI(t,"(anonymous)",e,r)}function xO(t,e,r){if($e(e)||Lu(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 mI(t,e,r,n,o){let i=P(t,e,o);return xO(r,i,n),g.Assign(t,{[r]:i})}function PO(t,e,r,n,o){let i=P(t,e,r.extends),a=P(t,e,r.equals);return s.TakeLeft(o,(u,p)=>cm(mI(t,e,r.name,i,u),e,n,p),()=>cm(mI(t,e,r.name,i,a),e,n,[]))}function cm(t,e,r,n){return s.TakeLeft(r,(o,i)=>PO(t,e,o,i,n),()=>t)}function cI(t,e,r,n){return cm(t,e,r,n)}function wO(t){return s.IsGreaterThan(t.callstack.length,0)?t.callstack[t.callstack.length-1]:""}function vO(t,e){return s.IsEqual(wO(t),e)}function bO(t,e,r,n,o,i){let a=cI(t,e,n,i),u=P(a,{callstack:[...e.callstack,r.$ref]},o);return P(t,e,u)}function AO(t,e,r,n,o,i){return i.reduce((a,u)=>[...a,bO(t,e,r,n,o,u)],[])}function TO(t,e,r,n,o,i){let a=pI(n,i,o),u=AO(t,e,r,n,o,a);return s.IsEqual(u.length,1)?u[0]:Ot(u)}function fm(t,e,r,n){let o=Rt(t,e,n),i=lI(t,r,n),a=i[0],u=i[1];return cu(u)?vO(e,a)?Au(St(a),o):TO(t,e,St(a),u.parameters,u.expression,o):Au(r,o)}function Au(t,e){return g.Create({"~kind":"Call"},{target:t,arguments:e},{})}function Lu(t){return v(t,"Call")}function fI(t,e){return t(e)}function gI(t,e){return s.IsString(e)?Z(fI(t,e)):Z(e)}function hI(t,e){let r=He(e);return fr(t,r)}function yI(t,e){let r=e.map(n=>fr(t,n));return B(r)}function fr(t,e){return G(e)?gI(t,e.const):Ae(e)?hI(t,e.pattern):b(e)?yI(t,e.anyOf):e}function Ol(t,e={}){return E("Capitalize",[t],e)}function _l(t,e={}){return E("Lowercase",[t],e)}function Dl(t,e={}){return E("Uncapitalize",[t],e)}function Ll(t,e={}){return E("Uppercase",[t],e)}var RO=t=>t[0].toUpperCase()+t.slice(1),CO=t=>t.toLowerCase(),EO=t=>t[0].toLowerCase()+t.slice(1),$O=t=>t.toUpperCase();function kI(t,e){return L([t])?g.Update(fr(RO,t),{},e):Ol(t,e)}function SI(t,e){return L([t])?g.Update(fr(CO,t),{},e):_l(t,e)}function II(t,e){return L([t])?g.Update(fr(EO,t),{},e):Dl(t,e)}function xI(t,e){return L([t])?g.Update(fr($O,t),{},e):Ll(t,e)}function PI(t,e,r,n){let o=P(t,e,r);return kI(o,n)}function wI(t,e,r,n){let o=P(t,e,r);return SI(o,n)}function vI(t,e,r,n){let o=P(t,e,r);return II(o,n)}function bI(t,e,r,n){let o=P(t,e,r);return xI(o,n)}function Fl(t,e,r,n,o={}){return E("Conditional",[t,e,r,n],o)}function MO(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 AI(t,e,r,n,o,i,a){return L([r,n])?g.Update(MO(t,e,r,n,o,i),{},a):Fl(r,n,o,i,a)}function TI(t,e,r,n,o,i,a){let u=P(t,e,r),p=P(t,e,n);return AI(t,e,u,p,o,i,a)}function Nl(t,e={}){return E("ConstructorParameters",[t],e)}function OO(t){let e=Fe(t)?t.parameters:[],r=Kr({},{callstack:[]},e);return Ke(r)}function RI(t,e){return L([t])?g.Update(OO(t),{},e):Nl(t,e)}function CI(t,e,r,n){let o=P(t,e,r);return RI(o,n)}function ql(t,e,r={}){return E("Exclude",[t,e],r)}function EI(t,e){return t.reduce((r,n)=>[...r,...$I(n,e)],[])}function $I(t,e){let r=pt({},t,e);return F.IsExtendsTrueLike(r)?[]:[t]}function MI(t,e){let r=qe(t)?EI(Wt(t.enum),e):b(t)?EI(Zt(t.anyOf),e):$I(t,e);return Ot(r)}function Fu(t,e,r){return L([t,e])?g.Update(MI(t,e),{},r):ql(t,e,r)}function OI(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return Fu(i,a,o)}function Bl(t,e,r={}){return E("Extract",[t,e],r)}function DI(t,e){return t.reduce((r,n)=>[...r,...LI(n,e)],[])}function LI(t,e){let r=pt({},t,e);return F.IsExtendsTrueLike(r)?[t]:[]}function FI(t,e){let r=qe(t)?DI(Wt(t.enum),e):b(t)?DI(Zt(t.anyOf),e):LI(t,e);return Ot(r)}function _I(t,e,r){return L([t,e])?g.Update(FI(t,e),{},r):Bl(t,e,r)}function NI(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return _I(i,a,o)}function Ul(t,e,r={}){return E("Index",[t,e],r)}function UI(t,e){let r=tr(t,e);return Vt(r)}function _O(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]:ke([t[m],e[m]])}),{}),p=g.Assign(i,a);return g.Assign(p,u)}function WI(t){return t.reduce((e,r)=>_O(e,Vt(r)),{})}function KI(t){let e=Rk(Ke(t));return Vt(e)}function DO(t,e){return s.Keys(t).filter(o=>o in e).reduce((o,i)=>({...o,[i]:Ot([t[i],e[i]])}),{})}function jI(t,e){return s.TakeLeft(t,(r,n)=>jI(n,DO(e,Vt(r))),()=>e)}function GI(t){return s.TakeLeft(t,(e,r)=>jI(r,Vt(e)),()=>Y())}function Vt(t){return ge(t)?UI(t.$defs,t.$ref):D(t)?WI(t.allOf):b(t)?GI(t.anyOf):V(t)?KI(t.items):N(t)?t.properties:{}}function ko(t){let e=Vt(t);return O(e)}var LO=new RegExp("^(?:0|[1-9][0-9]*)$");function So(t){let e=`${t}`;return LO.test(e)?parseInt(e):t}function FO(t){return Z(So(t))}function VI(t){return t.map(e=>HI(e))}function HI(t){return D(t)?qt(VI(t.allOf)):b(t)?B(VI(t.anyOf)):G(t)?FO(t.const):t}function zI(t,e){let r=HI(e),n=pt({},r,Ut());return F.IsExtendsTrueLike(n)?t:G(e)&&s.IsEqual(e.const,"length")?Ut():oe()}function JI(t,e){let r=tr(t,e);return rr(r)}function Nu(t){return t.reduce((e,r)=>[...e,...rr(r)],[])}function QI(t){let e=Wt(t);return Nu(e)}function YI(t){let e=ke(t);return rr(e)}function ZI(t){return[`${t}`]}function XI(t){let e=He(t);return rr(e)}function rr(t){return ge(t)?JI(t.$defs,t.$ref):qe(t)?QI(t.enum):D(t)?YI(t.allOf):G(t)?ZI(t.const):Ae(t)?XI(t.pattern):b(t)?Nu(t.anyOf):[]}function Io(t){return rr(t)}function Ri(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(Ri(t,e.parameters),Vr(t,e.instanceType)):Ne(e)?Pn(Ri(t,e.parameters),Vr(t,e.returnType)):ut(e)?cr(Vr(t,e.iteratorItems)):Ge(e)?dr(Vr(t,e.item)):V(e)?Ke(Ri(t,e.items)):b(e)?B(Ri(t,e.anyOf)):D(e)?qt(Ri(t,e.allOf)):jk(e)?O(t):e}function ex(t,e){return Vr(t,e)}function NO(t,e){let r=e in t?t[e]:oe();return ex(t,r)}function tx(t,e){return e.reduce((r,n)=>[...r,NO(t,n)],[])}function qO(t,e){let r=Io(e),n=tx(t,r);return Ot(n)}var BO=new RegExp(lo);function UO(t){return t.filter(r=>BO.test(r))}function WO(t){let e=fu(t),r=UO(e),n=tx(t,r);return Ot(n)}function rx(t,e){return be(e)?WO(t):qO(t,e)}function KO(t){return Z(So(t))}function nx(t){return t.map(e=>gm(e))}function gm(t){return D(t)?qt(nx(t.allOf)):b(t)?B(nx(t.anyOf)):G(t)?KO(t.const):t}function jO(t,e){return t.reduceRight((r,n,o)=>{let i=pt({},Z(o),e);return F.IsExtendsTrueLike(i)?[n,...r]:r},[])}function GO(t,e){let r=gm(e),n=jO(t,r);return An(n)}function VO(t){return An(t)}function ox(t,e){return G(e)&&s.IsEqual(e.const,"length")?Z(t.length):be(e)||at(e)?VO(t):GO(t,e)}function ix(t,e){return te(t)?zI(t.items,e):N(t)?rx(t.properties,e):V(t)?ox(t.items,e):oe()}function HO(t){return ge(t)||D(t)||b(t)?ko(t):t}function BI(t,e,r){return L([t,e])?g.Update(ix(HO(t),e),{},r):Ul(t,e,r)}function sx(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return BI(i,a,o)}function Wl(t,e={}){return E("InstanceType",[t],e)}function zO(t){return Fe(t)?t.instanceType:oe()}function ax(t,e){return L([t])?g.Update(zO(t),{},e):Wl(t,e)}function ux(t,e,r,n={}){let o=P(t,e,r);return ax(o,n)}function Kl(t,e={}){return E("KeyOf",[t],e)}function dx(){return B([Ut(),Tt(),wl()])}function lx(t){return Ut()}function JO(t){return t.reduce((r,n)=>Pl(n)?[...r,Z(So(n))]:Y(),[])}function mx(t){let e=s.Keys(t),r=JO(e);return An(r)}function cx(t){return bu(t)}function fx(t){let e=t.map((r,n)=>Z(n));return An(e)}function gx(t){return Ve(t)?dx():te(t)?lx(t.items):N(t)?mx(t.properties):Me(t)?cx(t):V(t)?fx(t.items):oe()}function QO(t){return ge(t)||D(t)||b(t)?ko(t):t}function px(t,e){return L([t])?g.Update(gx(QO(t)),{},e):Kl(t,e)}function hx(t,e,r,n){let o=P(t,e,r);return px(o,n)}function jl(t,e,r,n,o={}){return E("Mapped",[t,e,r,n],o)}function YO(t){let e=He(t);return hm(e)}function kx(t){return t.reduce((e,r)=>[...e,...hm(r)],[])}function ZO(t){return s.IsNumber(t)?[Z(`${t}`)]:[Z(t)]}function hm(t){return qe(t)?kx(Wt(t.enum)):G(t)?ZO(t.const):Ae(t)?YO(t.pattern):b(t)?kx(t.anyOf):[t]}function Sx(t){return hm(t)}function XO(t){return Ae(t)?He(t.pattern):t}function e_(t,e,r,n,o,i){let a=g.Assign(t,{[r.name]:n}),u=P(a,e,o),p=XO(u),d=P(a,e,i);return ku(p)||Su(p)?{[p.const]:d}:{}}function t_(t,e,r,n,o,i){return n.reduce((a,u)=>[...a,e_(t,e,r,u,o,i)],[])}function r_(t){return t.reduce((e,r)=>[...e,O(r)],[])}function Ix(t,e,r,n,o,i){let a=Sx(n),u=t_(t,e,r,a,o,i),p=r_(u);return ke(p)}function yx(t,e,r,n,o,i,a){return L([n])?g.Update(Ix(t,e,r,n,o,i),{},a):jl(r,n,o,i,a)}function xx(t,e,r,n,o,i,a){let u=P(t,e,n);return yx(t,e,r,u,o,i,a)}function n_(t,e){return s.Keys(t).filter(n=>e.includes(n)).reduce((n,o)=>({...n,[o]:rI(t,o,t[o])}),{})}function o_(t,e){return s.Keys(t).filter(n=>!e.includes(n)).reduce((n,o)=>({...n,[o]:P(t,{callstack:[]},t[o])}),{})}function i_(t,e){let r=ZS(t),n=n_(t,r),o=o_(t,r),i={...n,...o};return g.Update(i,{},e)}function Px(t,e,r,n){let o=g.Assign(t,r);return i_(o,n)}function Gl(t,e={}){return E("NonNullable",[t],e)}function s_(t){let e=B([fi(),El()]);return Fu(t,e,{})}function wx(t,e){return L([t])?g.Update(s_(t),{},e):Gl(t,e)}function vx(t,e,r,n){let o=P(t,e,r);return wx(o,n)}function Vl(t,e,r={}){return E("Omit",[t,e],r)}function qu(t){let e=ko(t);return N(e)?e.properties:Y()}function a_(t,e){return s.Keys(t).reduce((n,o)=>e.includes(o)?n:{...n,[o]:t[o]},{})}function Ax(t,e){let r=qu(t),n=Io(e),o=a_(r,n);return O(o)}function bx(t,e,r){return L([t,e])?g.Update(Ax(t,e),{},r):Vl(t,e,r)}function Tx(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return bx(i,a,o)}function Hl(t,e){return E("Options",[t,e],{})}function Rx(t,e){return ym(t,e)}function ym(t,e){return L([t])?g.Update(t,{},e):Hl(t,e)}function Cx(t,e,r,n){let o=P(t,e,r);return ym(o,n)}function zl(t,e={}){return E("Parameters",[t],e)}function u_(t){let e=Ne(t)?t.parameters:[],r=Kr({},{callstack:[]},e);return Ke(r)}function Ex(t,e){return L([t])?g.Update(u_(t),{},e):zl(t,e)}function $x(t,e,r,n){let o=P(t,e,r);return Ex(o,n)}function Jl(t,e={}){return E("Partial",[t],e)}function Ox(t,e){let r=tr(t,e),n=Hr(r);return qr(g.Assign(t,{[e]:n}),e)}function _x(t){let e=t.map(r=>Hr(r));return ke(e)}function Dx(t){let e=t.map(r=>Hr(r));return B(e)}function Lx(t){let e=s.Keys(t).reduce((n,o)=>({...n,[o]:Xy(t[o])}),{});return O(e)}function Hr(t){return ge(t)?Ox(t.$defs,t.$ref):D(t)?_x(t.allOf):b(t)?Dx(t.anyOf):N(t)?Lx(t.properties):O({})}function Mx(t,e){return L([t])?g.Update(Hr(t),{},e):Jl(t,e)}function Fx(t,e,r,n){let o=P(t,e,r);return Mx(o,n)}function Ql(t,e,r={}){return E("Pick",[t,e],r)}function p_(t,e){return s.Keys(t).reduce((n,o)=>e.includes(o)?g.Assign(n,{[o]:t[o]}):n,{})}function qx(t,e){let r=qu(t),n=Io(e),o=p_(r,n);return O(o)}function Nx(t,e,r){return L([t,e])?g.Update(qx(t,e),{},r):Ql(t,e,r)}function Bx(t,e,r,n,o){let i=P(t,e,r),a=P(t,e,n);return Nx(i,a,o)}function Yl(t,e={}){return E("ReadonlyObject",[t],e)}function Wx(t){return so(lr(t))}function Kx(t,e){let r=tr(t,e),n=zr(r);return qr(g.Assign(t,{[e]:n}),e)}function jx(t){let e=t.map(r=>zr(r));return ke(e)}function Gx(t){let e=s.Keys(t).reduce((n,o)=>({...n,[o]:ek(t[o])}),{});return O(e)}function Vx(t){return so(Ke(t))}function Hx(t){let e=t.map(r=>zr(r));return B(e)}function zr(t){return te(t)?Wx(t.items):ge(t)?Kx(t.$defs,t.$ref):D(t)?jx(t.allOf):N(t)?Gx(t.properties):V(t)?Vx(t.items):b(t)?Hx(t.anyOf):t}function Ux(t,e){return L([t])?g.Update(zr(t),{},e):Yl(t)}function zx(t,e,r,n){let o=P(t,e,r);return Ux(o,n)}function Jx(t,e,r,n){return n in t?Du([n],t,t[n])?r:P(t,e,t[n]):r}function Qx(t,e){let r=tr(t,e),n=Jr(r);return qr(g.Assign(t,{[e]:n}),e)}function Yx(t){let e=t.map(r=>Jr(r));return ke(e)}function Zx(t){let e=t.map(r=>Jr(r));return B(e)}function Xx(t){let e=s.Keys(t).reduce((n,o)=>({...n,[o]:ao(t[o])}),{});return O(e)}function Jr(t){return ge(t)?Qx(t.$defs,t.$ref):D(t)?Yx(t.allOf):b(t)?Zx(t.anyOf):N(t)?Xx(t.properties):O({})}function Zl(t,e={}){return E("Required",[t],e)}function eP(t,e){return L([t])?g.Update(Jr(t),{},e):Zl(t,e)}function tP(t,e,r,n){let o=P(t,e,r);return eP(o,n)}function Xl(t,e={}){return E("ReturnType",[t],e)}function d_(t){return Ne(t)?t.returnType:oe()}function rP(t,e){return L([t])?g.Update(d_(t),{},e):Xl(t,e)}function nP(t,e,r,n={}){let o=P(t,e,r);return rP(o,n)}function l_(t){return mo(t)?V(t.items)?km(t.items.items):$e(t.items)?[t]:se(t.items)?[t]:[oe()]:[t]}function km(t){return t.reduce((r,n)=>[...r,...l_(n)],[])}function L(t){return s.TakeLeft(t,(e,r)=>se(e)?!1:L(r),()=>!0)}function Ci(t,e,r){return Qy(t)?Ci(t.type,"remove",r):zy(t)?Ci(t.type,e,"remove"):Jy(t)?Ci(t.type,"add",r):Hy(t)?Ci(t.type,e,"add"):[t,e,r]}function m_(t,e){return s.IsEqual(t,"remove")?lu(e):s.IsEqual(t,"add")?In(e):e}function c_(t,e){return s.IsEqual(t,"remove")?ao(e):s.IsEqual(t,"add")?Sn(e):e}function bi(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 km(n)}function Rt(t,e,r){return r.map(n=>P(t,e,n))}function f_(t,e,r,n,o){return s.IsEqual(r,"Awaited")?oP(t,e,n[0],o):s.IsEqual(r,"Capitalize")?PI(t,e,n[0],o):s.IsEqual(r,"Conditional")?TI(t,e,n[0],n[1],n[2],n[3],o):s.IsEqual(r,"ConstructorParameters")?CI(t,e,n[0],o):s.IsEqual(r,"Evaluate")?iI(t,e,n[0],o):s.IsEqual(r,"Exclude")?OI(t,e,n[0],n[1],o):s.IsEqual(r,"Extract")?NI(t,e,n[0],n[1],o):s.IsEqual(r,"Index")?sx(t,e,n[0],n[1],o):s.IsEqual(r,"InstanceType")?ux(t,e,n[0],o):s.IsEqual(r,"Interface")?QS(t,e,n[0],n[1],o):s.IsEqual(r,"KeyOf")?hx(t,e,n[0],o):s.IsEqual(r,"Lowercase")?wI(t,e,n[0],o):s.IsEqual(r,"Mapped")?xx(t,e,n[0],n[1],n[2],n[3],o):s.IsEqual(r,"Module")?Px(t,e,n[0],o):s.IsEqual(r,"NonNullable")?vx(t,e,n[0],o):s.IsEqual(r,"Pick")?Bx(t,e,n[0],n[1],o):s.IsEqual(r,"Options")?Cx(t,e,n[0],n[1]):s.IsEqual(r,"Parameters")?$x(t,e,n[0],o):s.IsEqual(r,"Partial")?Fx(t,e,n[0],o):s.IsEqual(r,"Omit")?Tx(t,e,n[0],n[1],o):s.IsEqual(r,"ReadonlyObject")?zx(t,e,n[0],o):s.IsEqual(r,"Record")?Uk(t,e,n[0],n[1],o):s.IsEqual(r,"Required")?tP(t,e,n[0],o):s.IsEqual(r,"ReturnType")?nP(t,e,n[0],o):s.IsEqual(r,"TemplateLiteral")?gS(t,e,n[0],o):s.IsEqual(r,"Uncapitalize")?vI(t,e,n[0],o):s.IsEqual(r,"Uppercase")?bI(t,e,n[0],o):E(r,n,o)}function P(t,e,r){let n=mi(r),o=Ci(r,ci(r)?"add":"none",We(r)?"add":"none"),i=Qt(o[0])?o[0].Clone():o[0],a=se(i)?Jx(t,e,i,i.$ref):te(i)?lr(P(t,e,i.items),mu(i)):st(i)?mr(P(t,e,i.iteratorItems),tk(i)):Lu(i)?fm(t,e,i.target,i.arguments):Fe(i)?xn(Rt(t,e,i.parameters),P(t,e,i.instanceType),rk(i)):Fr(i)?f_(t,e,i.action,i.parameters,i.options):Ne(i)?Pn(Rt(t,e,i.parameters),P(t,e,i.returnType),nk(i)):D(i)?qt(Rt(t,e,i.allOf),pk(i)):ut(i)?cr(P(t,e,i.iteratorItems),ck(i)):N(i)?O(bi(t,e,i.properties),sk(i)):Ge(i)?dr(P(t,e,i.item),Yy(i)):Me(i)?Kk(_t(i),P(t,e,Xe(i))):mo(i)?Cl(P(t,e,i.items)):V(i)?Ke(Kr(t,e,i.items),Tk(i)):b(i)?B(Rt(t,e,i.anyOf),ak(i)):i,u=n?so(a):a;return m_(o[1],c_(o[2],u))}function nr(t,e){return P(t,{callstack:[]},e)}function iP(t){return Ge(t)?iP(t.item):t}function sP(t,e){return L([t])?g.Update(iP(t),{},e):em(t,e)}function oP(t,e,r,n){let o=P(t,e,r);return sP(o,n)}function em(t,e={}){return E("Awaited",[t],e)}function Qr(t,e={}){return mm(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 hl(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]=du(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 aP(t,e,r){return s.IsArray(r)?r.map(n=>Be(t,e.items,n)):r}function uP(t,e,r){return e.Clean(r)}function pP(t,e,r){return Be({...t,...e.$defs},St(e.$ref),r)}function g_(t,e){let r=s.HasPropertyKey(e,"unevaluatedProperties")?{additionalProperties:e.unevaluatedProperties}:{},n=nr(t,e),o=Qr(n);return N(o)?Rx(o,r):o}function dP(t,e,r){let n=g_(t,e);return Be(t,n,r)}function Bu(t){return s.HasPropertyKey(t,"additionalProperties")?t.additionalProperties:void 0}function lP(t,e,r){if(!s.IsObject(r)||s.IsArray(r))return r;let n=Bu(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)||de(n)&&ae(t,n,r[o])){r[o]=Be(t,n,r[o]);continue}delete r[o]}return r}function mP(t,e,r){if(!s.IsObject(r))return r;let n=Bu(e),[o,i]=[new RegExp(_t(e)),Xe(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)||de(n)&&ae(t,n,r[a])){r[a]=Be(t,n,r[a]);continue}delete r[a]}return r}function cP(t,e,r){return s.HasPropertyKey(t,e.$ref)?Be(t,t[e.$ref],r):r}function fP(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 h_(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 y_(t){return s.IsClassInstance(t)?t:h_(t)}function k_(t){return t.map(e=>ue(e))}function S_(t){return t.slice()}function I_(t){return new Map(ue([...t.entries()]))}function x_(t){return new Set(ue([...t.values()]))}function ue(t){return nt.IsTypeArray(t)?S_(t):nt.IsMap(t)?I_(t):nt.IsSet(t)?x_(t):s.IsArray(t)?k_(t):s.IsObject(t)?y_(t):t}function gP(t,e){return JSON.stringify(t).localeCompare(JSON.stringify(e))}function Ei(t,e=1){return t.sort((r,n)=>{let o=vn(r,n);return(s.IsEqual(o,"disjoint")?gP(r,n):s.IsEqual(o,"right-inside")?1:s.IsEqual(o,"left-inside")?-1:gP(r,n))*e})}function hP(t,e,r){for(let n of Ei(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)?aP(t,e,r):Qt(e)?uP(t,e,r):ge(e)?pP(t,e,r):D(e)?dP(t,e,r):N(e)?lP(t,e,r):Me(e)?mP(t,e,r):se(e)?cP(t,e,r):V(e)?fP(t,e,r):b(e)?hP(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:()=>Sm,Ok:()=>T,TryArray:()=>P_,TryBigInt:()=>Im,TryBoolean:()=>__,TryNull:()=>q_,TryNumber:()=>K_,TryString:()=>j_,TryUndefined:()=>J_});function Sm(t){return s.IsObject(t)&&s.HasPropertyKey(t,"value")}function T(t){return{value:t}}function En(){}function P_(t){return s.IsArray(t)?T(t):T([t])}function w_(t){return s.IsEqual(t,!0)?T(BigInt(1)):T(BigInt(0))}var v_=/^-?(0|[1-9]\d*)n$/,b_=/^-?(0|[1-9]\d*)\.\d+$/,A_=/^-?(0|[1-9]\d*)$/;function T_(t){return v_.test(t)}function R_(t){return b_.test(t)}function C_(t){return A_.test(t)}function E_(t){let e=t.toLowerCase();return T_(t)?T(BigInt(t.slice(0,t.length-1))):R_(t)?T(BigInt(t.split(".")[0])):C_(t)?T(BigInt(t)):s.IsEqual(e,"false")?T(BigInt(0)):s.IsEqual(e,"true")?T(BigInt(1)):void 0}function Im(t){return s.IsBigInt(t)?T(t):s.IsBoolean(t)?w_(t):s.IsNumber(t)?T(BigInt(Math.trunc(t))):s.IsNull(t)?T(BigInt(0)):s.IsString(t)?E_(t):s.IsUndefined(t)?T(BigInt(0)):void 0}function $_(t){return s.IsEqual(t,BigInt(0))?T(!1):s.IsEqual(t,BigInt(1))?T(!0):void 0}function M_(t){return s.IsEqual(t,0)?T(!1):s.IsEqual(t,1)?T(!0):void 0}function O_(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 __(t){return s.IsBigInt(t)?$_(t):s.IsBoolean(t)?T(t):s.IsNumber(t)?M_(t):s.IsNull(t)?T(!1):s.IsString(t)?O_(t):s.IsUndefined(t)?T(!1):void 0}function D_(t){return s.IsEqual(t,BigInt(0))?T(null):void 0}function L_(t){return s.IsEqual(t,!1)?T(null):void 0}function F_(t){return s.IsEqual(t,0)?T(null):void 0}function N_(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 q_(t){return s.IsBigInt(t)?D_(t):s.IsBoolean(t)?L_(t):s.IsNumber(t)?F_(t):s.IsNull(t)?T(null):s.IsString(t)?N_(t):s.IsUndefined(t)?T(null):void 0}var yP=BigInt(Number.MAX_SAFE_INTEGER),kP=BigInt(Number.MIN_SAFE_INTEGER);function B_(t){return t<=yP&&t>=kP?T(Number(t)):void 0}function U_(t){return T(t?1:0)}function W_(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=Im(t);return Sm(n)?n.value<=yP&&n.value>=kP?T(Number(n.value)):void 0:void 0}function K_(t){return s.IsBigInt(t)?B_(t):s.IsBoolean(t)?U_(t):s.IsNumber(t)?T(t):s.IsNull(t)?T(0):s.IsString(t)?W_(t):s.IsUndefined(t)?T(0):void 0}function j_(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 G_(t){return s.IsEqual(t,BigInt(0))?T(void 0):void 0}function V_(t){return s.IsEqual(t,!1)?T(void 0):void 0}function H_(t){return s.IsEqual(t,0)?T(void 0):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(void 0):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(void 0):s.IsString(t)?z_(t):s.IsUndefined(t)?T(t):void 0}function SP(t,e,r){return Q.TryArray(r).value.map(o=>Te(t,e.items,o))}function IP(t,e,r){return e.Convert(r)}function xP(t,e,r){let n=Q.TryBigInt(r);return Q.IsOk(n)?n.value:r}function PP(t,e,r){let n=Q.TryBoolean(r);return Q.IsOk(n)?n.value:r}function wP(t,e,r){return Te({...t,...e.$defs},St(e.$ref),r)}function Uu(t,e,r){if(e.anyOf.some(a=>ae(t,a,r)))return r;let i=e.anyOf.map(a=>Te(t,a,ue(r))).find(a=>ae(t,e,a));return s.IsUndefined(i)?r:i}function vP(t,e,r){let n=po(e);return Uu(t,n,r)}function bP(t,e,r){let n=Q.TryNumber(r);return Q.IsOk(n)?Math.trunc(n.value):r}function AP(t,e,r){let n=nr(t,e),o=Qr(n);return Te(t,o,r)}function Q_(t,e,r){let n=Q.TryBigInt(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function Y_(t,e,r){let n=Q.TryBoolean(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function Z_(t,e,r){let n=Q.TryNumber(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function X_(t,e,r){let n=Q.TryString(r);return Q.IsOk(n)&&s.IsEqual(e.const,n.value)?n.value:r}function TP(t,e,r){return s.IsEqual(e.const,r)?r:fk(e)?Q_(t,e,r):gk(e)?Y_(t,e,r):ku(e)?Z_(t,e,r):Su(e)?X_(t,e,r):Y()}function RP(t,e,r){let n=Q.TryNull(r);return Q.IsOk(n)?n.value:r}function CP(t,e,r){let n=Q.TryNumber(r);return Q.IsOk(n)?n.value:r}function Wu(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]=Te(t,r,n[u]));return n}function $i(t,e,r){return We(t)&&s.IsUndefined(r[e])}function e0(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)||$i(a,u,r)||(r[u]=Te(t,a,r[u]));return s.HasPropertyKey(e,"additionalProperties")&&s.IsObject(e.additionalProperties)?Wu(t,n,e.additionalProperties,r):r}function EP(t,e,r){return s.IsObjectNotArray(r)?e0(t,e,r):r}function t0(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]=Te(t,a,r[u]));return s.HasPropertyKey(e,"additionalProperties")&&s.IsObject(e.additionalProperties)?Wu(t,n,e.additionalProperties,r):r}function $P(t,e,r){return s.IsObjectNotArray(r)?t0(t,e,r):r}function MP(t,e,r){return s.HasPropertyKey(t,e.$ref)?Te(t,t[e.$ref],r):r}function OP(t,e,r){let n=Q.TryString(r);return Q.IsOk(n)?n.value:r}function _P(t,e,r){let n=He(e.pattern);return Te(t,n,r)}function DP(t,e,r){if(!s.IsArray(r))return r;for(let n=0;n<Math.min(e.items.length,r.length);n++)r[n]=Te(t,e.items[n],r[n]);return r}function LP(t,e,r){let n=Q.TryUndefined(r);return Q.IsOk(n)?n.value:r}function FP(t,e,r){let n=Q.TryUndefined(r);return Q.IsOk(n)?void 0:r}function Te(t,e,r){return te(e)?SP(t,e,r):Qt(e)?IP(t,e,r):Bt(e)?xP(t,e,r):At(e)?PP(t,e,r):ge(e)?wP(t,e,r):qe(e)?vP(t,e,r):at(e)?bP(t,e,r):D(e)?AP(t,e,r):G(e)?TP(t,e,r):wn(e)?RP(t,e,r):be(e)?CP(t,e,r):N(e)?EP(t,e,r):Me(e)?$P(t,e,r):se(e)?MP(t,e,r):Ze(e)?OP(t,e,r):Ae(e)?_P(t,e,r):V(e)?DP(t,e,r):Tn(e)?LP(t,e,r):b(e)?Uu(t,e,r):Kt(e)?FP(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 Te(e,r,n)}function NP(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 qP(t,e,r){return e.Default(r)}function BP(t,e,r){return _e({...t,...e.$defs},St(e.$ref),r)}function UP(t,e){return s.IsUndefined(e)?s.IsFunction(t.default)?t.default():ue(t.default):e}function WP(t,e,r){let n=nr(t,e),o=Qr(n);return _e(t,o,r)}function KP(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)&&(We(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 jP(t,e,r){if(!s.IsObject(r))return r;let[n,o]=[new RegExp(_t(e)),Xe(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 GP(t,e,r){return s.HasPropertyKey(t,e.$ref)?_e(t,t[e.$ref],r):r}function VP(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 HP(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)?UP(e,r):r;return te(e)?NP(t,e,n):Qt(e)?qP(t,e,n):ge(e)?BP(t,e,n):D(e)?WP(t,e,n):N(e)?KP(t,e,n):Me(e)?jP(t,e,n):se(e)?GP(t,e,n):V(e)?VP(t,e,n):b(e)?HP(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 xo(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 r0(t,e,r){return e["~codec"].decode(r)}function n0(t,e,r){return e["~codec"].encode(r)}function fe(t,e,r,n){return Il(r)?s.IsEqual(t,"Decode")?r0(e,r,n):n0(e,r,n):n}function o0(t,e,r,n){if(!s.IsArray(n))return Y();for(let o=0;o<n.length;o++)n[o]=he(t,e,r.items,n[o]);return fe(t,e,r,n)}function i0(t,e,r,n){let o=fe(t,e,r,n);if(!s.IsArray(o))return o;for(let i=0;i<o.length;i++)o[i]=he(t,e,r.items,o[i]);return o}function zP(t,e,r,n){return s.IsEqual(t,"Decode")?o0(t,e,r,n):i0(t,e,r,n)}function JP(t,e,r,n){return n=he(t,{...e,...r.$defs},St(r.$ref),n),fe(t,e,r,n)}function QP(t){return t.reduce((e,r)=>({...e,...r}),{})}function YP(t,e){for(let r of e)if(!s.IsDeepEqual(t,r))return r;return t}function s0(t,e,r,n){if(s.IsEqual(r.allOf.length,0))return fe(t,e,r,n);let o=r.allOf.map(u=>he(t,e,u,Ht(u,ue(n)))),a=o.every(u=>s.IsObject(u))?QP(o):YP(n,o);return fe(t,e,r,a)}function a0(t,e,r,n){if(s.IsEqual(r.allOf.length,0))return fe(t,e,r,n);let o=fe(t,e,r,n),i=r.allOf.map(u=>he(t,e,u,Ht(u,ue(o))));return i.every(u=>s.IsObject(u))?QP(i):YP(o,i)}function ZP(t,e,r,n){return s.IsEqual(t,"Decode")?s0(t,e,r,n):a0(t,e,r,n)}function u0(t,e,r,n){if(!s.IsObjectNotArray(n))return Y();for(let o of s.Keys(r.properties))!s.HasPropertyKey(n,o)||$i(r.properties[o],o,n)||(n[o]=he(t,e,r.properties[o],n[o]));return fe(t,e,r,n)}function p0(t,e,r,n){let o=fe(t,e,r,n);if(!s.IsObjectNotArray(o))return o;for(let i of s.Keys(r.properties))!s.HasPropertyKey(o,i)||$i(r.properties[i],i,o)||(o[i]=he(t,e,r.properties[i],o[i]));return o}function XP(t,e,r,n){return s.IsEqual(t,"Decode")?u0(t,e,r,n):p0(t,e,r,n)}function d0(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]=he(t,e,Xe(r),n[i]);return fe(t,e,r,n)}function l0(t,e,r,n){let o=fe(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]=he(t,e,Xe(r),o[a]));return o}function ew(t,e,r,n){return s.IsEqual(t,"Decode")?d0(t,e,r,n):l0(t,e,r,n)}function tw(t,e,r,n){return s.HasPropertyKey(e,r.$ref)?he(t,e,e[r.$ref],n):n}function rw(t,e,r,n){return s.IsEqual(t,"Decode")?fe(t,e,r,tw(t,e,r,n)):tw(t,e,r,fe(t,e,r,n))}function m0(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]=he(t,e,r.items[o],n[o]);return fe(t,e,r,n)}function c0(t,e,r,n){let o=fe(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]=he(t,e,r.items[i],o[i]);return o}function nw(t,e,r,n){return s.IsEqual(t,"Decode")?m0(t,e,r,n):c0(t,e,r,n)}function f0(t,e,r,n){for(let o of Ei(r.anyOf,1)){if(!ae(e,o,n))continue;let i=he(t,e,o,n);return fe(t,e,r,i)}return n}function g0(t,e,r,n){let o=fe(t,e,r,n);for(let i of Ei(r.anyOf,-1)){let a=he(t,e,i,ue(o));if(ae(e,i,a))return a}return o}function ow(t,e,r,n){return s.IsEqual(t,"Decode")?f0(t,e,r,n):g0(t,e,r,n)}function he(t,e,r,n){return te(r)?zP(t,e,r,n):ge(r)?JP(t,e,r,n):D(r)?ZP(t,e,r,n):N(r)?XP(t,e,r,n):Me(r)?ew(t,e,r,n):se(r)?rw(t,e,r,n):V(r)?nw(t,e,r,n):b(r)?ow(t,e,r,n):fe(t,e,r,n)}var xm=class extends Yr{constructor(e,r){super("Decode",e,r)}};function h0(t,e,r){if(!ae(t,e,r))throw new xm(r,gr(t,e,r));return r}function y0(t,e,r){return he("Decode",t,e,r)}var gCe=xo([(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)=>h0(t,e,r),(t,e,r)=>y0(t,e,r)]);var Pm=class extends Yr{constructor(e,r){super("Encode",e,r)}};function k0(t,e,r){if(!ae(t,e,r))throw new Pm(r,gr(t,e,r));return r}function S0(t,e,r){return he("Encode",t,e,r)}var TCe=xo([(t,e,r)=>ue(r),(t,e,r)=>S0(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)=>k0(t,e,r)]);var ju=class extends Yr{constructor(e,r){super("Parse",e,r)}};function I0(t,e,r){if(!ae(t,e,r))throw new ju(r,gr(t,e,r));return r}var x0=xo([(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)=>I0(t,e,r)]);var w0=O({type:Z("insert"),path:Tt(),value:Yt()}),v0=Object({type:Z("update"),path:Tt(),value:Yt()}),b0=O({type:Z("delete"),path:Tt()}),dOe=B([w0,v0,b0]);var RDe=new Bg(512);function pw(t){return{success:!1,error:{issues:[{path:[],message:t}]}}}function wm(){return{safeParse(t){return t===void 0?{success:!0,data:void 0}:!t||typeof t!="object"||Array.isArray(t)?pw("expected config object"):Object.keys(t).length>0?pw("config must be empty"):{success:!0,data:t}},jsonSchema:{type:"object",additionalProperties:!1,properties:{}}}}function _0(t,e){let r=!1,n;return()=>(r||(n=(typeof t=="function"?t():t)??e,r=!0),n)}function Gu({id:t,name:e,description:r,kind:n,configSchema:o=wm,reload:i,nodeHostCommands:a,securityAuditCollectors:u,register:p}){let d=_0(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 q0(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=N0("git",["rev-parse","--show-toplevel"],{cwd:p.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();d&&i.add(dw(d,".worktrees"))}catch{}if(i.size===0)return;let u=0;for(let p of i)try{let d=D0(p);for(let l of d){if(!l.startsWith("openclaw-worktree-"))continue;let m=dw(p,l);try{let c=L0(m);if(!c.isDirectory()||c.mtimeMs>n||o.has(m))continue;F0(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 B0(t){let e=null,r=null,n=!1,o=!1,i=t.registerTool;Nn(t.runtime);let a=m=>{if(n){m&&!o&&(Nn(t.runtime,m.config),o=!0);return}let c=t.pluginConfig??{};Cm(c),m?(Nn(t.runtime,m.config),o=!0):(Nn(t.runtime),o=!1),e=new Ra(K.maxSessions,K.maxPersistedSessions,{worktreeSummaryProvider:ig()}),r=new Hs(e),Hu(e),zu(r),r.start(),q0(e),e.bootstrapMaintenanceSchedules(),n=!0},u=()=>{r&&r.stop(),e&&e.killAll("shutdown"),e&&e.dispose(),r=null,e=null,n=!1,o=!1,Nn(void 0),zu(null),Hu(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=wf(m);t.registerInteractiveHandler({...c,handler:async h=>(a(),c.handler(h))})};p(m=>fc(m),{optional:!1,name:"agent_launch"}),p(m=>Uc(m),{optional:!1,name:"agent_sessions"}),p(m=>Wc(m),{optional:!1,name:"agent_kill"}),p(m=>As(m),{optional:!1,name:"agent_output"}),p(m=>zc(m),{optional:!1,name:"agent_respond"}),p(m=>Jc(m),{optional:!1,name:"agent_request_plan_approval"}),p(m=>Yc(m),{optional:!1,name:"agent_send_plan_offer"}),p(m=>Zc(m),{optional:!1,name:"agent_stats"}),p(m=>_s(m),{optional:!1,name:"agent_merge"}),p(m=>Vo(m),{optional:!1,name:"agent_pr"}),p(m=>lf(m),{optional:!1,name:"agent_worktree_cleanup"}),p(m=>mf(m),{optional:!1,name:"agent_worktree_status"}),p(m=>cf(m),{optional:!1,name:"goal_launch"}),p(m=>gf(m),{optional:!1,name:"goal_status"}),p(m=>hf(m),{optional:!1,name:"goal_stop"}),l("telegram"),l("discord"),bf(d),Af(d),Tf(d),Rf(d),Cf(d),Ef(d),Mf(d),Of(d),_f(d),t.registerService({id:"openclaw-code-agent",start:a,stop:u})}var vLe=Gu({id:"openclaw-code-agent",name:"OpenClaw Code Agent",description:"Multi-session coding-agent orchestration from OpenClaw chat",register:B0});export{vLe as default,B0 as register};