@wular/coder 0.2.12 → 0.3.0

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/cli.js CHANGED
@@ -1,170 +1,66 @@
1
1
  #!/usr/bin/env node
2
- var F8=Object.defineProperty;var R8=(Q,Y)=>{for(var X in Y)F8(Q,X,{get:Y[X],enumerable:!0,configurable:!0,set:(W)=>Y[X]=()=>W})};import e from"node:process";import $2 from"node:fs";import k8 from"node:path";import{spawn as j8}from"node:child_process";import m0 from"node:process";import{execFileSync as x4}from"node:child_process";import k from"node:fs";import T8 from"node:os";import x from"node:path";import{spawn as _4,spawnSync as E8}from"node:child_process";import M8 from"node:fs";import _8 from"node:os";import M4 from"node:path";function T4(Q){try{let Y=_4("codex",["archive",Q],{detached:!0,stdio:"ignore"});Y.on("error",()=>{}),Y.unref()}catch{}}function I4(Q){let Y=M4.join(process.env.CODEX_HOME||M4.join(_8.homedir(),".codex"),"archived_sessions");try{return M8.readdirSync(Y).some((X)=>X.endsWith(`-${Q}.jsonl`))}catch{return!1}}function w4(Q){return new Promise((Y)=>{try{let X=_4("codex",["unarchive",Q],{stdio:"ignore"});X.on("error",()=>Y(!1)),X.on("close",(W)=>Y(W===0))}catch{Y(!1)}})}function S4(Q){return E8("codex",["delete","--force",Q],{encoding:"utf8"}).status===0}var Z0=["completed","failed","cancelled"],J0=["queued","running"];var I8="CODER_HOME";function M0(){return x.resolve(process.env[I8]||x.join(T8.homedir(),".coder"))}var C4=new Map;function Y0(Q){let Y=C4.get(Q);if(Y!==void 0)return Y;let X;try{X=x4("git",["rev-parse","--show-toplevel"],{cwd:Q,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{X=Q}return C4.set(Q,X),X}var k4="global";function K2(Q){return x.join(M0(),"state",k4)}var S2=null;function U3(){if(S2)return S2;let Q=x.join(M0(),"state"),Y=[];try{Y=k.readdirSync(Q,{withFileTypes:!0})}catch{}return S2=Y.filter((X)=>X.isDirectory()&&X.name!==k4).map((X)=>x.join(Q,X.name)),S2}function L3(Q){return x.join(K2(Q),"jobs")}function C2(Q){return x.join(K2(Q),"archive")}function C(Q,Y){let X=x.join(L3(Q),Y);if(k.existsSync(x.join(X,"job.json")))return X;let W=x.join(C2(Q),Y);if(k.existsSync(x.join(W,"job.json")))return W;for(let q of U3()){let K=x.join(q,"jobs",Y);if(k.existsSync(x.join(K,"job.json")))return K}return X}function P3(Q,Y){return Y.archived?Y:m(Q,Y.id,{archived:!0,archivedAt:new Date().toISOString()})}function h0(Q,Y){let X=P3(Q,Y);if(Y.engine==="codex"&&Y.threadId)T4(Y.threadId);let W=C(Q,Y.id),q=x.join(C2(Q),Y.id);if(W!==q)try{k.mkdirSync(C2(Q),{recursive:!0}),k.renameSync(W,q)}catch{}return X}function j4(){let Q=Math.random().toString(36).slice(2,8);return`coder-${Date.now().toString(36)}-${Q}`}function m(Q,Y,X){let W=C(Q,Y);k.mkdirSync(W,{recursive:!0});let q=x.join(W,"job.json"),G={...r(Q,Y)??{id:Y,createdAt:new Date().toISOString(),status:"queued"},...X,updatedAt:new Date().toISOString()};return k.writeFileSync(q,`${JSON.stringify(G,null,2)}
3
- `,"utf8"),G}function v4(Q){if(!Q.engine&&(Q.agent==="codex"||Q.agent==="claude"))Q.engine=Q.agent;return Q}function r(Q,Y){let X=x.join(C(Q,Y),"job.json");if(!k.existsSync(X))return null;try{return v4(JSON.parse(k.readFileSync(X,"utf8")))}catch{return null}}function O3(Q,Y){let X=C(Q,Y);if(!k.existsSync(X))return!1;return k.rmSync(X,{recursive:!0,force:!0}),!0}function w8(Q){if(!Q)return!1;try{return process.kill(Q,0),!0}catch(Y){return Y.code==="EPERM"}}function S8(Q){try{let Y=x4("ps",["-o","lstart=","-p",String(Q)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),X=Y?Date.parse(Y):NaN;return Number.isFinite(X)?X:null}catch{return null}}function C8(Q,Y){if(!w8(Q))return!1;let X=S8(Q),W=Date.parse(Y.createdAt??"");if(X===null||!Number.isFinite(W))return!0;return X<=W+60000}var x8=60000;function b0(Q,Y){if(Y.status!=="running"&&Y.status!=="queued")return Y;let X;if(Y.pid)X=!C8(Y.pid,Y);else{let W=Date.parse(Y.updatedAt??Y.createdAt??"");X=Number.isFinite(W)&&Date.now()-W>x8}if(X)return m(Q,Y.id,{status:"failed",error:"worker exited without finishing",completedAt:new Date().toISOString()});return Y}function V3(Q,Y){let X=[];for(let W of Q){let q=[];try{q=k.readdirSync(W)}catch{continue}for(let K of q){if(Y.has(K))continue;let G=x.join(W,K,"job.json");try{let z=v4(JSON.parse(k.readFileSync(G,"utf8")));Y.add(K),X.push(z)}catch{}}}return X}var Z3=(Q,Y)=>String(Y.updatedAt??"").localeCompare(String(Q.updatedAt??""));function z2(Q){let Y=[L3(Q),...U3().map((W)=>x.join(W,"jobs"))],X=[];for(let W of V3(Y,new Set))if(W.archived)h0(Q,W);else X.push(b0(Q,W));return X.sort(Z3)}function g0(Q,Y){let X=Y?.migrate??!0,W=new Set,q=V3([C2(Q)],W),K=[L3(Q),...U3().map((G)=>x.join(G,"jobs"))];for(let G of V3(K,W))if(G.archived)q.push(X?h0(Q,G):G);return q.sort(Z3)}function y0(Q,Y){let X=[...z2(Q),...g0(Q)].sort(Z3);if(!Y)return X[0]??null;let W=X.find((K)=>K.id===Y);if(W)return W;let q=X.filter((K)=>K.id.startsWith(Y));if(q.length===1)return q[0];if(q.length>1)throw Error(`Job reference "${Y}" is ambiguous. Use a longer id.`);return null}function h4(Q,Y){let X=C(Q,Y);try{k.mkdirSync(X,{recursive:!0}),k.writeFileSync(x.join(X,"heartbeat"),"","utf8")}catch{}}function x2(Q,Y){let X=C(Q,Y.id),W=Date.parse(Y.updatedAt??"")||0;for(let q of["log.jsonl","heartbeat"])try{W=Math.max(W,k.statSync(x.join(X,q)).mtimeMs)}catch{}return W?new Date(W).toISOString():void 0}async function b4(Q,Y,X=400){let W=Y;while(!Z0.includes(W.status))await new Promise((q)=>setTimeout(q,X)),W=b0(Q,r(Q,W.id)??W);return W}var g4="steer-queue.jsonl";function y4(Q,Y,X){let W=C(Q,Y);k.mkdirSync(W,{recursive:!0}),k.appendFileSync(x.join(W,g4),`${JSON.stringify({at:new Date().toISOString(),text:X})}
4
- `,"utf8")}function m4(Q,Y){let X=C(Q,Y),W=x.join(X,g4),q=x.join(X,`steer-claim-${process.pid}-${Date.now()}.tmp`);try{k.renameSync(W,q)}catch{return[]}try{return k.readFileSync(q,"utf8").split(/\r?\n/).filter(Boolean).map((K)=>{try{return String(JSON.parse(K).text??"")}catch{return""}}).filter(Boolean)}finally{try{k.unlinkSync(q)}catch{}}}function V0(Q,Y,X){let W=C(Q,Y);k.mkdirSync(W,{recursive:!0}),k.appendFileSync(x.join(W,"log.jsonl"),`${JSON.stringify({at:new Date().toISOString(),...X})}
5
- `,"utf8")}function H0(Q,Y,X=40){let W=x.join(C(Q,Y),"log.jsonl");if(!k.existsSync(W))return[];return k.readFileSync(W,"utf8").split(/\r?\n/).filter(Boolean).slice(-X).map((K)=>{try{return JSON.parse(K)}catch{return{message:K}}})}var G2="@wular/coder",v8=`https://registry.npmjs.org/${G2}/latest`,h8=86400000;function A3(){return k8.join(M0(),"update-check.json")}function D3(Q,Y){let X=String(Q).split(".").map((q)=>parseInt(q,10)||0),W=String(Y).split(".").map((q)=>parseInt(q,10)||0);for(let q=0;q<3;q+=1){if((X[q]??0)>(W[q]??0))return 1;if((X[q]??0)<(W[q]??0))return-1}return 0}function u4(){try{return JSON.parse($2.readFileSync(A3(),"utf8"))}catch{return null}}function b8(Q){try{$2.mkdirSync(M0(),{recursive:!0}),$2.writeFileSync(A3(),JSON.stringify(Q))}catch{}}function c4(){try{$2.rmSync(A3(),{force:!0})}catch{}}function f4(Q,Y){if(m0.env.CODER_NO_UPDATE_CHECK||m0.env.CI)return;let X=u4();if(X?.latest&&D3(X.latest,Q)>0){let q=m0.stderr.isTTY&&!m0.env.NO_COLOR,K=(z)=>q?`\x1B[38;5;245m${z}\x1B[0m`:z,G=(z)=>q?`\x1B[1m${z}\x1B[0m`:z;m0.stderr.write(K(`coder ${Q} -> `)+G(X.latest)+K(` available. run: coder upgrade
6
-
7
- `))}if(!X?.checkedAt||Date.now()-X.checkedAt>h8)try{j8(m0.execPath,[Y,"_refreshUpdate"],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function p4(Q){let X=u4()?.latest??null;try{let W=new AbortController,q=setTimeout(()=>W.abort(),3000),K=await fetch(v8,{signal:W.signal,headers:{accept:"application/json"}});if(clearTimeout(q),K.ok){let G=await K.json();if(G?.version)X=G.version}}catch{}b8({checkedAt:Date.now(),latest:X,current:Q})}function l4(Q){let Y=Q;try{Y=$2.realpathSync(Q)}catch{}let X=Y.replace(/\\/g,"/");if(/\/\.bun\//.test(X))return{pm:"bun",command:["bun","add","-g",`${G2}@latest`]};if(/\/\.pnpm\//.test(X)||/\/pnpm(-global)?\//i.test(X)||/\/Library\/pnpm\//.test(X))return{pm:"pnpm",command:["pnpm","add","-g",`${G2}@latest`]};if(/\/\.config\/yarn\/global\//.test(X)||/\/yarn\/global\//.test(X)||/\/Yarn\/Data\/global\//.test(X))return{pm:"yarn",command:["yarn","global","add",`${G2}@latest`]};return{pm:"npm",command:["npm","install","-g",`${G2}@latest`]}}import F3 from"node:fs";import{fileURLToPath as R3}from"node:url";var A0=R3(import.meta.url);function a(){try{return JSON.parse(F3.readFileSync(R3(new URL("../package.json",import.meta.url)),"utf8")).version??"unknown"}catch{return"unknown"}}function E3(Q){try{return JSON.parse(F3.readFileSync(Q,"utf8")).version??null}catch{return null}}function k2(){return R3(new URL("..",import.meta.url))}import g8 from"node:path";import G0 from"node:process";function d4(Q){let Y=Q.isTTY&&!G0.env.NO_COLOR,X=(W,q)=>Y?`\x1B[${W}m${q}\x1B[0m`:q;return{blue:(W)=>X("34",W),bold:(W)=>X("1",W),cyan:(W)=>X("36",W),dim:(W)=>X("38;5;245",W),green:(W)=>X("32",W),red:(W)=>X("31",W)}}var O=d4(G0.stdout),M3=d4(G0.stderr);function _0(Q,Y=M3){let X=Q.map((q)=>{let K=q.indexOf("coder ");return K===-1?{label:q,cmd:""}:{label:q.slice(0,K),cmd:q.slice(K)}}),W=Math.max(0,...X.map((q)=>q.label.length));return X.map(({label:q,cmd:K})=>K?` ${Y.dim(q.padEnd(W))}${Y.bold(K)}`:` ${Y.dim(q)}`).join(`
8
- `)}function D(Q,Y={}){let X=typeof Y==="number"?Y:Y.code??1,W=typeof Y==="object"?Y.hint:null,q=W==null?[]:Array.isArray(W)?W:[W];if(G0.stderr.write(`${Q}
9
- `),q.length)G0.stderr.write(`
10
- ${_0(q,M3)}
11
- `);G0.exit(X)}function E(Q){G0.stdout.write(`${JSON.stringify(Q,null,2)}
12
- `)}function B2(Q){let Y=Date.parse(Q??"");return Number.isFinite(Y)?Math.max(0,Date.now()-Y):0}function H2(Q){let Y=Math.floor(Q/1000);if(Y<60)return`${Y}s`;let X=Math.floor(Y/60);if(X<60)return`${X}m`;return`${Math.floor(X/60)}h${X%60}m`}function j2(Q){if(Q<1000)return String(Q);if(Q<1e6)return`${(Q/1000).toFixed(Q<1e4?1:0)}k`;return`${(Q/1e6).toFixed(1)}M`}function u0(Q,Y){let X=[`in ${j2(Q.input)}`,...Q.cachedInput?[`cached ${j2(Q.cachedInput)}`]:[],`out ${j2(Q.output)}`];return`${j2(Q.total)} (${X.join(" · ")}) on ${Y||"default model"}`}function v2(Q,Y,X,W=O){let q=Q?.error?.message??Y;return Q?.finalMessage||(q?`${W.red("error:")} ${q}`:X)}var r4=500;function h2(Q,Y=O){let X=Q.length>r4?`${Q.slice(0,r4)}…`:Q;return[Y.dim("prompt:"),...X.split(`
13
- `).map((W)=>` ${Y.dim(W)}`)]}var _3=128;function c0(Q,Y=_3,{plain:X=!1,style:W=O}={}){if(Q.length<=Y)return Q;let q=`<${Q.length-Y} more chars>`;return`${Q.slice(0,Y)} ${X?q:W.dim(q)}`}var b2=600000,n4=120000;function g2(Q,Y=0){let X=Q.padEnd(Y);if(Q==="running")return O.green(X);if(Q==="failed"||Q==="cancelled")return O.red(X);if(Q==="completed")return O.blue(X);return O.dim(X)}var y8=4;function y2(Q,Y,X=!1){if(X)E({taskId:Q,status:"awaiting-approval",approval:Y});else G0.stdout.write(`Approval needed for task ${Q}: ${Y.summary}
14
- `),G0.stderr.write(`
15
- ${_0([`Approve: coder approve ${Q} ${Y.id}`,`Deny: coder approve ${Q} ${Y.id} --deny`,`Then: coder task result ${Q} --wait`],M3)}
16
- `);G0.exit(y8)}function f(Q,Y,X){if(Q.length>Y){let W=Q.slice(Y);D(`Unexpected argument${W.length>1?"s":""}: ${W.join(" ")}`,{hint:`Help: coder ${X} --help`})}}function I(Q){return Q.cwd?g8.resolve(String(Q.cwd)):G0.cwd()}function p(Q,Y){let X=y0(Q,Y);if(!X)D(Y?`No task found for "${Y}".`:"No tasks found for this workspace.",{hint:Y?["List tasks: coder task list",'Start one: coder run "<text>"']:['Start one: coder run "<text>"']});return X}var m8=[["--wait","run in the foreground and block until the answer is ready"],["--agent <codex|claude|custom>","engine to use; custom runs your configured custom models (default: first in the chain)"],["--model <alias|slug>","spark/luna/terra/sol (codex) · opus/sonnet/fable (claude) · a custom model (coder model list)"],["--effort <low|medium|high>","reasoning effort"],["--permissions <mode>","read-only · workspace-write · auto (default: auto)"],["--resume <task-id>","continue that task's thread instead of a fresh run"],["--json","machine-readable JSON output"]],W0=["--cwd <dir>","workspace directory (default: current)"],X0=["--json","JSON output"],T3=[{sub:"run",usage:'run "<text>"',blurb:"run a task (background; --wait blocks)",alias:"run"},{sub:"list",usage:"list",blurb:"list recent tasks (running + just stopped)",alias:"list"},{sub:"result",usage:"result [task-id]",blurb:"status + final answer (--wait blocks)",alias:"result"},{sub:"stream",usage:"stream [task-id]",blurb:"watch a task live (progress log)",alias:"stream"},{sub:"steer",usage:'steer <task-id> "<follow-up>"',blurb:"continue a task's thread"},{sub:"stop",usage:"stop <task-id>",blurb:"interrupt a running task"},{sub:"archive",usage:"archive <task-id>",blurb:"archive a session (or --all-stopped)"},{sub:"delete",usage:"delete <task-id>",blurb:"delete a session (or --all-archived)"},{sub:"approvals",usage:"approvals <task-id>",blurb:"list escalated approvals"},{sub:"approve",usage:"approve <task-id> <id>",blurb:"answer an escalated permission"}],f0={"task run":{list:['task run "<text>"',"run a coding task (background; --wait blocks)"],usage:'coder task run "<task text>"',summary:'Dispatch a coding task to the configured engine. Backgrounds by default and\nprints a task id; --wait runs in the foreground and prints the answer.\nShortcut: `coder run "<text>"`.',flags:[["--name <name>","label the task (shown in list/result)"],["--system <text>","standing instructions prepended to the task (kept out of prompt previews)"],...m8,W0],examples:[['coder run "add a /health endpoint"',"dispatch in the background, print a task id"],['coder run --wait "fix the failing test"',"block until done, print the answer"],[`coder task run --model spark --system "tests live in test/, don't touch anything outside of it" "rename foo to bar"`,"pick an engine via its model alias; --system adds standing instructions"]],seeAlso:"task result · task steer · task stop · task stream"},"task list":{list:["task list [--running|--stopped|--archived]","list recent tasks (running + just stopped)"],usage:"coder task list [--running] [--stopped] [--archived [--limit N]]",summary:"List recent tasks across all workspaces, most recent first: running tasks plus\nones stopped within the last 2 minutes. Older stopped tasks auto-archive and\nmove to --archived. Shortcut: `coder list`.",flags:[["--running","show only running tasks"],["--stopped","show only recently stopped tasks (not yet archived)"],["--archived","show only archived tasks (auto-archived or via task archive)"],["--limit <n|all>","show at most n tasks (default all)"],["--dir <dir>","only tasks launched in that workspace"],X0],seeAlso:"task result · task archive · task delete"},"task result":{list:["task result [task-id]","status + final answer of a task"],usage:"coder task result [task-id]",summary:`Show a task's status and its final answer (result pending while it runs), plus
2
+ import{B as e,E as t,F as n,M as r,V as i,c as a,d as o,f as s,l as c,m as l,o as u,s as d,u as f}from"./app-server-Dwd7IcQH.js";import{$t as p,A as m,Bt as h,D as g,Ft as _,Gt as ee,Ht as v,It as y,Jt as b,Kt as x,Lt as te,M as S,Nt as ne,O as C,Ot as w,Qt as T,R as re,Rt as E,S as D,T as O,Ut as ie,Vt as ae,Xt as oe,Yt as k,Zt as A,_ as se,a as ce,b as le,d as ue,en as de,g as j,h as fe,j as pe,jt as me,kt as he,l as M,n as ge,nn as _e,p as ve,qt as N,r as ye,rn as be,s as xe,t as Se,tn as Ce,u as we,v as P,vt as Te,w as Ee,x as De,xt as Oe,y as ke,yt as Ae,zt as je}from"./runtime-BitZWgom.js";import{D as Me,E as Ne,S as Pe,a as Fe,h as Ie,p as F,r as Le,t as Re,v as ze,w as I,x as Be}from"./upgrade-glYqFjxk.js";import L from"node:process";import R from"node:fs";import z from"node:path";import{spawn as Ve,spawnSync as He}from"node:child_process";import Ue from"node:os";import*as B from"zod/mini";const We=[[`--wait`,`run in the foreground and block until the answer is ready`],[`--agent <codex|claude|custom>`,`engine to use; custom runs your configured custom models (default: first in the chain)`],[`--model <alias|slug>`,`spark/luna/terra/sol (codex) · opus/sonnet/fable (claude) · a custom model (coder model list)`],[`--effort <low|medium|high>`,`reasoning effort`],[`--permissions <mode>`,`read-only · workspace-write · auto (default: auto)`],[`--resume <task-id>`,`continue that task's thread instead of a fresh run`],[`--json`,`machine-readable JSON output`]],V=[`--cwd <dir>`,`workspace directory (default: current)`],H=[`--json`,`JSON output`],Ge=[{sub:`run`,usage:`run "<text>"`,blurb:`run a task (background; --wait blocks)`,alias:`run`},{sub:`list`,usage:`list`,blurb:`list recent tasks (running + just stopped)`,alias:`list`},{sub:`result`,usage:`result [task-id]`,blurb:`status + final answer (--wait blocks)`,alias:`result`},{sub:`stream`,usage:`stream [task-id]`,blurb:`watch a task live (progress log)`,alias:`stream`},{sub:`steer`,usage:`steer <task-id> "<follow-up>"`,blurb:`continue a task's thread`},{sub:`stop`,usage:`stop <task-id>`,blurb:`interrupt a running task`},{sub:`archive`,usage:`archive <task-id>`,blurb:`archive a session (or --all-stopped)`},{sub:`delete`,usage:`delete <task-id>`,blurb:`delete a session (or --all-archived)`},{sub:`approvals`,usage:`approvals <task-id>`,blurb:`list escalated approvals`},{sub:`approve`,usage:`approve <task-id> <id>`,blurb:`answer an escalated permission`}],U={"task run":{list:[`task run "<text>"`,`run a coding task (background; --wait blocks)`],usage:`coder task run "<task text>"`,summary:`Dispatch a coding task to the configured engine. Backgrounds by default and
3
+ prints a task id; --wait runs in the foreground and prints the answer.
4
+ Shortcut: \`coder run "<text>"\`.`,flags:[[`--name <name>`,`label the task (shown in list/result)`],[`--system <text>`,`standing instructions prepended to the task (kept out of prompt previews)`],...We,V],examples:[[`coder run "add a /health endpoint"`,`dispatch in the background, print a task id`],[`coder run --wait "fix the failing test"`,`block until done, print the answer`],[`coder task run --model spark --system "tests live in test/, don't touch anything outside of it" "rename foo to bar"`,`pick an engine via its model alias; --system adds standing instructions`]],seeAlso:`task result · task steer · task stop · task stream`},"task list":{list:[`task list [--running|--stopped|--archived]`,`list recent tasks (running + just stopped)`],usage:`coder task list [--running] [--stopped] [--archived [--limit N]]`,summary:`List recent tasks across all workspaces, most recent first: running tasks plus
5
+ ones stopped within the last 10 minutes. Older stopped tasks auto-archive and
6
+ move to --archived. Shortcut: \`coder list\`.`,flags:[[`--running`,`show only running tasks`],[`--stopped`,`show only recently stopped tasks (not yet archived)`],[`--archived`,`show only archived tasks (auto-archived or via task archive)`],[`--limit <n|all>`,`show at most n tasks (default all)`],[`--dir <dir>`,`only tasks launched in that workspace`],H],seeAlso:`task result · task archive · task delete`},"task result":{list:[`task result [task-id]`,`status + final answer of a task`],usage:`coder task result [task-id]`,summary:`Show a task's status and its final answer (result pending while it runs), plus
17
7
  any pending approvals. --wait blocks until it finishes, then prints. --tail <n>
18
8
  includes the last n progress-log steps (--tail all for the whole transcript).
19
- Defaults to the most recent task. Shortcut: \`coder result\`.`,flags:[["--wait","block until the task finishes, then print"],["--tail <n|all>","include the last n progress-log steps"],X0,W0],seeAlso:"task list · task steer · task stream"},"task stream":{list:["task stream [task-id]","watch a task live (progress log)"],usage:"coder task stream [task-id]",summary:`Watch a running task's progress log live (for you/debugging), then print its
9
+ Defaults to the most recent task. Shortcut: \`coder result\`.`,flags:[[`--wait`,`block until the task finishes, then print`],[`--tail <n|all>`,`include the last n progress-log steps (default: 0, final result only)`],H,V],seeAlso:`task list · task steer · task stream`},"task stream":{list:[`task stream [task-id]`,`watch a task live (progress log)`],usage:`coder task stream [task-id]`,summary:`Watch a running task's progress log live (for you/debugging), then print its
20
10
  final answer. Replays the last line first so the current step is visible;
21
11
  --tail <n> replays the last n lines (--tail all for the whole transcript).
22
12
  Blocks until it finishes; exits 0 on success, 1 otherwise. For the answer
23
- alone, prefer \`coder result\`.`,flags:[["--tail <n|all>","replay the last n log lines first (default: 1)"],["--trim <n|none>","cap each step at n chars, text and JSON alike (default: 128)"],["--json","emit each log entry as a JSON line, then the result"],W0],examples:[["coder stream","follow the most recent task to completion"]],seeAlso:"task result · task run"},"task steer":{list:['task steer <task-id> "<follow-up>"',"continue a task's thread"],usage:'coder task steer <task-id> "<follow-up instructions>" [--wait]',summary:`Continue a finished task's thread with new instructions. Reuses the task's
24
- engine, model, and permissions unless you override them.`,flags:[["--wait","run in the foreground and block until the answer is ready"],["--model <alias|slug>","override the task's model for this follow-up"],["--effort <low|medium|high>","override the task's reasoning effort"],["--permissions <mode>","read-only · workspace-write · auto"],W0],examples:[['coder task steer coder-abc "now add tests"',"continue that task with a follow-up"]],seeAlso:"task run · task stop"},"task stop":{list:["task stop <task-id>","interrupt a running task"],usage:"coder task stop <task-id>",summary:"Interrupt a running task and mark it cancelled.",flags:[X0,W0],seeAlso:"task result · task steer"},"task archive":{list:["task archive <task-id> | --all-stopped","hide a task (or all stopped) from the list"],usage:"coder task archive <task-id> | coder task archive --all-stopped",summary:"Archive a task session so it drops out of the default list (see it again with\n`coder task list --archived [--limit N]`). Pass --all-stopped to archive every\nfinished task.",flags:[["--all-stopped","archive every stopped (finished) task"],X0,W0],seeAlso:"task list · task delete"},"task delete":{list:["task delete <task-id> | --all-archived","delete a task session (or all archived)"],usage:"coder task delete <task-id> | coder task delete --all-archived",summary:`Delete a task's session from disk. This is permanent. Pass --all-archived to
25
- delete every archived task at once. A running task must be stopped first.`,flags:[["--all-archived","delete every archived task"],X0,W0],seeAlso:"task archive · task stop"},"task approvals":{list:["task approvals <task-id>","list escalated approvals"],usage:"coder task approvals <task-id>",summary:"List permission escalations a task has raised, and how each was answered.",flags:[X0,W0],seeAlso:"task approve"},"task approve":{list:["task approve <task-id> <id> [--deny]","answer an escalated permission"],usage:"coder task approve <task-id> <approval-id> [--deny]",summary:"Answer an escalated permission request. Accepts by default; --deny rejects it.",flags:[["--deny","reject the request instead of accepting"],X0,W0],seeAlso:"task approvals · task result"},config:{list:["config [get|set|unset] <key> [value]","read or write config"],usage:"coder config [get|set|unset] <key> [value] [--workspace]",summary:`Read or write configuration. No args prints the effective config; get/set/unset
26
- target a dotted key (e.g. agents.codex.model). Writes go to ~/.coder/config.json.`,flags:[["--workspace","target <repo>/coder.config.json instead of the user file"],X0,W0],examples:[["coder config","print the effective config"],["coder config set chain codex,claude","set the engine fallback chain"],["coder config get agents.codex.model","read one value"]]},"setup-host":{list:["setup-host [claude|codex|agents]","set up the host: check engines, write config, install plugin"],usage:"coder setup-host [claude] [codex] [agents] [--json]",summary:`Set up coder in your host: check engines and auth, seed the config, and
13
+ alone, prefer \`coder result\`.`,flags:[[`--tail <n|all>`,`replay the last n log lines first (default: 1)`],[`--trim <n|none>`,`cap each step at n chars, text and JSON alike (default: 128)`],[`--json`,`emit each log entry as a JSON line, then the result`],V],examples:[[`coder stream`,`follow the most recent task to completion`]],seeAlso:`task result · task run`},"task steer":{list:[`task steer <task-id> "<follow-up>"`,`continue a task's thread`],usage:`coder task steer <task-id> "<follow-up instructions>" [--wait]`,summary:`Continue a finished task's thread with new instructions. Reuses the task's
14
+ engine, model, and permissions unless you override them.`,flags:[[`--wait`,`run in the foreground and block until the answer is ready`],[`--model <alias|slug>`,`override the task's model for this follow-up`],[`--effort <low|medium|high>`,`override the task's reasoning effort`],[`--permissions <mode>`,`read-only · workspace-write · auto`],V],examples:[[`coder task steer task-abc "now add tests"`,`continue that task with a follow-up`]],seeAlso:`task run · task stop`},"task stop":{list:[`task stop <task-id>`,`interrupt a running task`],usage:`coder task stop <task-id>`,summary:`Interrupt a running task and mark it cancelled.`,flags:[H,V],seeAlso:`task result · task steer`},"task archive":{list:[`task archive <task-id> | --all-stopped`,`hide a task (or all stopped) from the list`],usage:`coder task archive <task-id> | coder task archive --all-stopped`,summary:`Archive a task session so it drops out of the default list (see it again with
15
+ \`coder task list --archived [--limit N]\`). Pass --all-stopped to archive every
16
+ finished task.`,flags:[[`--all-stopped`,`archive every stopped (finished) task`],H,V],seeAlso:`task list · task delete`},"task delete":{list:[`task delete <task-id> | --all-archived`,`delete a task session (or all archived)`],usage:`coder task delete <task-id> | coder task delete --all-archived`,summary:`Delete a task's session from disk. This is permanent. Pass --all-archived to
17
+ delete every archived task at once. A running task must be stopped first.`,flags:[[`--all-archived`,`delete every archived task`],H,V],seeAlso:`task archive · task stop`},"task approvals":{list:[`task approvals <task-id>`,`list escalated approvals`],usage:`coder task approvals <task-id>`,summary:`List permission escalations a task has raised, and how each was answered.`,flags:[H,V],seeAlso:`task approve`},"task approve":{list:[`task approve <task-id> <id> [--deny]`,`answer an escalated permission`],usage:`coder task approve <task-id> <approval-id> [--deny]`,summary:`Answer an escalated permission request. Accepts by default; --deny rejects it.`,flags:[[`--deny`,`reject the request instead of accepting`],H,V],seeAlso:`task approvals · task result`},"flow run":{list:[`flow run <name|path> [--args | key=value...]`,`run a flow (orchestrate a wave of tasks)`],usage:`coder flow run <name|path> [--args '<json>' | key=value...] [--wait] [--concurrency N] [--max-tasks N] [--json] [--dry-run]`,summary:`Run a flow: a TypeScript file that orchestrates many coder tasks with gates,
18
+ journaling, and resume. Prints the run id and orchestrates in the background;
19
+ --wait follows the run in the foreground with live progress (Ctrl-C detaches;
20
+ it keeps running), and \`coder flow stream\` shows the same lines any time.
21
+ Stop a run with \`coder flow stop\`.`,flags:[[`--wait`,`follow the run in the foreground (Ctrl-C detaches; it keeps running)`],[`--args <json>`,`the flow's input as a JSON value (or pass bare key=value pairs)`],[`--concurrency <n>`,`tasks running at once (default: CPU count)`],[`--max-tasks <n>`,`total tasks the run may dispatch (default: CPU count x 10)`],[`--dry-run`,`print every resolved prompt and gate command without dispatching`],H,V],examples:[[`coder flow run audit-routes --wait`,`run a discovered flow`],[`coder flow run ./scratch/one-off.ts --wait`,`run a flow by path`],[`coder flow run verify --args '{"clusters":["a","b"]}' --wait`,`pass structured input`]],seeAlso:`flow list · flow discover · flow result · flow resume`},"flow list":{list:[`flow list`,`recent flow runs (running + just stopped)`],usage:`coder flow list [--archived] [--limit N] [--json]`,summary:`List recent flow runs, most recent first: running runs plus ones that ended
22
+ within the last 10 minutes. Older runs auto-archive and move to --archived.`,flags:[[`--archived`,`show archived runs (auto-archived or via flow archive)`],[`--limit <n|all>`,`show at most n runs (default all)`],H,V],seeAlso:`flow run · flow result · flow resume`},"flow discover":{list:[`flow discover`,`list flows runnable here (workspace + global)`],usage:`coder flow discover [--json]`,summary:`List every flow discoverable from the current directory: workspace flows in
23
+ .coder/flows/ (walking up to the repo root) and global flows in ~/.coder/flows/.`,flags:[H,V],seeAlso:`flow run · flow result`},"flow result":{list:[`flow result [run-id]`,`progress and result of a flow run`],usage:`coder flow result [run-id] [--tail <n|all>] [--json]`,summary:`Show a flow run's status and result, with its tasks, gates, and token ledger.
24
+ --tail <n> caps the step rows (0 for the result alone). Defaults to the most
25
+ recent run. To watch a run live, prefer \`coder flow stream\`.`,flags:[[`--tail <n|all>`,`show the last n step rows (default: all; 0 hides them)`],H,V],examples:[[`coder flow result --tail 0`,`the most recent run's result, no step rows`]],seeAlso:`flow run · flow stream · flow resume`},"flow stream":{list:[`flow stream [run-id]`,`watch a flow run live (replay + follow)`],usage:`coder flow stream [run-id] [--tail <n|all>] [--json]`,summary:`Watch a flow run live: replay its progress lines from the start, then keep
26
+ following while it runs (Ctrl-C detaches; it keeps running). Blocks until it
27
+ finishes; exits 0 on success, 1 otherwise. Defaults to the most recent run.
28
+ For the result alone, prefer \`coder flow result\`.`,flags:[[`--tail <n|all>`,`replay only the last n events first (default: all)`],[`--json`,`emit each event as a JSON line, then the result`],V],examples:[[`coder flow stream`,`follow the most recent run to completion`]],seeAlso:`flow result · flow run`},"flow stop":{list:[`flow stop [run-id]`,`stop a run and its still-running tasks`],usage:`coder flow stop [run-id] [--keep-tasks] [--json]`,summary:`Stop a running flow: signal the orchestrator so it stops dispatching, stamp the
29
+ run stopped, and stop its still-running tasks. Defaults to the most recent run;
30
+ the journal stays ready for \`coder flow resume\`.`,flags:[[`--keep-tasks`,`leave the run's still-running tasks running`],[`--json`,`print { runId, status, stoppedTasks, keptTasks }`]],seeAlso:`flow resume · flow result`},"flow resume":{list:[`flow resume [run-id]`,`continue a stopped or edited run`],usage:`coder flow resume [run-id] [--wait] [--json] [--dry-run]`,summary:`Re-run a flow from its journal: finished steps replay instantly, the first
31
+ changed or new step onward runs live. Defaults to the most recent run.
32
+ Accepts the same flags as flow run.`,flags:[[`--wait`,`follow the run in the foreground (Ctrl-C detaches; it keeps running)`],[`--concurrency <n>`,`tasks running at once`],[`--max-tasks <n>`,`total tasks the run may dispatch`],H,V],examples:[[`coder flow resume`,`continue the most recent run`]],seeAlso:`flow run · flow result`},"flow archive":{list:[`flow archive <run-id> | --all-stopped`,`hide a run (or all stopped) from the list`],usage:`coder flow archive <run-id> | coder flow archive --all-stopped`,summary:`Archive a flow run so it drops out of the default list (see it again with
33
+ \`coder flow list --archived [--limit N]\`). Pass --all-stopped to archive every
34
+ finished run. A running run must be stopped first.`,flags:[[`--all-stopped`,`archive every stopped (finished) run`],H],seeAlso:`flow list · flow delete`},"flow delete":{list:[`flow delete <run-id> | --all-archived`,`delete a run's record (or all archived)`],usage:`coder flow delete <run-id> | coder flow delete --all-archived`,summary:`Delete a flow run's record from disk (its journal, events, and logs). This is
35
+ permanent; the run's tasks are ordinary tasks and are not touched. Pass
36
+ --all-archived to delete every archived run at once. A running run must be
37
+ stopped first.`,flags:[[`--all-archived`,`delete every archived run`],H],seeAlso:`flow archive · flow stop`},config:{list:[`config [get|set|unset] <key> [value]`,`read or write config`],usage:`coder config [get|set|unset] <key> [value] [--workspace]`,summary:`Read or write configuration. No args prints the effective config; get/set/unset
38
+ target a dotted key (e.g. agents.codex.model). Writes go to ~/.coder/config.json.`,flags:[[`--workspace`,`target <repo>/coder.config.json instead of the user file`],H,V],examples:[[`coder config`,`print the effective config`],[`coder config set chain codex,claude`,`set the engine fallback chain`],[`coder config get agents.codex.model`,`read one value`]]},"setup-host":{list:[`setup-host [claude|codex|agents]`,`set up the host: check engines, write config, install plugin`],usage:`coder setup-host [claude] [codex] [agents] [--json]`,summary:`Set up coder in your host: check engines and auth, seed the config, and
27
39
  install the host plugin/skill for the named host(s). Claude Code gets its
28
40
  marketplace plugin; "agents" installs a skill into ~/.agents/skills for
29
41
  every host that reads the Agent Skills standard dir (Codex, Pi, OpenCode,
30
- ...). "codex" is an alias for agents. With no host, checks and seeds.`,flags:[["--json","machine-readable output"]],examples:[["coder setup-host claude","install the Claude Code plugin"],["coder setup-host agents","install the skill into ~/.agents/skills (Codex, Pi, OpenCode, ...)"]]},"model list":{list:["model list","list custom models and probe their endpoints"],usage:"coder model list [--json]",summary:"List the configured custom models and probe each endpoint for reachability.\nAlso the default when `coder model` is run bare.",flags:[X0,W0],seeAlso:"model add · model remove"},"model add":{list:["model add <name> --base-url <url> --model <id>","connect a local or third-party model (OpenAI-compatible)"],usage:"coder model add <name> --base-url <url> --model <id> [--env-key VAR]",summary:`Connect a custom model behind an OpenAI-compatible endpoint (Ollama, LM Studio,
42
+ ...). "codex" is an alias for agents. With no host, checks and seeds.`,flags:[[`--json`,`machine-readable output`]],examples:[[`coder setup-host claude`,`install the Claude Code plugin`],[`coder setup-host agents`,`install the skill into ~/.agents/skills (Codex, Pi, OpenCode, ...)`]]},"model list":{list:[`model list`,`list built-ins, custom models, and aliases`],usage:`coder model list [--json]`,summary:"List built-in aliases, configured custom models, and user aliases. Only custom\nmodels are probed. Also the default when `coder model` is run bare.",flags:[H,V],seeAlso:`model add · model remove`},"model add":{list:[`model add <name> --base-url <url> --model <id>`,`connect a local or third-party model (OpenAI-compatible)`],usage:`coder model add <name> --base-url <url> --model <id> [--env-key VAR]`,summary:`Connect a custom model behind an OpenAI-compatible endpoint (Ollama, LM Studio,
31
43
  vLLM, OpenRouter, ...). It currently runs on the codex engine pointed at your
32
44
  URL and is usable anywhere a model is: --model <name>, --agent custom, or as an
33
- agent default in config. Alias: \`coder model setup\`.`,flags:[["--base-url <url>","OpenAI-compatible API base (e.g. http://localhost:11434/v1)"],["--model <id>","the provider's model id (e.g. qwen2.5-coder:32b)"],["--env-key <VAR>","env var holding the API key (omit for keyless local endpoints)"],["--workspace","write to <repo>/coder.config.json instead of the user file"],X0],examples:[["coder model add qwen --base-url http://localhost:11434/v1 --model qwen2.5-coder:32b","local Ollama model, no key"],["coder model add kimi --base-url https://openrouter.ai/api/v1 --model moonshotai/kimi-k2 --env-key OPENROUTER_API_KEY","third-party provider via OpenRouter"],['coder run --model qwen "explain this repo"',"dispatch a task on it"]],seeAlso:"model list · model update · setup-host · config"},"model update":{list:["model update <name> [--base-url|--model|--env-key]","change a custom model in place"],usage:"coder model update <name> [--base-url <url>] [--model <id>] [--env-key VAR]",summary:`Update a configured custom model. Only the flags you pass change; the endpoint
34
- is re-probed and the wire protocol re-detected.`,flags:[["--base-url <url>","new API base"],["--model <id>","new provider model id"],["--env-key <VAR>","new API-key env var"],["--workspace","write to <repo>/coder.config.json instead of the user file"],X0],seeAlso:"model list · model remove"},"model remove":{list:["model remove <name>","delete a custom model"],usage:"coder model remove <name>",summary:"Remove a configured custom model.",flags:[["--workspace","target <repo>/coder.config.json instead of the user file"],X0],seeAlso:"model list · model add"},upgrade:{list:["upgrade [--cli-only|--plugins-only]","update the CLI and host plugins (alias: update)"],usage:"coder upgrade [--cli-only] [--plugins-only] [--codex] [--claude] [--pm <mgr>]",summary:`Update the coder CLI through whichever package manager installed it, then refresh
35
- the host plugins to match. Alias: update.`,flags:[["--cli-only","update just the CLI"],["--plugins-only","refresh just the host plugins"],["--codex","limit the refresh to the Agent Skills copy (Codex, Pi, ...)"],["--claude","limit the refresh to the Claude Code plugin"],["--pm <npm|pnpm|yarn|bun>","force a package manager instead of auto-detecting"]]}},m2={run:"task run",list:"task list",stream:"task stream",watch:"task stream",result:"task result",steer:"task steer",stop:"task stop",archive:"task archive",delete:"task delete",approvals:"task approvals",approve:"task approve",setup:"setup-host","host-setup":"setup-host",update:"upgrade"},u8=[{usage:"list",blurb:"list models, probe their endpoints"},{usage:"add <name> --base-url <url> --model <id> [--env-key VAR]",blurb:"connect a model (alias: setup)"},{usage:"update <name> [--base-url|--model|--env-key]",blurb:"change a model in place"},{usage:"remove <name>",blurb:"delete a model"}];function I3(){let Q=O,Y=u8.map((X)=>` ${Q.cyan(X.usage.padEnd(60))}${Q.dim(X.blurb)}`);return`${[Q.bold("Usage:")," coder model <subcommand>","","Custom (OpenAI-compatible) models: local (Ollama, LM Studio, vLLM, ...) or","hosted (OpenRouter, gateways). Together they form the `custom` agent and","currently run on the codex engine pointed at your URL.","",Q.bold("Subcommands:"),...Y,"",Q.dim("Run 'coder model <subcommand> --help' for details on any subcommand.")].join(`
36
- `)}
37
- `}function c8(Q,Y){return Q.map(([X,W])=>` ${Y.cyan(X.padEnd(30))}${Y.dim(W)}`)}function N2(Q){let Y=f0[Q];if(!Y)return null;let X=O,W=[X.bold("Usage:"),` ${Y.usage}`];if(Y.summary)W.push("",Y.summary);if(Y.flags?.length)W.push("",X.bold("Flags:"),...c8(Y.flags,X));if(Y.examples?.length){W.push("",X.bold("Examples:"));for(let[q,K]of Y.examples)W.push(` ${X.cyan(q)}`,` ${X.dim(K)}`)}if(Y.seeAlso)W.push("",X.dim(`Related: ${Y.seeAlso}`));return`${W.join(`
38
- `)}
39
- `}function J2(){let Q=O,Y=T3.map((X)=>{let W=X.alias?Q.dim(` (coder ${X.alias})`):"";return` ${Q.cyan(X.usage.padEnd(30))}${Q.dim(X.blurb)}${W}`});return`${[Q.bold("Usage:")," coder task <subcommand>","",Q.bold("Subcommands:"),...Y,"",Q.dim("Run 'coder task <subcommand> --help' for details on any subcommand.")].join(`
40
- `)}
41
- `}function u2(){let Q=O,Y=([q,K])=>` ${Q.cyan(q.padEnd(38))}${Q.dim(K)}`,X=T3.filter((q)=>q.alias).map((q)=>Y([q.usage.replace(/^\S+/,q.alias),q.blurb])),W=T3.filter((q)=>!q.alias).map((q)=>q.sub).join(", ");return`${[`${Q.bold("Coder")} ${Q.dim(`v${a()}`)}`,"Delegate a coding task to the best available engine and steer it while it runs.","",Q.bold("Get started:"),` ${Q.cyan("coder setup-host claude")} ${Q.dim("# or agents (Codex, Pi, ...); installs the host plugin/skill")}`,` ${Q.cyan(`coder run "explain this repo's layout"`)}`,"",Q.bold("Usage:")," coder <command>","",Q.bold("Commands:"),...X,` ${Q.dim(`More task commands (${W}): `)}${Q.cyan("coder task --help")}`,Y(f0.config.list),Y(["model <list|add|update|remove>","manage custom models (OpenAI-compatible)"]),Y(f0.upgrade.list),"",Q.bold("Global:"),Y(["-h, --help","show help (top-level, or for a command)"]),Y(["-v, --version","print the coder version"]),Y(["--json","JSON output instead of human-readable text"]),Y(W0)].join(`
42
- `)}
43
- `}function c2(Q){let Y=Q.indexOf("--"),X=Y===-1?Q:Q.slice(0,Y);return X.includes("-h")||X.includes("--help")}import E0 from"node:fs";import I2 from"node:path";import v from"node:process";import{spawn as wY}from"node:child_process";var o4;function F(Q,Y,X){function W(z,$){if(!z._zod)Object.defineProperty(z,"_zod",{value:{def:$,constr:G,traits:new Set},enumerable:!1});if(z._zod.traits.has(Q))return;z._zod.traits.add(Q),Y(z,$);let B=G.prototype,N=Object.keys(B);for(let H=0;H<N.length;H++){let V=N[H];if(!(V in z))z[V]=B[V].bind(z)}}let q=X?.Parent??Object;class K extends q{}Object.defineProperty(K,"name",{value:Q});function G(z){var $;let B=X?.Parent?new K:this;W(B,z),($=B._zod).deferred??($.deferred=[]);for(let N of B._zod.deferred)N();return B}return Object.defineProperty(G,"init",{value:W}),Object.defineProperty(G,Symbol.hasInstance,{value:(z)=>{if(X?.Parent&&z instanceof X.Parent)return!0;return z?._zod?.traits?.has(Q)}}),Object.defineProperty(G,"name",{value:Q}),G}var x6=Symbol("zod_brand");class D0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(o4=globalThis).__zod_globalConfig??(o4.__zod_globalConfig={});var w3=globalThis.__zod_globalConfig;function U0(Q){if(Q)Object.assign(w3,Q);return w3}function t4(Q){let Y=Object.values(Q).filter((W)=>typeof W==="number");return Object.entries(Q).filter(([W,q])=>Y.indexOf(+W)===-1).map(([W,q])=>q)}function a4(Q,Y){if(typeof Y==="bigint")return Y.toString();return Y}function s4(Q){return{get value(){{let X=Q();return Object.defineProperty(this,"value",{value:X}),X}throw Error("cached value already set")}}}function e4(Q){return Q===null||Q===void 0}function C3(Q){let Y=Q.startsWith("^")?1:0,X=Q.endsWith("$")?Q.length-1:Q.length;return Q.slice(Y,X)}var i4=Symbol("evaluating");function $0(Q,Y,X){let W=void 0;Object.defineProperty(Q,Y,{get(){if(W===i4)return;if(W===void 0)W=i4,W=X();return W},set(q){Object.defineProperty(Q,Y,{value:q})},configurable:!0})}function Q1(Q,Y,X){Object.defineProperty(Q,Y,{value:X,writable:!0,enumerable:!0,configurable:!0})}function Y1(...Q){let Y={};for(let X of Q){let W=Object.getOwnPropertyDescriptors(X);Object.assign(Y,W)}return Object.defineProperties({},Y)}var x3="captureStackTrace"in Error?Error.captureStackTrace:(...Q)=>{};function p2(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function k3(Q){if(p2(Q)===!1)return!1;let Y=Q.constructor;if(Y===void 0)return!0;if(typeof Y!=="function")return!0;let X=Y.prototype;if(p2(X)===!1)return!1;if(Object.prototype.hasOwnProperty.call(X,"isPrototypeOf")===!1)return!1;return!0}var X1=new Set(["string","number","symbol"]);function V2(Q){return Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U2(Q,Y,X){let W=new Q._zod.constr(Y??Q._zod.def);if(!Y||X?.parent)W._zod.parent=Q;return W}function h(Q){let Y=Q;if(!Y)return{};if(typeof Y==="string")return{error:()=>Y};if(Y?.message!==void 0){if(Y?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");Y.error=Y.message}if(delete Y.message,typeof Y.error==="string")return{...Y,error:()=>Y.error};return Y}function W1(Q){return Object.keys(Q).filter((Y)=>{return Q[Y]._zod.optin==="optional"&&Q[Y]._zod.optout==="optional"})}var q1={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function K1(Q,Y){if(!k3(Y))throw Error("Invalid input to extend: expected a plain object");let X=Q._zod.def.checks;if(X&&X.length>0){let K=Q._zod.def.shape;for(let G in Y)if(Object.getOwnPropertyDescriptor(K,G)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let q=Y1(Q._zod.def,{get shape(){let K={...Q._zod.def.shape,...Y};return Q1(this,"shape",K),K}});return U2(Q,q)}function z1(Q,Y,X){let q=Y._zod.def.checks;if(q&&q.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let G=Y1(Y._zod.def,{get shape(){let z=Y._zod.def.shape,$={...z};if(X)for(let B in X){if(!(B in z))throw Error(`Unrecognized key: "${B}"`);if(!X[B])continue;$[B]=Q?new Q({type:"optional",innerType:z[B]}):z[B]}else for(let B in z)$[B]=Q?new Q({type:"optional",innerType:z[B]}):z[B];return Q1(this,"shape",$),$},checks:[]});return U2(Y,G)}function p0(Q,Y=0){if(Q.aborted===!0)return!0;for(let X=Y;X<Q.issues.length;X++)if(Q.issues[X]?.continue!==!0)return!0;return!1}function G1(Q,Y=0){if(Q.aborted===!0)return!0;for(let X=Y;X<Q.issues.length;X++)if(Q.issues[X]?.continue===!1)return!0;return!1}function F0(Q,Y){return Y.map((X)=>{var W;return(W=X).path??(W.path=[]),X.path.unshift(Q),X})}function f2(Q){return typeof Q==="string"?Q:Q?.message}function L0(Q,Y,X){let W=Q.message?Q.message:f2(Q.inst?._zod.def?.error?.(Q))??f2(Y?.error?.(Q))??f2(X.customError?.(Q))??f2(X.localeError?.(Q))??"Invalid input",{inst:q,continue:K,input:G,...z}=Q;if(z.path??(z.path=[]),z.message=W,Y?.reportInput)z.input=G;return z}function $1(Q){if(Array.isArray(Q))return"array";if(typeof Q==="string")return"string";return"unknown"}var B1=(Q,Y)=>{Q.name="$ZodError",Object.defineProperty(Q,"_zod",{value:Q._zod,enumerable:!1}),Object.defineProperty(Q,"issues",{value:Y,enumerable:!1}),Q.message=JSON.stringify(Y,a4,2),Object.defineProperty(Q,"toString",{value:()=>Q.message,enumerable:!1})},H1=F("$ZodError",B1),L2=F("$ZodError",B1,{Parent:Error});var p8=(Q)=>(Y,X,W,q)=>{let K=W?{...W,async:!1}:{async:!1},G=Y._zod.run({value:X,issues:[]},K);if(G instanceof Promise)throw new D0;if(G.issues.length){let z=new(q?.Err??Q)(G.issues.map(($)=>L0($,K,U0())));throw x3(z,q?.callee),z}return G.value},l2=p8(L2),l8=(Q)=>async(Y,X,W,q)=>{let K=W?{...W,async:!0}:{async:!0},G=Y._zod.run({value:X,issues:[]},K);if(G instanceof Promise)G=await G;if(G.issues.length){let z=new(q?.Err??Q)(G.issues.map(($)=>L0($,K,U0())));throw x3(z,q?.callee),z}return G.value},r2=l8(L2),r8=(Q)=>(Y,X,W)=>{let q=W?{...W,async:!1}:{async:!1},K=Y._zod.run({value:X,issues:[]},q);if(K instanceof Promise)throw new D0;return K.issues.length?{success:!1,error:new(Q??H1)(K.issues.map((G)=>L0(G,q,U0())))}:{success:!0,data:K.value}},P2=r8(L2),d8=(Q)=>async(Y,X,W)=>{let q=W?{...W,async:!0}:{async:!0},K=Y._zod.run({value:X,issues:[]},q);if(K instanceof Promise)K=await K;return K.issues.length?{success:!1,error:new Q(K.issues.map((G)=>L0(G,q,U0())))}:{success:!0,data:K.value}},O2=d8(L2);var N1=/^https?$/;var n8="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",o8=new RegExp(`^${n8}$`);var J1=(Q)=>{let Y=Q?`[\\s\\S]{${Q?.minimum??0},${Q?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Y}$`)},V1=/^-?\d+n?$/,U1=/^-?\d+$/,d2=/^-?\d+(?:\.\d+)?$/,L1=/^(?:true|false)$/i;var T0=F("$ZodCheck",(Q,Y)=>{var X;Q._zod??(Q._zod={}),Q._zod.def=Y,(X=Q._zod).onattach??(X.onattach=[])}),i8={number:"number",bigint:"bigint",object:"date"};var v3=F("$ZodCheckGreaterThan",(Q,Y)=>{T0.init(Q,Y);let X=i8[typeof Y.value];Q._zod.onattach.push((W)=>{let q=W._zod.bag,K=(Y.inclusive?q.minimum:q.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(Y.value>K)if(Y.inclusive)q.minimum=Y.value;else q.exclusiveMinimum=Y.value}),Q._zod.check=(W)=>{if(Y.inclusive?W.value>=Y.value:W.value>Y.value)return;W.issues.push({origin:X,code:"too_small",minimum:typeof Y.value==="object"?Y.value.getTime():Y.value,input:W.value,inclusive:Y.inclusive,inst:Q,continue:!Y.abort})}});var P1=F("$ZodCheckNumberFormat",(Q,Y)=>{T0.init(Q,Y),Y.format=Y.format||"float64";let X=Y.format?.includes("int"),W=X?"int":"number",[q,K]=q1[Y.format];Q._zod.onattach.push((G)=>{let z=G._zod.bag;if(z.format=Y.format,z.minimum=q,z.maximum=K,X)z.pattern=U1}),Q._zod.check=(G)=>{let z=G.value;if(X){if(!Number.isInteger(z)){G.issues.push({expected:W,format:Y.format,code:"invalid_type",continue:!1,input:z,inst:Q});return}if(!Number.isSafeInteger(z)){if(z>0)G.issues.push({input:z,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:W,inclusive:!0,continue:!Y.abort});else G.issues.push({input:z,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:W,inclusive:!0,continue:!Y.abort});return}}if(z<q)G.issues.push({origin:"number",input:z,code:"too_small",minimum:q,inclusive:!0,inst:Q,continue:!Y.abort});if(z>K)G.issues.push({origin:"number",input:z,code:"too_big",maximum:K,inclusive:!0,inst:Q,continue:!Y.abort})}});var O1=F("$ZodCheckMinLength",(Q,Y)=>{var X;T0.init(Q,Y),(X=Q._zod.def).when??(X.when=(W)=>{let q=W.value;return!e4(q)&&q.length!==void 0}),Q._zod.onattach.push((W)=>{let q=W._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(Y.minimum>q)W._zod.bag.minimum=Y.minimum}),Q._zod.check=(W)=>{let q=W.value;if(q.length>=Y.minimum)return;let G=$1(q);W.issues.push({origin:G,code:"too_small",minimum:Y.minimum,inclusive:!0,input:q,inst:Q,continue:!Y.abort})}});var h3=F("$ZodCheckStringFormat",(Q,Y)=>{var X,W;if(T0.init(Q,Y),Q._zod.onattach.push((q)=>{let K=q._zod.bag;if(K.format=Y.format,Y.pattern)K.patterns??(K.patterns=new Set),K.patterns.add(Y.pattern)}),Y.pattern)(X=Q._zod).check??(X.check=(q)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(q.value))return;q.issues.push({origin:"string",code:"invalid_format",format:Y.format,input:q.value,...Y.pattern?{pattern:Y.pattern.toString()}:{},inst:Q,continue:!Y.abort})});else(W=Q._zod).check??(W.check=()=>{})}),Z1=F("$ZodCheckRegex",(Q,Y)=>{h3.init(Q,Y),Q._zod.check=(X)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(X.value))return;X.issues.push({origin:"string",code:"invalid_format",format:"regex",input:X.value,pattern:Y.pattern.toString(),inst:Q,continue:!Y.abort})}});var D1={major:4,minor:4,patch:3};var l=F("$ZodType",(Q,Y)=>{var X;Q??(Q={}),Q._zod.def=Y,Q._zod.bag=Q._zod.bag||{},Q._zod.version=D1;let W=[...Q._zod.def.checks??[]];if(Q._zod.traits.has("$ZodCheck"))W.unshift(Q);for(let q of W)for(let K of q._zod.onattach)K(Q);if(W.length===0)(X=Q._zod).deferred??(X.deferred=[]),Q._zod.deferred?.push(()=>{Q._zod.run=Q._zod.parse});else{let q=(G,z,$)=>{let B=p0(G),N;for(let H of z){if(H._zod.def.when){if(G1(G))continue;if(!H._zod.def.when(G))continue}else if(B)continue;let V=G.issues.length,J=H._zod.check(G);if(J instanceof Promise&&$?.async===!1)throw new D0;if(N||J instanceof Promise)N=(N??Promise.resolve()).then(async()=>{if(await J,G.issues.length===V)return;if(!B)B=p0(G,V)});else{if(G.issues.length===V)continue;if(!B)B=p0(G,V)}}if(N)return N.then(()=>{return G});return G},K=(G,z,$)=>{if(p0(G))return G.aborted=!0,G;let B=q(z,W,$);if(B instanceof Promise){if($.async===!1)throw new D0;return B.then((N)=>Q._zod.parse(N,$))}return Q._zod.parse(B,$)};Q._zod.run=(G,z)=>{if(z.skipChecks)return Q._zod.parse(G,z);if(z.direction==="backward"){let B=Q._zod.parse({value:G.value,issues:[]},{...z,skipChecks:!0});if(B instanceof Promise)return B.then((N)=>{return K(N,G,z)});return K(B,G,z)}let $=Q._zod.parse(G,z);if($ instanceof Promise){if(z.async===!1)throw new D0;return $.then((B)=>q(B,W,z))}return q($,W,z)}}$0(Q,"~standard",()=>({validate:(q)=>{try{let K=P2(Q,q);return K.success?{value:K.data}:{issues:K.error?.issues}}catch(K){return O2(Q,q).then((G)=>G.success?{value:G.data}:{issues:G.error?.issues})}},vendor:"zod",version:1}))}),b3=F("$ZodString",(Q,Y)=>{l.init(Q,Y),Q._zod.pattern=[...Q?._zod.bag?.patterns??[]].pop()??J1(Q._zod.bag),Q._zod.parse=(X,W)=>{if(Y.coerce)try{X.value=String(X.value)}catch(q){}if(typeof X.value==="string")return X;return X.issues.push({expected:"string",code:"invalid_type",input:X.value,inst:Q}),X}}),g3=F("$ZodStringFormat",(Q,Y)=>{h3.init(Q,Y),b3.init(Q,Y)});var M1=F("$ZodURL",(Q,Y)=>{g3.init(Q,Y),Q._zod.check=(X)=>{try{let W=X.value.trim();if(!Y.normalize&&Y.protocol?.source===N1.source){if(!/^https?:\/\//i.test(W)){X.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:X.value,inst:Q,continue:!Y.abort});return}}let q=new URL(W);if(Y.hostname){if(Y.hostname.lastIndex=0,!Y.hostname.test(q.hostname))X.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Y.hostname.source,input:X.value,inst:Q,continue:!Y.abort})}if(Y.protocol){if(Y.protocol.lastIndex=0,!Y.protocol.test(q.protocol.endsWith(":")?q.protocol.slice(0,-1):q.protocol))X.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:Y.protocol.source,input:X.value,inst:Q,continue:!Y.abort})}if(Y.normalize)X.value=q.href;else X.value=W;return}catch(W){X.issues.push({code:"invalid_format",format:"url",input:X.value,inst:Q,continue:!Y.abort})}}});var y3=F("$ZodNumber",(Q,Y)=>{l.init(Q,Y),Q._zod.pattern=Q._zod.bag.pattern??d2,Q._zod.parse=(X,W)=>{if(Y.coerce)try{X.value=Number(X.value)}catch(G){}let q=X.value;if(typeof q==="number"&&!Number.isNaN(q)&&Number.isFinite(q))return X;let K=typeof q==="number"?Number.isNaN(q)?"NaN":!Number.isFinite(q)?"Infinity":void 0:void 0;return X.issues.push({expected:"number",code:"invalid_type",input:q,inst:Q,...K?{received:K}:{}}),X}}),_1=F("$ZodNumberFormat",(Q,Y)=>{P1.init(Q,Y),y3.init(Q,Y)}),T1=F("$ZodBoolean",(Q,Y)=>{l.init(Q,Y),Q._zod.pattern=L1,Q._zod.parse=(X,W)=>{if(Y.coerce)try{X.value=Boolean(X.value)}catch(K){}let q=X.value;if(typeof q==="boolean")return X;return X.issues.push({expected:"boolean",code:"invalid_type",input:q,inst:Q}),X}}),I1=F("$ZodBigInt",(Q,Y)=>{l.init(Q,Y),Q._zod.pattern=V1,Q._zod.parse=(X,W)=>{if(Y.coerce)try{X.value=BigInt(X.value)}catch(q){}if(typeof X.value==="bigint")return X;return X.issues.push({expected:"bigint",code:"invalid_type",input:X.value,inst:Q}),X}});var w1=F("$ZodNever",(Q,Y)=>{l.init(Q,Y),Q._zod.parse=(X,W)=>{return X.issues.push({expected:"never",code:"invalid_type",input:X.value,inst:Q}),X}});var S1=F("$ZodDate",(Q,Y)=>{l.init(Q,Y),Q._zod.parse=(X,W)=>{if(Y.coerce)try{X.value=new Date(X.value)}catch(z){}let q=X.value,K=q instanceof Date;if(K&&!Number.isNaN(q.getTime()))return X;return X.issues.push({expected:"date",code:"invalid_type",input:q,...K?{received:"Invalid Date"}:{},inst:Q}),X}});function F1(Q,Y,X){if(Q.issues.length)Y.issues.push(...F0(X,Q.issues));Y.value[X]=Q.value}var C1=F("$ZodArray",(Q,Y)=>{l.init(Q,Y),Q._zod.parse=(X,W)=>{let q=X.value;if(!Array.isArray(q))return X.issues.push({expected:"array",code:"invalid_type",input:q,inst:Q}),X;X.value=Array(q.length);let K=[];for(let G=0;G<q.length;G++){let z=q[G],$=Y.element._zod.run({value:z,issues:[]},W);if($ instanceof Promise)K.push($.then((B)=>F1(B,X,G)));else F1($,X,G)}if(K.length)return Promise.all(K).then(()=>X);return X}});function n2(Q,Y,X,W,q,K){let G=X in W;if(Q.issues.length){if(q&&K&&!G)return;Y.issues.push(...F0(X,Q.issues))}if(!G&&!q){if(!Q.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[X]});return}if(Q.value===void 0){if(G)Y.value[X]=void 0}else Y.value[X]=Q.value}function a8(Q){let Y=Object.keys(Q.shape);for(let W of Y)if(!Q.shape?.[W]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${W}": expected a Zod schema`);let X=W1(Q.shape);return{...Q,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(X)}}function s8(Q,Y,X,W,q,K){let G=[],z=q.keySet,$=q.catchall._zod,B=$.def.type,N=$.optin==="optional",H=$.optout==="optional";for(let V in Y){if(V==="__proto__")continue;if(z.has(V))continue;if(B==="never"){G.push(V);continue}let J=$.run({value:Y[V],issues:[]},W);if(J instanceof Promise)Q.push(J.then((U)=>n2(U,X,V,Y,N,H)));else n2(J,X,V,Y,N,H)}if(G.length)X.issues.push({code:"unrecognized_keys",keys:G,input:Y,inst:K});if(!Q.length)return X;return Promise.all(Q).then(()=>{return X})}var x1=F("$ZodObject",(Q,Y)=>{if(l.init(Q,Y),!Object.getOwnPropertyDescriptor(Y,"shape")?.get){let z=Y.shape;Object.defineProperty(Y,"shape",{get:()=>{let $={...z};return Object.defineProperty(Y,"shape",{value:$}),$}})}let W=s4(()=>a8(Y));$0(Q._zod,"propValues",()=>{let z=Y.shape,$={};for(let B in z){let N=z[B]._zod;if(N.values){$[B]??($[B]=new Set);for(let H of N.values)$[B].add(H)}}return $});let q=p2,K=Y.catchall,G;Q._zod.parse=(z,$)=>{G??(G=W.value);let B=z.value;if(!q(B))return z.issues.push({expected:"object",code:"invalid_type",input:B,inst:Q}),z;z.value={};let N=[],H=G.shape;for(let V of G.keys){let J=H[V],U=J._zod.optin==="optional",L=J._zod.optout==="optional",P=J._zod.run({value:B[V],issues:[]},$);if(P instanceof Promise)N.push(P.then((Z)=>n2(Z,z,V,B,U,L)));else n2(P,z,V,B,U,L)}if(!K)return N.length?Promise.all(N).then(()=>z):z;return s8(N,B,z,$,W.value,Q)}});function R1(Q,Y,X,W){for(let K of Q)if(K.issues.length===0)return Y.value=K.value,Y;let q=Q.filter((K)=>!p0(K));if(q.length===1)return Y.value=q[0].value,q[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map((K)=>K.issues.map((G)=>L0(G,W,U0())))}),Y}var k1=F("$ZodUnion",(Q,Y)=>{l.init(Q,Y),$0(Q._zod,"optin",()=>Y.options.some((W)=>W._zod.optin==="optional")?"optional":void 0),$0(Q._zod,"optout",()=>Y.options.some((W)=>W._zod.optout==="optional")?"optional":void 0),$0(Q._zod,"values",()=>{if(Y.options.every((W)=>W._zod.values))return new Set(Y.options.flatMap((W)=>Array.from(W._zod.values)));return}),$0(Q._zod,"pattern",()=>{if(Y.options.every((W)=>W._zod.pattern)){let W=Y.options.map((q)=>q._zod.pattern);return new RegExp(`^(${W.map((q)=>C3(q.source)).join("|")})$`)}return});let X=Y.options.length===1?Y.options[0]._zod.run:null;Q._zod.parse=(W,q)=>{if(X)return X(W,q);let K=!1,G=[];for(let z of Y.options){let $=z._zod.run({value:W.value,issues:[]},q);if($ instanceof Promise)G.push($),K=!0;else{if($.issues.length===0)return $;G.push($)}}if(!K)return R1(G,W,Q,q);return Promise.all(G).then((z)=>{return R1(z,W,Q,q)})}});var j1=F("$ZodRecord",(Q,Y)=>{l.init(Q,Y),Q._zod.parse=(X,W)=>{let q=X.value;if(!k3(q))return X.issues.push({expected:"record",code:"invalid_type",input:q,inst:Q}),X;let K=[],G=Y.keyType._zod.values;if(G){X.value={};let z=new Set;for(let B of G)if(typeof B==="string"||typeof B==="number"||typeof B==="symbol"){z.add(typeof B==="number"?B.toString():B);let N=Y.keyType._zod.run({value:B,issues:[]},W);if(N instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(N.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:N.issues.map((J)=>L0(J,W,U0())),input:B,path:[B],inst:Q});continue}let H=N.value,V=Y.valueType._zod.run({value:q[B],issues:[]},W);if(V instanceof Promise)K.push(V.then((J)=>{if(J.issues.length)X.issues.push(...F0(B,J.issues));X.value[H]=J.value}));else{if(V.issues.length)X.issues.push(...F0(B,V.issues));X.value[H]=V.value}}let $;for(let B in q)if(!z.has(B))$=$??[],$.push(B);if($&&$.length>0)X.issues.push({code:"unrecognized_keys",input:q,inst:Q,keys:$})}else{X.value={};for(let z of Reflect.ownKeys(q)){if(z==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(q,z))continue;let $=Y.keyType._zod.run({value:z,issues:[]},W);if($ instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof z==="string"&&d2.test(z)&&$.issues.length){let H=Y.keyType._zod.run({value:Number(z),issues:[]},W);if(H instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(H.issues.length===0)$=H}if($.issues.length){if(Y.mode==="loose")X.value[z]=q[z];else X.issues.push({code:"invalid_key",origin:"record",issues:$.issues.map((H)=>L0(H,W,U0())),input:z,path:[z],inst:Q});continue}let N=Y.valueType._zod.run({value:q[z],issues:[]},W);if(N instanceof Promise)K.push(N.then((H)=>{if(H.issues.length)X.issues.push(...F0(z,H.issues));X.value[$.value]=H.value}));else{if(N.issues.length)X.issues.push(...F0(z,N.issues));X.value[$.value]=N.value}}}if(K.length)return Promise.all(K).then(()=>X);return X}});var v1=F("$ZodEnum",(Q,Y)=>{l.init(Q,Y);let X=t4(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((q)=>X1.has(typeof q)).map((q)=>typeof q==="string"?V2(q):q.toString()).join("|")})$`),Q._zod.parse=(q,K)=>{let G=q.value;if(W.has(G))return q;return q.issues.push({code:"invalid_value",values:X,input:G,inst:Q}),q}}),h1=F("$ZodLiteral",(Q,Y)=>{if(l.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");let X=new Set(Y.values);Q._zod.values=X,Q._zod.pattern=new RegExp(`^(${Y.values.map((W)=>typeof W==="string"?V2(W):W?V2(W.toString()):String(W)).join("|")})$`),Q._zod.parse=(W,q)=>{let K=W.value;if(X.has(K))return W;return W.issues.push({code:"invalid_value",values:Y.values,input:K,inst:Q}),W}});function E1(Q,Y){if(Y===void 0&&(Q.issues.length||Q.fallback))return{issues:[],value:void 0};return Q}var b1=F("$ZodOptional",(Q,Y)=>{l.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",$0(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),$0(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${C3(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let q=X.value,K=Y.innerType._zod.run(X,W);if(K instanceof Promise)return K.then((G)=>E1(G,q));return E1(K,q)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}});function g1(Q,Y){return new Q({type:"string",...h(Y)})}function y1(Q,Y){return new Q({type:"string",coerce:!0,...h(Y)})}function m1(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...h(Y)})}function u1(Q,Y){return new Q({type:"number",checks:[],...h(Y)})}function c1(Q,Y){return new Q({type:"number",coerce:!0,checks:[],...h(Y)})}function f1(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...h(Y)})}function p1(Q,Y){return new Q({type:"boolean",...h(Y)})}function l1(Q,Y){return new Q({type:"boolean",coerce:!0,...h(Y)})}function r1(Q,Y){return new Q({type:"bigint",coerce:!0,...h(Y)})}function d1(Q,Y){return new Q({type:"never",...h(Y)})}function n1(Q,Y){return new Q({type:"date",coerce:!0,...h(Y)})}function o1(Q,Y){return new v3({check:"greater_than",...h(Y),value:Q,inclusive:!1})}function m3(Q,Y){return new v3({check:"greater_than",...h(Y),value:Q,inclusive:!0})}function I0(Q){return o1(0,Q)}function Z2(Q){return m3(0,Q)}function r0(Q,Y){return new O1({check:"min_length",...h(Y),minimum:Q})}function u3(Q,Y){return new Z1({check:"string_format",format:"regex",...h(Y),pattern:Q})}var s=F("ZodMiniType",(Q,Y)=>{if(!Q._zod)throw Error("Uninitialized schema in ZodMiniType.");l.init(Q,Y),Q.def=Y,Q.type=Y.type,Q.parse=(X,W)=>l2(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>P2(Q,X,W),Q.parseAsync=async(X,W)=>r2(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>O2(Q,X,W),Q.check=(...X)=>{return Q.clone({...Y,checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]},{parent:!0})},Q.with=Q.check,Q.clone=(X,W)=>U2(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.apply=(X)=>X(Q)}),o2=F("ZodMiniString",(Q,Y)=>{b3.init(Q,Y),s.init(Q,Y)});function P0(Q){return g1(o2,Q)}var YQ=F("ZodMiniStringFormat",(Q,Y)=>{g3.init(Q,Y),o2.init(Q,Y)});var XQ=F("ZodMiniURL",(Q,Y)=>{M1.init(Q,Y),YQ.init(Q,Y)});function a1(Q){return m1(XQ,Q)}var i2=F("ZodMiniNumber",(Q,Y)=>{y3.init(Q,Y),s.init(Q,Y)});function s1(Q){return u1(i2,Q)}var WQ=F("ZodMiniNumberFormat",(Q,Y)=>{_1.init(Q,Y),i2.init(Q,Y)});function w0(Q){return f1(WQ,Q)}var c3=F("ZodMiniBoolean",(Q,Y)=>{T1.init(Q,Y),s.init(Q,Y)});function e1(Q){return p1(c3,Q)}var Q9=F("ZodMiniBigInt",(Q,Y)=>{I1.init(Q,Y),s.init(Q,Y)});var qQ=F("ZodMiniNever",(Q,Y)=>{w1.init(Q,Y),s.init(Q,Y)});function KQ(Q){return d1(qQ,Q)}var Y9=F("ZodMiniDate",(Q,Y)=>{S1.init(Q,Y),s.init(Q,Y)});var zQ=F("ZodMiniArray",(Q,Y)=>{C1.init(Q,Y),s.init(Q,Y)});function f3(Q,Y){return new zQ({type:"array",element:Q,...h(Y)})}var X9=F("ZodMiniObject",(Q,Y)=>{x1.init(Q,Y),s.init(Q,Y),$0(Q,"shape",()=>Y.shape)});function S(Q,Y){let X={type:"object",shape:Q??{},...h(Y)};return new X9(X)}function d0(Q,Y){return new X9({type:"object",shape:Q,catchall:KQ(),...h(Y)})}function W9(Q,Y){return K1(Q,Y)}function A2(Q,Y){return z1(K9,Q,Y)}var GQ=F("ZodMiniUnion",(Q,Y)=>{k1.init(Q,Y),s.init(Q,Y)});function S0(Q,Y){return new GQ({type:"union",options:Q,...h(Y)})}var i1=F("ZodMiniRecord",(Q,Y)=>{j1.init(Q,Y),s.init(Q,Y)});function q9(Q,Y,X){if(!Y||!Y._zod)return new i1({type:"record",keyType:P0(),valueType:Q,...h(Y)});return new i1({type:"record",keyType:Q,valueType:Y,...h(X)})}var $Q=F("ZodMiniEnum",(Q,Y)=>{v1.init(Q,Y),s.init(Q,Y),Q.options=Object.values(Y.entries)});function n0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new $Q({type:"enum",entries:X,...h(Y)})}var BQ=F("ZodMiniLiteral",(Q,Y)=>{h1.init(Q,Y),s.init(Q,Y)});function C0(Q,Y){return new BQ({type:"literal",values:Array.isArray(Q)?Q:[Q],...h(Y)})}var K9=F("ZodMiniOptional",(Q,Y)=>{b1.init(Q,Y),s.init(Q,Y)});function d(Q){return new K9({type:"optional",innerType:Q})}var O0={};R8(O0,{string:()=>JQ,number:()=>VQ,date:()=>PQ,boolean:()=>UQ,bigint:()=>LQ});function JQ(Q){return y1(o2,Q)}function VQ(Q){return c1(i2,Q)}function UQ(Q){return l1(c3,Q)}function LQ(Q){return r1(Q9,Q)}function PQ(Q){return n1(Y9,Q)}var _=d(e1()),j=d(P0()),b={cwd:j,json:_};function p3(Q){let Y=Q.def;while(Y){if(Y.type==="boolean")return!0;let X=Y.innerType??Y.in;Y=X?X.def:void 0}return!1}function T(Q,Y){let X=Y.shape,W={},q=[],K=!1,G=($,B,N,H)=>{let V=X[B],J=H?"-":"--";if(!V)throw Error(`Unknown option ${J}${$} (use -- to pass literal text starting with -)`);if(p3(V))return W[B]=N===void 0?!0:N!=="false",0;if(N===void 0)throw Error(`Missing value for ${J}${$}`);return W[B]=N,1};for(let $=0;$<Q.length;$+=1){let B=Q[$];if(K){q.push(B);continue}if(B==="--"){K=!0;continue}if(!B.startsWith("-")||B==="-"){q.push(B);continue}if(B.startsWith("--")){let[H,V]=B.slice(2).split("=",2);if(V===void 0&&X[H]&&!p3(X[H]))$+=G(H,H,Q[$+1],!1);else G(H,H,V,!1);continue}let N=B.slice(1);if(X[N]&&!p3(X[N]))$+=G(N,N,Q[$+1],!0);else G(N,N,void 0,!0)}let z=Y.safeParse(W);if(!z.success){let $=z.error.issues[0],B=String($.path[0]??""),N=W[B];throw Error(N===void 0?`Missing required --${B}.`:`Invalid --${B} value ${JSON.stringify(N)}: ${$.message}`)}return{options:z.data,positionals:q}}import q0 from"node:fs";import K0 from"node:path";var OQ="item/commandExecution/requestApproval",ZQ="item/fileChange/requestApproval",AQ=new Set(["commit","checkout","switch","restore","stash","reset","rebase","merge","push","pull","cherry-pick","revert","clean","am","apply","tag","branch","worktree","filter-branch","filter-repo","gc","prune","reflog","remote","submodule","config"]),DQ=[/\bsudo\b/,/\brm\s+(-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r)\b.*\s(\/\*?|~\/?|\$HOME\/?)(\s|$)/,/\b(shutdown|reboot|halt|poweroff)\b/,/\bmkfs\b|\bdiskutil\s+erase/i,/\b(chmod|chown)\b.*-R.*\s\/(\s|$)/,/\bkill(all)?\s+-9\s+1\b/,/curl[^|;&]*\|\s*(ba|z|da)?sh\b/,/wget[^|;&]*\|\s*(ba|z|da)?sh\b/,/\blaunchctl\b|\bsystemctl\b/,/\bdefaults\s+write\b/,/>\s*\/dev\/(sd|disk)/],FQ=new Set(["status","log","diff","show","blame","rev-parse","ls-files","ls-tree","cat-file","describe","shortlog","grep","branch","stash"]);function RQ(Q){let Y=Q.match(/^\s*(?:ba|z|da)?sh\s+(?:-[a-zA-Z]+\s+)*(?:-c\s+)?(["'])([\s\S]*)\1\s*$/);return Y?Y[2]:Q}function EQ(Q){return Q.trim().split(/\s+/).filter(Boolean)}function MQ(Q){let Y=Q.find((X,W)=>W>0&&!X.startsWith("-"));if(!Y)return{decision:"accept",reason:"bare git"};if(Y==="branch"&&Q.some((X)=>/^-(d|D|m|M|c|C|f|u)|^--(delete|move|copy|force|set-upstream)/.test(X)))return{decision:"decline",reason:"git branch write operation (git is read-only for Coder)"};if(Y==="stash"){let X=Q.find((W,q)=>q>1&&!W.startsWith("-"));if(X==="list"||X==="show")return{decision:"accept",reason:`git stash ${X} is read-only`};return{decision:"decline",reason:"git stash write operation (git is read-only for Coder)"}}if(FQ.has(Y))return{decision:"accept",reason:`git ${Y} is read-only`};if(AQ.has(Y))return{decision:"decline",reason:`git ${Y} is a write operation (git is read-only for Coder)`};return{decision:"escalate",reason:`unrecognized git subcommand: ${Y}`}}function z9(Q,Y={}){let X=RQ(String(Q??""));if(!X.trim())return{decision:"escalate",reason:"empty command"};for(let z of DQ)if(z.test(X))return{decision:"decline",reason:`matches hard-deny pattern ${z}`};if(/\$\(|`|<\(/.test(X))return{decision:"escalate",reason:"contains command substitution"};let W=X.split(/&&|\|\||;|\||\r?\n/).map((z)=>z.trim()).filter(Boolean);if(W.length>1){let z={decision:"accept",reason:"all segments safe"};for(let $ of W){let B=z9($,Y);if(B.decision==="decline")return B;if(B.decision==="escalate")z=B}return z}let q=EQ(X),K=K0.basename(q[0]??"");if(K==="git")return MQ(q);let G=Y.networkHost;if(G){if((Y.allowedNetworkHosts??[]).some(($)=>G===$||G.endsWith(`.${$}`)))return{decision:"accept",reason:`network host ${G} is allowlisted`};return{decision:"escalate",reason:`network access to ${G}`}}return{decision:"escalate",reason:`command needs approval: ${K||"(unknown)"}`}}function _Q(Q,Y){if(!Q.length)return{decision:"escalate",reason:"file change with no resolvable paths"};for(let X of Q){let W=K0.resolve(Y,X),q=K0.relative(Y,W);if(q.startsWith("..")||K0.isAbsolute(q))return{decision:"escalate",reason:`path outside workspace: ${X}`};if(q===".git"||q.startsWith(`.git${K0.sep}`))return{decision:"decline",reason:`direct .git modification: ${X}`}}return{decision:"accept",reason:"all paths inside workspace"}}function r3(Q){return K0.join(Q,"approvals")}function o0(Q){let Y=r3(Q);if(!q0.existsSync(Y))return[];return q0.readdirSync(Y).filter((X)=>X.endsWith(".request.json")).map((X)=>{let W=X.replace(/\.request\.json$/,""),q=JSON.parse(q0.readFileSync(K0.join(Y,X),"utf8")),K=K0.join(Y,`${W}.response.json`),G=q0.existsSync(K)?JSON.parse(q0.readFileSync(K,"utf8")):null;return{...q,id:W,response:G}}).sort((X,W)=>String(X.createdAt??"").localeCompare(String(W.createdAt??"")))}function G9(Q,Y,X){let W=r3(Q),q=K0.join(W,`${Y}.request.json`);if(!q0.existsSync(q))throw Error(`No pending approval "${Y}" for this job.`);q0.writeFileSync(K0.join(W,`${Y}.response.json`),`${JSON.stringify({decision:X,answeredAt:new Date().toISOString()},null,2)}
44
- `,"utf8")}async function l3(Q,Y,{timeoutMs:X,onEvent:W}){let q=r3(Q);q0.mkdirSync(q,{recursive:!0});let K=`apr-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`;q0.writeFileSync(K0.join(q,`${K}.request.json`),`${JSON.stringify({...Y,createdAt:new Date().toISOString()},null,2)}
45
- `,"utf8"),W?.({kind:"approval-escalated",approvalId:K,summary:Y.summary,message:`Approval needed (${K}): ${Y.summary}. Answer with: coder approve <job> ${K} [--deny]`});let G=K0.join(q,`${K}.response.json`),z=Date.now()+X;while(Date.now()<z){if(q0.existsSync(G))try{let B=JSON.parse(q0.readFileSync(G,"utf8")).decision==="accept"?"accept":"decline";return W?.({kind:"approval-answered",approvalId:K,decision:B}),B}catch{}await new Promise(($)=>setTimeout($,400))}return W?.({kind:"approval-timeout",approvalId:K,message:`Approval ${K} timed out; declining.`}),"decline"}function $9(Q,Y={}){return l3(Q,{method:"simulate",summary:"simulated approval probe (--simulate-approval)"},{timeoutMs:Y.timeoutMs??120000,onEvent:Y.onEvent??null})}function B9({workspaceRoot:Q,jobDir:Y,mode:X="auto",escalationTimeoutMs:W=120000,allowedNetworkHosts:q=[],onEvent:K=null}){return async(G,z,$)=>{if(G===OQ){let B=z.command??$?.itemIndex?.get(z.itemId??"")?.command??"",N=`run command: ${B||"(unknown command)"}${z.reason?` — ${z.reason}`:""}`;if(X==="deny")return K?.({kind:"approval-decision",method:G,decision:"decline",reason:"deny mode",summary:N}),{decision:"decline"};let H=z9(B,{networkHost:z.networkApprovalContext?.host??null,allowedNetworkHosts:q});if(K?.({kind:"approval-decision",method:G,decision:H.decision,reason:H.reason,summary:N}),H.decision==="escalate")return{decision:await l3(Y,{method:G,summary:N,command:B,params:z},{timeoutMs:W,onEvent:K})};return{decision:H.decision}}if(G===ZQ){let N=($?.itemIndex?.get(z.itemId??"")?.changes??[]).map((J)=>J.path).filter((J)=>Boolean(J)),H=`apply file changes: ${N.join(", ")||"(unknown paths)"}${z.reason?` — ${z.reason}`:""}`;if(X==="deny")return K?.({kind:"approval-decision",method:G,decision:"decline",reason:"deny mode",summary:H}),{decision:"decline"};let V=_Q(N,Q);if(K?.({kind:"approval-decision",method:G,decision:V.decision,reason:V.reason,summary:H}),V.decision==="escalate")return{decision:await l3(Y,{method:G,summary:H,paths:N,params:z},{timeoutMs:W,onEvent:K})};return{decision:V.decision}}throw K?.({kind:"approval-unsupported",method:G}),Error(`Coder does not handle server request ${G}; treating as denied.`)}}async function t2(Q,Y,X=400){let W=Y;for(;;){if(Z0.includes(W.status))return{job:W,reason:"terminal"};let q=o0(C(Q,W.id)).filter((K)=>!K.response);if(q[0])return{job:W,reason:"approval",approval:{id:q[0].id,summary:String(q[0].summary??"")}};await new Promise((K)=>setTimeout(K,X)),W=b0(Q,r(Q,W.id)??W)}}import{spawnSync as oQ}from"node:child_process";import pQ from"node:net";import R2 from"node:process";import{spawn as lQ}from"node:child_process";import rQ from"node:readline";import H9 from"node:path";import TQ from"node:process";function IQ(Q){return String(Q??"").replace(/[^A-Za-z0-9._-]/g,"-").replace(/^-+|-+$/g,"")}function N9(Q,Y=TQ.platform){if(Y==="win32")return`pipe:\\\\.\\pipe\\${IQ(`${H9.win32.basename(Q)}-codex-app-server`)}`;return`unix:${H9.join(Q,"broker.sock")}`}function D2(Q){if(typeof Q!=="string"||Q.length===0)throw Error("Missing broker endpoint.");if(Q.startsWith("pipe:")){let Y=Q.slice(5);if(!Y)throw Error("Broker pipe endpoint is missing its path.");return{kind:"pipe",path:Y}}if(Q.startsWith("unix:")){let Y=Q.slice(5);if(!Y)throw Error("Broker Unix socket endpoint is missing its path.");return{kind:"unix",path:Y}}throw Error(`Unsupported broker endpoint: ${Q}`)}import g from"node:fs";import wQ from"node:net";import SQ from"node:os";import i0 from"node:path";import d3 from"node:process";import{spawn as CQ}from"node:child_process";import{fileURLToPath as xQ}from"node:url";var kQ="broker.json";function jQ(Q="coder-"){return g.mkdtempSync(i0.join(SQ.tmpdir(),Q))}function vQ(Q){let Y=D2(Q);return wQ.createConnection({path:Y.path})}async function V9(Q,Y=2000){let X=Date.now();while(Date.now()-X<Y){if(await new Promise((q)=>{let K=vQ(Q);K.on("connect",()=>{K.end(),q(!0)}),K.on("error",()=>q(!1))}))return!0;await new Promise((q)=>setTimeout(q,50))}return!1}function hQ({scriptPath:Q,cwd:Y,endpoint:X,pidFile:W,logFile:q,env:K=d3.env}){let G=g.openSync(q,"a"),z=CQ(d3.execPath,[Q,"serve","--endpoint",X,"--cwd",Y,"--pid-file",W],{cwd:Y,env:K,detached:!0,stdio:["ignore",G,G]});return z.unref(),g.closeSync(G),z}function bQ(){let Q=[new URL("./lib/broker.js",import.meta.url),new URL("./broker.js",import.meta.url)];for(let Y of Q){let X=xQ(Y);if(g.existsSync(X))return X}throw Error("Coder broker script not found next to the runtime. Rebuild with `bun run build`.")}function n3(Q){return i0.join(K2(Q),kQ)}function o3(Q){let Y=n3(Q);if(!g.existsSync(Y))return null;try{return JSON.parse(g.readFileSync(Y,"utf8"))}catch{return null}}function gQ(Q,Y){let X=K2(Q);g.mkdirSync(X,{recursive:!0}),g.writeFileSync(n3(Q),`${JSON.stringify(Y,null,2)}
46
- `,"utf8")}function yQ(Q){let Y=n3(Q);if(g.existsSync(Y))g.unlinkSync(Y)}async function mQ(Q){if(!Q)return!1;try{return await V9(Q,150)}catch{return!1}}async function U9(Q,Y={}){let X=Y.scriptPath??bQ(),W=a(),q=o3(Q),K=q?.version===W&&q?.scriptPath===X;if(q&&K&&await mQ(q.endpoint))return q;if(q)J9({endpoint:q.endpoint??null,pidFile:q.pidFile??null,logFile:q.logFile??null,sessionDir:q.sessionDir??null,pid:q.pid??null,killProcess:Y.killProcess??null}),yQ(Q);let G=jQ(),$=(Y.createBrokerEndpoint??N9)(G,Y.platform),B=i0.join(G,"broker.pid"),N=i0.join(G,"broker.log"),H=hQ({scriptPath:X,cwd:Q,endpoint:$,pidFile:B,logFile:N,env:Y.env??d3.env});if(!await V9($,Y.timeoutMs??2000))return J9({endpoint:$,pidFile:B,logFile:N,sessionDir:G,pid:H.pid??null,killProcess:Y.killProcess??null}),null;let J={endpoint:$,pidFile:B,logFile:N,sessionDir:G,pid:H.pid??null,version:W,scriptPath:X};return gQ(Q,J),J}function J9({endpoint:Q=null,pidFile:Y,logFile:X,sessionDir:W=null,pid:q=null,killProcess:K=null}){if(Number.isFinite(q)&&K)try{K(q)}catch{}if(Y&&g.existsSync(Y))g.unlinkSync(Y);if(X&&g.existsSync(X))g.unlinkSync(X);if(Q)try{let z=D2(Q);if(z.kind==="unix"&&g.existsSync(z.path))g.unlinkSync(z.path)}catch{}let G=W??(Y?i0.dirname(Y):X?i0.dirname(X):null);if(G&&g.existsSync(G))try{g.rmdirSync(G)}catch{}}import{spawnSync as uQ}from"node:child_process";import F2 from"node:process";function a2(Q,Y=[],X={}){let W=uQ(Q,Y,{cwd:X.cwd,env:X.env,encoding:"utf8",input:X.input,maxBuffer:X.maxBuffer,stdio:X.stdio??"pipe",shell:F2.platform==="win32"?F2.env.SHELL||!0:!1,windowsHide:!0});return{command:Q,args:Y,status:W.status??0,signal:W.signal??null,stdout:W.stdout??"",stderr:W.stderr??"",error:W.error??null}}function i3(Q,Y=["--version"],X={}){let W=a2(Q,Y,X);if(W.error&&W.error.code==="ENOENT")return{available:!1,detail:"not found"};if(W.error)return{available:!1,detail:W.error.message};if(W.status!==0)return{available:!1,detail:W.stderr.trim()||W.stdout.trim()||`exit ${W.status}`};return{available:!0,detail:W.stdout.trim()||W.stderr.trim()||"ok"}}function cQ(Q){return/not found|no running instance|cannot find|does not exist|no such process/i.test(Q)}function L9(Q,Y={}){if(!Number.isFinite(Q))return{attempted:!1,delivered:!1,method:null};let X=Q,W=Y.platform??F2.platform,q=Y.runCommandImpl??a2,K=Y.killImpl??F2.kill.bind(F2);if(W==="win32"){let G=q("taskkill",["/PID",String(X),"/T","/F"],{cwd:Y.cwd,env:Y.env});if(!G.error&&G.status===0)return{attempted:!0,delivered:!0,method:"taskkill",result:G};let z=`${G.stderr}
47
- ${G.stdout}`.trim();if(!G.error&&cQ(z))return{attempted:!0,delivered:!1,method:"taskkill",result:G};if(G.error?.code==="ENOENT")try{return K(X),{attempted:!0,delivered:!0,method:"kill"}}catch($){if($?.code==="ESRCH")return{attempted:!0,delivered:!1,method:"kill"};throw $}if(G.error)throw G.error;throw Error(fQ(G))}try{return K(-X,"SIGTERM"),{attempted:!0,delivered:!0,method:"process-group"}}catch(G){if(G?.code!=="ESRCH")try{return K(X,"SIGTERM"),{attempted:!0,delivered:!0,method:"process"}}catch(z){if(z?.code==="ESRCH")return{attempted:!0,delivered:!1,method:"process"};throw z}return{attempted:!0,delivered:!1,method:"process-group"}}}function fQ(Q){let Y=[`${Q.command} ${Q.args.join(" ")}`.trim()];if(Q.signal)Y.push(`signal=${Q.signal}`);else Y.push(`exit=${Q.status}`);let X=(Q.stderr||"").trim(),W=(Q.stdout||"").trim();if(X)Y.push(X);else if(W)Y.push(W);return Y.join(": ")}var s2="CODER_APP_SERVER_ENDPOINT",O9=-32001,dQ="0.144.1",t3;function nQ(){if(t3===void 0){let Q=a2("codex",["--version"]),Y=/(\d+\.\d+\.\d+(?:-[\w.]+)?)/.exec(`${Q.stdout} ${Q.stderr}`);t3=Y?Y[1]:dQ}return t3}function Z9(){return{title:"Coder",name:"coder",version:nQ()}}var A9={experimentalApi:!1,requestAttestation:!1,optOutNotificationMethods:["item/agentMessage/delta","item/reasoning/summaryTextDelta","item/reasoning/summaryPartAdded","item/reasoning/textDelta"]};function P9(Q,Y,X){return X===void 0?{code:Q,message:Y}:{code:Q,message:Y,data:X}}function a3(Q,Y){let X=Error(Q);if(X.data=Y,Y?.code!==void 0)X.rpcCode=Y.code;return X}class s3{cwd;options;pending;nextId;stderr;closed;exitError;notificationHandler;serverRequestHandler;lineBuffer;transport;exitPromise;exitResolved;resolveExit;handleServerRequest;constructor(Q,Y={}){this.cwd=Q,this.options=Y,this.pending=new Map,this.nextId=1,this.stderr="",this.closed=!1,this.exitError=null,this.notificationHandler=null,this.serverRequestHandler=null,this.lineBuffer="",this.transport="unknown",this.handleServerRequest=(X)=>this.defaultHandleServerRequest(X),this.exitPromise=new Promise((X)=>{this.resolveExit=X})}setNotificationHandler(Q){this.notificationHandler=Q}setServerRequestHandler(Q){this.serverRequestHandler=Q}request(Q,Y){if(this.closed)throw Error("codex app-server client is closed.");let X=this.nextId;return this.nextId+=1,new Promise((W,q)=>{this.pending.set(X,{resolve:W,reject:q,method:Q}),this.sendMessage({id:X,method:Q,params:Y})})}notify(Q,Y={}){if(this.closed)return;this.sendMessage({method:Q,params:Y})}handleChunk(Q){this.lineBuffer+=Q;let Y=this.lineBuffer.indexOf(`
48
- `);while(Y!==-1){let X=this.lineBuffer.slice(0,Y);this.lineBuffer=this.lineBuffer.slice(Y+1),this.handleLine(X),Y=this.lineBuffer.indexOf(`
49
- `)}}handleLine(Q){if(!Q.trim())return;let Y;try{Y=JSON.parse(Q)}catch(X){this.handleExit(a3(`Failed to parse codex app-server JSONL: ${X instanceof Error?X.message:String(X)}`,{line:Q}));return}if(Y.id!==void 0&&Y.method){this.handleServerRequest(Y);return}if(Y.id!==void 0){let X=this.pending.get(Y.id);if(!X)return;if(this.pending.delete(Y.id),Y.error)X.reject(a3(Y.error.message??`codex app-server ${X.method} failed.`,Y.error));else X.resolve(Y.result??{});return}if(Y.method&&this.notificationHandler)this.notificationHandler(Y)}defaultHandleServerRequest(Q){let Y=this.serverRequestHandler;if(!Y){this.sendMessage({id:Q.id,error:P9(-32601,`Unsupported server request: ${Q.method}`)});return}Promise.resolve().then(()=>Y(Q.method,Q.params??{})).then((X)=>{this.sendMessage({id:Q.id,result:X??{}})}).catch((X)=>{this.sendMessage({id:Q.id,error:P9(-32000,X instanceof Error?X.message:String(X))})})}handleExit(Q){if(this.exitResolved)return;this.exitResolved=!0,this.exitError=Q??null;for(let Y of this.pending.values())Y.reject(this.exitError??Error("codex app-server connection closed."));this.pending.clear(),this.resolveExit(void 0)}sendMessage(Q){throw Error("sendMessage must be implemented by subclasses.")}}class D9 extends s3{proc;readline;constructor(Q,Y={}){super(Q,Y);this.transport="direct"}async initialize(){this.proc=lQ("codex",["-c","sandbox_workspace_write.network_access=false","app-server","--disable","plugins"],{cwd:this.cwd,env:this.options.env??R2.env,stdio:["pipe","pipe","pipe"],shell:R2.platform==="win32"?R2.env.SHELL||!0:!1,windowsHide:!0});let Q=this.proc.stdout,Y=this.proc.stderr;if(!Q||!Y)throw Error("codex app-server did not expose stdio streams.");Q.setEncoding("utf8"),Y.setEncoding("utf8"),Y.on("data",(X)=>{this.stderr+=X}),this.proc.on("error",(X)=>{this.handleExit(X)}),this.proc.on("exit",(X,W)=>{let q=this.stderr.trim(),K=X===0?null:a3(`codex app-server exited unexpectedly (${W?`signal ${W}`:`exit ${X}`}).${q?`
50
- ${q}`:""}`);this.handleExit(K)}),this.readline=rQ.createInterface({input:Q}),this.readline.on("line",(X)=>{this.handleLine(X)}),await this.request("initialize",{clientInfo:this.options.clientInfo??Z9(),capabilities:this.options.capabilities??A9}),this.notify("initialized",{})}async close(){if(this.closed){await this.exitPromise;return}if(this.closed=!0,this.readline)this.readline.close();if(this.proc&&!this.proc.killed)this.proc.stdin?.end(),setTimeout(()=>{if(this.proc&&!this.proc.killed&&this.proc.exitCode===null)if(R2.platform==="win32")try{L9(this.proc.pid)}catch{}else this.proc.kill("SIGTERM")},50).unref?.();await this.exitPromise}sendMessage(Q){let Y=`${JSON.stringify(Q)}
51
- `,X=this.proc?.stdin;if(!X)throw Error("codex app-server stdin is not available.");X.write(Y)}}class F9 extends s3{endpoint;socket;constructor(Q,Y={}){super(Q,Y);this.transport="broker",this.endpoint=Y.brokerEndpoint}async initialize(){await new Promise((Q,Y)=>{let X=D2(this.endpoint);this.socket=pQ.createConnection({path:X.path}),this.socket.setEncoding("utf8"),this.socket.on("connect",Q),this.socket.on("data",(W)=>{this.handleChunk(W)}),this.socket.on("error",(W)=>{if(!this.exitResolved)Y(W);this.handleExit(W)}),this.socket.on("close",()=>{this.handleExit(this.exitError)})}),await this.request("initialize",{clientInfo:this.options.clientInfo??Z9(),capabilities:this.options.capabilities??A9}),this.notify("initialized",{})}async close(){if(this.closed){await this.exitPromise;return}if(this.closed=!0,this.socket)this.socket.end();await this.exitPromise}sendMessage(Q){let Y=`${JSON.stringify(Q)}
52
- `,X=this.socket;if(!X)throw Error("codex app-server broker connection is not connected.");X.write(Y)}}class x0{static async connect(Q,Y={}){let X=null;if(!Y.disableBroker){if(X=Y.brokerEndpoint??Y.env?.[s2]??R2.env[s2]??null,!X&&Y.reuseExistingBroker)X=o3(Q)?.endpoint??null;if(!X&&!Y.reuseExistingBroker)X=(await U9(Q,{env:Y.env}))?.endpoint??null}let W=X?new F9(Q,{...Y,brokerEndpoint:X}):new D9(Q,Y);return await W.initialize(),W}}var iQ="coder_runtime",R9="Coder Task";function tQ(Q){return Q.split(/\r?\n/).map((Y)=>Y.trimEnd()).filter((Y)=>Y&&!Y.startsWith("WARNING: proceeding, even though we could not update PATH:")).join(`
53
- `)}function aQ(Q,Y=72){let X=String(Q??"").trim().replace(/\s+/g," ");if(!X)return"";if(X.length<=Y)return X;return`${X.slice(0,Y-3)}...`}function sQ(Q){let Y=aQ(Q,56);return Y?`${R9}: ${Y}`:R9}function _9(Q){return Q?.params?.threadId??null}function eQ(Q){if(Q?.params?.turnId)return Q.params.turnId;if(Q?.params?.turn?.id)return Q.params.turn.id;return null}function QY(Q){let Y=new Set;for(let X of Q)for(let W of X.changes??[])if(W.path)Y.add(W.path);return[...Y]}function YY(Q){if(!Q||typeof Q!=="object")return null;let Y=(K)=>typeof K==="number"&&Number.isFinite(K)?K:0,X=Y(Q.inputTokens),W=Y(Q.cachedInputTokens),q=Y(Q.outputTokens);return{input:X,cachedInput:W,output:q,total:Y(Q.totalTokens)||X+W+q}}function XY(Q){if(Q.tokenUsageByThread.size===0)return null;let Y={input:0,cachedInput:0,output:0,total:0};for(let X of Q.tokenUsageByThread.values())Y.input+=X.input,Y.cachedInput+=X.cachedInput,Y.output+=X.output,Y.total+=X.total;return Y}function T9(Q){return String(Q??"").replace(/\s+/g," ").trim()}function t0(Q){if(!Q)return[];if(typeof Q==="string"){let Y=T9(Q);return Y?[Y]:[]}if(Array.isArray(Q))return Q.flatMap((Y)=>t0(Y));if(typeof Q==="object"){let Y=Q;if(typeof Y.text==="string")return t0(Y.text);if("summary"in Y)return t0(Y.summary);if("content"in Y)return t0(Y.content);if("parts"in Y)return t0(Y.parts)}return[]}function WY(Q,Y){let X=[];for(let W of[...Q,...Y]){let q=T9(W);if(!q||X.includes(q))continue;X.push(q)}return X}function R0(Q,Y,X=null,W={}){if(!Q||!Y)return;Q({message:Y,phase:X,...W})}function qY(Q){switch(Q.type){case"commandExecution":return{message:`Running command: ${String(Q.command??"").trim()}`,phase:"running"};case"fileChange":return{message:`Applying ${Q.changes.length} file change(s).`,phase:"editing"};case"mcpToolCall":return{message:`Calling ${Q.server}/${Q.tool}.`,phase:"investigating"};case"dynamicToolCall":return{message:`Running tool: ${Q.tool}.`,phase:"investigating"};case"webSearch":return{message:`Searching: ${String(Q.query??"").trim()}`,phase:"investigating"};default:return null}}function KY(Q){switch(Q.type){case"commandExecution":{let Y=String(Q.aggregatedOutput??"").trim();return{message:`Command ${Q.status==="completed"?"completed":Q.status}: ${String(Q.command??"").trim()} (exit ${Q.exitCode??"?"})`+(Y?`
54
- ${Y}`:""),phase:"running"}}case"fileChange":return{message:`File changes ${Q.status}.`,phase:"editing"};case"mcpToolCall":return{message:`Tool ${Q.server}/${Q.tool} ${Q.status}.`,phase:"investigating"};case"dynamicToolCall":return{message:`Tool ${Q.tool} ${Q.status}.`,phase:"investigating"};default:return null}}function zY(Q,Y={}){let X,W,q=new Promise((K,G)=>{X=K,W=G});return{threadId:Q,rootThreadId:Q,threadIds:new Set([Q]),threadTurnIds:new Map,turnId:null,bufferedNotifications:[],completion:q,resolveCompletion:X,rejectCompletion:W,finalTurn:null,completed:!1,finalAnswerSeen:!1,pendingCollaborations:new Set,activeSubagentTurns:new Set,completionTimer:null,lastAgentMessage:"",reasoningSummary:[],error:null,fileChanges:[],commandExecutions:[],tokenUsageByThread:new Map,itemIndex:new Map,onProgress:Y.onProgress??null,onHeartbeat:Y.onHeartbeat??null}}function Y4(Q){if(Q.completionTimer)clearTimeout(Q.completionTimer),Q.completionTimer=null}function X4(Q,Y=null){if(Q.completed)return;if(Y4(Q),Q.completed=!0,Y){if(Q.finalTurn=Y,!Q.turnId)Q.turnId=Y.id??null}else if(!Q.finalTurn)Q.finalTurn={id:Q.turnId??"inferred-turn",status:"completed"};Q.resolveCompletion(Q)}function Q4(Q){if(Q.completed||Q.finalTurn||!Q.finalAnswerSeen)return;if(Q.pendingCollaborations.size>0||Q.activeSubagentTurns.size>0)return;Y4(Q),Q.completionTimer=setTimeout(()=>{if(Q.completionTimer=null,Q.completed||Q.finalTurn||!Q.finalAnswerSeen)return;if(Q.pendingCollaborations.size>0||Q.activeSubagentTurns.size>0)return;X4(Q,null)},250),Q.completionTimer.unref?.()}function E9(Q,Y){let X=_9(Y);if(!X||!Q.threadIds.has(X))return!1;let W=Q.threadTurnIds.get(X)??null,q=eQ(Y);return W===null||q===null||q===W}function M9(Q,Y,X,W=null){if(Y.id)Q.itemIndex.set(Y.id,Y);if(Y.type==="collabAgentToolCall"){if(!W||W===Q.threadId){if(X==="started"||Y.status==="inProgress")Q.pendingCollaborations.add(Y.id);else if(X==="completed")Q.pendingCollaborations.delete(Y.id),Q4(Q)}for(let q of Y.receiverThreadIds??[])Q.threadIds.add(q)}if(Y.type==="agentMessage"){if(Y.text&&(!W||W===Q.threadId)){if(Q.lastAgentMessage=Y.text,X==="completed"&&Y.phase==="final_answer")Q.finalAnswerSeen=!0,Q4(Q)}return}if(Y.type==="reasoning"&&X==="completed"){Q.reasoningSummary=WY(Q.reasoningSummary,t0(Y.summary));return}if(Y.type==="fileChange"&&X==="completed"){Q.fileChanges.push(Y);return}if(Y.type==="commandExecution"&&X==="completed")Q.commandExecutions.push(Y)}function e3(Q,Y){switch(Q.onHeartbeat?.(),Y.method){case"thread/started":Q.threadIds.add(Y.params.thread.id);break;case"turn/started":if(Q.threadIds.add(Y.params.threadId),Q.threadTurnIds.set(Y.params.threadId,Y.params.turn.id),(Y.params.threadId??null)!==Q.threadId)Q.activeSubagentTurns.add(Y.params.threadId);R0(Q.onProgress,`Turn started (${Y.params.turn.id}).`,"starting",{threadId:Y.params.threadId??null,turnId:Y.params.turn.id??null});break;case"item/started":M9(Q,Y.params.item,"started",Y.params.threadId??null);{let X=qY(Y.params.item);R0(Q.onProgress,X?.message,X?.phase??null)}break;case"item/completed":M9(Q,Y.params.item,"completed",Y.params.threadId??null);{let X=KY(Y.params.item);R0(Q.onProgress,X?.message,X?.phase??null)}break;case"thread/tokenUsage/updated":{let X=YY(Y.params?.tokenUsage?.total??Y.params?.tokenUsage),W=_9(Y);if(X&&W)Q.tokenUsageByThread.set(W,X);break}case"error":Q.error=Y.params.error,R0(Q.onProgress,`Codex error: ${Y.params.error.message}`,"failed");break;case"turn/completed":if((Y.params.threadId??null)!==Q.threadId){Q.activeSubagentTurns.delete(Y.params.threadId),Q4(Q);break}R0(Q.onProgress,`Turn ${Y.params.turn.status}.`,"finalizing"),X4(Q,Y.params.turn);break;default:break}}async function GY(Q,Y,X,W={}){let q=zY(Y,W),K=Q.notificationHandler;Q.setNotificationHandler((z)=>{if(!q.turnId){q.bufferedNotifications.push(z);return}if(z.method==="thread/started"){e3(q,z);return}if(!E9(q,z)){K?.(z);return}e3(q,z)});let G=W.onApprovalRequest;if(G)Q.setServerRequestHandler((z,$)=>G(z,$,q));try{let z=await X();if(q.turnId=z.turn?.id??null,q.turnId)q.threadTurnIds.set(q.threadId,q.turnId);for(let $ of q.bufferedNotifications)if(E9(q,$))e3(q,$);else K?.($);if(q.bufferedNotifications.length=0,z.turn?.status&&z.turn.status!=="inProgress")X4(q,z.turn);return await q.completion}finally{Y4(q),Q.setNotificationHandler(K??null),Q.setServerRequestHandler(null)}}async function $Y(Q,Y){let X=null;try{X=await x0.connect(Q);let W=await Y(X);return await X.close(),W}catch(W){let q=W,K=X?.transport==="broker"||Boolean(process.env[s2]),G=X?.transport==="broker"&&q?.rpcCode===O9||K&&(q?.code==="ENOENT"||q?.code==="ECONNREFUSED");if(X)await X.close().catch(()=>{}),X=null;if(!G)throw W;let z=await x0.connect(Q,{disableBroker:!0});try{return await Y(z)}finally{await z.close()}}}function B0(Q){let Y=i3("codex",["--version"],{cwd:Q});if(!Y.available)return Y;let X=i3("codex",["app-server","--help"],{cwd:Q});if(!X.available)return{available:!1,detail:`${Y.detail}; app-server runtime unavailable: ${X.detail}`};return{available:!0,detail:`${Y.detail}; app-server runtime available`}}async function I9(Q){let Y=B0(Q);if(!Y.available)return{available:!1,loggedIn:!1,detail:Y.detail};let X=null;try{X=await x0.connect(Q,{reuseExistingBroker:!0});let W=await X.request("account/read",{refreshToken:!1}),q=W?.account??null;if(q?.type==="chatgpt")return{available:!0,loggedIn:!0,detail:q.email?`ChatGPT login active for ${q.email}`:"ChatGPT login active"};if(q?.type==="apiKey")return{available:!0,loggedIn:!0,detail:"API key configured"};if(W?.requiresOpenaiAuth===!1)return{available:!0,loggedIn:!0,detail:"Active provider does not require OpenAI authentication"};return{available:!0,loggedIn:!1,detail:"Not authenticated. Run `codex login`."}}catch(W){let q=oQ("codex",["login","status"],{encoding:"utf8"}),K=`${q.stdout??""}${q.stderr??""}`.trim();if(q.status===0)return{available:!0,loggedIn:!0,detail:K||"Logged in"};return{available:!0,loggedIn:!1,detail:K||(W instanceof Error?W.message:String(W))}}finally{await X?.close().catch(()=>{})}}async function w9(Q,{threadId:Y,turnId:X}){if(!Y||!X)return{interrupted:!1,detail:"missing threadId or turnId"};let W=null;try{return W=await x0.connect(Q,{reuseExistingBroker:!0}),await W.request("turn/interrupt",{threadId:Y,turnId:X}),{interrupted:!0,detail:`Interrupted ${X} on ${Y}.`}}catch(q){return{interrupted:!1,detail:q instanceof Error?q.message:String(q)}}finally{await W?.close().catch(()=>{})}}async function S9(Q,{threadId:Y,text:X}){if(!Y)return{steered:!1,detail:"missing threadId"};let W=X.trim();if(!W)return{steered:!1,detail:"empty follow-up"};let q=null;try{return q=await x0.connect(Q,{reuseExistingBroker:!0}),await q.request("turn/steer",{threadId:Y,input:[{type:"text",text:W,text_elements:[]}]}),{steered:!0,detail:`Steered follow-up into the active turn on ${Y}.`}}catch(K){return{steered:!1,detail:K instanceof Error?K.message:String(K)}}finally{await q?.close().catch(()=>{})}}async function C9(Q,Y={}){let X=B0(Q);if(!X.available)throw Error(`Codex CLI is not available: ${X.detail}`);let W=Y.prompt?.trim();if(!W)throw Error("A prompt is required.");return $Y(Q,async(q)=>{let K;if(Y.resumeThreadId){if(R0(Y.onProgress,`Resuming thread ${Y.resumeThreadId}.`,"starting"),I4(Y.resumeThreadId))await w4(Y.resumeThreadId);K=(await q.request("thread/resume",{threadId:Y.resumeThreadId,cwd:Q,model:Y.model??null,modelProvider:Y.modelProvider??null,config:Y.configOverrides??null,approvalPolicy:Y.approvalPolicy??"never",sandbox:Y.sandbox??"read-only"})).thread.id}else{R0(Y.onProgress,"Starting Codex task thread.","starting"),K=(await q.request("thread/start",{cwd:Q,model:Y.model??null,modelProvider:Y.modelProvider??null,config:Y.configOverrides??null,approvalPolicy:Y.approvalPolicy??"never",sandbox:Y.sandbox??"read-only",serviceName:iQ,ephemeral:Y.ephemeral??!1})).thread.id;try{await q.request("thread/name/set",{threadId:K,name:sQ(W)})}catch($){let B=String($?.message??$??"");if(!B.includes("unknown variant")&&!B.includes("unknown method"))throw $}}R0(Y.onProgress,`Thread ready (${K}).`,"starting",{threadId:K});let G=await GY(q,K,()=>q.request("turn/start",{threadId:K,input:[{type:"text",text:W,text_elements:[]}],model:Y.model??null,effort:Y.effort??null,outputSchema:Y.outputSchema??null}),{onProgress:Y.onProgress,onHeartbeat:Y.onHeartbeat,onApprovalRequest:Y.onApprovalRequest});return{status:G.finalTurn?.status==="completed"?0:1,threadId:K,turnId:G.turnId,finalMessage:G.lastAgentMessage,reasoningSummary:G.reasoningSummary,turn:G.finalTurn,error:G.error,stderr:tQ(q.stderr),fileChanges:G.fileChanges,touchedFiles:QY(G.fileChanges),tokens:XY(G),model:Y.model??null,commandExecutions:G.commandExecutions}})}import{spawn as PY,spawnSync as u9}from"node:child_process";import{randomUUID as OY}from"node:crypto";import E2 from"node:fs";import e2 from"node:path";var q4={chain:["codex","claude"],agents:{codex:{model:"gpt-5.6-terra",effort:"high",permissions:"auto"},claude:{model:"opus",effort:"medium",permissions:"auto"}},models:{},approvals:{escalationTimeoutMs:120000,allowedNetworkHosts:[]}},a0={spark:"gpt-5.3-codex-spark",luna:"gpt-5.6-luna",terra:"gpt-5.6-terra",sol:"gpt-5.6-sol"},K4=new Set(["low","medium","high"]),M2={sonnet:"sonnet",opus:"opus",fable:"fable"},z4=new Set(["low","medium","high"]),_2={"read-only":{sandbox:"read-only",approvalPolicy:"never",approvalMode:null},"workspace-write":{sandbox:"workspace-write",approvalPolicy:"never",approvalMode:null},auto:{sandbox:"workspace-write",approvalPolicy:"on-request",approvalMode:"auto"}},G4={"read-only":["--permission-mode","dontAsk","--disallowedTools","Edit","Write","NotebookEdit"],"workspace-write":["--permission-mode","acceptEdits"],auto:["--permission-mode","auto"]},x9=/failIfUnavailable|sandbox\b[^.\n]*?(?:failed|could ?n[o']t|cannot|unavailable|not available|not supported)/i;function k9(Q,Y){if(Q!=="read-only")return null;return JSON.stringify({sandbox:{enabled:!0,failIfUnavailable:!0,autoAllowBashIfSandboxed:!0,filesystem:{denyWrite:[Y]}}})}var s5=n0(["codex","claude"]),BY=n0(["codex","claude","custom"]),HY=n0(["low","medium","high"]),NY=n0(["read-only","workspace-write","auto"]),W4=A2(d0({model:P0().check(r0(1)),effort:HY,permissions:NY})),JY=d0({baseUrl:a1(),model:P0().check(r0(1)),envKey:d(P0().check(r0(1))),wireApi:d(n0(["chat","responses"]))}),j9=d0({escalationTimeoutMs:s1().check(I0()),allowedNetworkHosts:f3(P0())}),VY=d0({chain:f3(BY).check(r0(1)),agents:A2(d0({codex:W4,claude:W4,custom:W4})),models:d(q9(P0().check(u3(/^[a-z][a-z0-9-]*$/,"lowercase kebab-case")),JY)),approvals:j9}),UY=A2(W9(VY,{approvals:A2(j9)}));function s0(Q){let Y=UY.safeParse(Q);if(Y.success)return[];return Y.error.issues.map((X)=>{return`${X.path.join(".")||"config"}: ${X.message}`})}function v9(Q){if(!E2.existsSync(Q))return null;try{return JSON.parse(E2.readFileSync(Q,"utf8"))}catch(Y){let X=Y instanceof Error?Y.message:String(Y);throw Error(`Invalid JSON in ${Q}: ${X}`)}}function h9(Q,Y){if(!Y||typeof Y!=="object"||Array.isArray(Y))return Y??Q;let X={...Q},W=Q;for(let[q,K]of Object.entries(Y))if(K&&typeof K==="object"&&!Array.isArray(K)&&W?.[q]&&typeof W[q]==="object")X[q]=h9(W[q],K);else X[q]=K;return X}function N0(){return e2.join(M0(),"config.json")}function o(Q){let Y=Y0(Q),X=q4;for(let W of[N0(),e2.join(Y,"coder.config.json")]){let q=v9(W);if(!q)continue;let K=s0(q);if(K.length)throw Error(`Invalid config in ${W}:
55
- ${K.join(`
56
- `)}`);X=h9(X,q)}return X}function T2(Q){return Q.replace(/\/+$/,"").replace(/\/(chat\/completions|completions|responses)$/,"")}function b9(Q,Y,X){let W=[e2.join(Y0(Q),"coder.config.json"),N0()];for(let q of W){let K;try{K=v9(q)}catch{continue}if(!K?.models?.[Y])continue;if(Object.assign(K.models[Y],X),s0(K).length)return!1;return E2.writeFileSync(q,`${JSON.stringify(K,null,2)}
57
- `,"utf8"),!0}return!1}function LY(Q){return/\/(chat\/completions|completions|responses)\/*$/.test(Q)}function e0(Q,Y){let X=T2(Q);if(LY(Q)||/\/v\d+(alpha|beta)?$/.test(X))return[`${X}/${Y}`];return[`${X}/${Y}`,`${X}/v1/${Y}`]}function g9(Q,Y,X){let W=Y?Q.models?.[Y]:void 0;if(!Y||!W)return null;let q=`coder-${Y}`;return{model:W.model,modelProvider:q,configOverrides:{[`model_providers.${q}`]:{name:Y,base_url:X?.url??T2(W.baseUrl),...W.envKey&&!X?{env_key:W.envKey}:{},wire_api:"responses"}}}}function y9(Q){if(!Q)return null;return a0[Q]??Q}function m9(Q){let Y=N0();return E2.mkdirSync(e2.dirname(Y),{recursive:!0}),E2.writeFileSync(Y,`${JSON.stringify(Q,null,2)}
58
- `,"utf8"),Y}function ZY(Q){if(typeof Q==="string")return Q;if(Array.isArray(Q))return Q.map((Y)=>typeof Y?.text==="string"?Y.text:"").join("");return Q==null?"":JSON.stringify(Q)}function AY(Q){if(!Q||typeof Q!=="object")return null;let Y=(K)=>typeof K==="number"&&Number.isFinite(K)?K:0,X=Y(Q.input_tokens),W=Y(Q.cache_read_input_tokens)+Y(Q.cache_creation_input_tokens),q=Y(Q.output_tokens);return{input:X,cachedInput:W,output:q,total:X+W+q}}function Q2(){let Q=u9("claude",["--version"],{encoding:"utf8"});if(Q.error||Q.status!==0)return{available:!1,detail:"claude CLI not found on PATH (npm install -g @anthropic-ai/claude-code)"};return{available:!0,detail:String(Q.stdout||"").trim()}}function c9(){let Q=u9("claude",["auth","status","--json"],{encoding:"utf8"});if(Q.error||Q.status!==0)return{loggedIn:!1,detail:"not logged in"};try{let Y=JSON.parse(String(Q.stdout||""));if(!Y.loggedIn)return{loggedIn:!1,detail:"not logged in"};return{loggedIn:!0,detail:[Y.email,Y.subscriptionType].filter(Boolean).join(", ")||"logged in"}}catch{return{loggedIn:!1,detail:"unknown"}}}async function f9(Q,Y){let X=Y.resumeSessionId??OY(),W=["-p",Y.prompt,"--output-format","stream-json","--verbose"];if(W.push(Y.resumeSessionId?"--resume":"--session-id",X),Y.model)W.push("--model",Y.model);if(Y.effort)W.push("--effort",Y.effort);let q=Y.permissions??"auto";W.push(...G4[q]??G4.auto);let K=k9(q,Q);if(K)W.push("--settings",K);return Y.onProgress?.({message:`claude turn started (session ${X})`,threadId:X}),new Promise((G,z)=>{let $=PY("claude",W,{cwd:Q,stdio:["ignore","pipe","pipe"]}),B="",N="",H=null,V=X,J=(L)=>{if(!L||typeof L!=="object")return;if(Y.onHeartbeat?.(),L.type==="system"&&L.subtype==="init"&&L.session_id)V=L.session_id;else if(L.type==="assistant"){for(let P of L.message?.content??[])if(P?.type==="tool_use")Y.onProgress?.({message:`${P.name} ${JSON.stringify(P.input??{})}`,threadId:V})}else if(L.type==="user"){for(let P of L.message?.content??[])if(P?.type==="tool_result"){let Z=ZY(P.content).trim();if(Z)Y.onProgress?.({message:Z,threadId:V})}}else if(L.type==="result"){if(H=L,L.session_id)V=L.session_id}};$.stdout.on("data",(L)=>{B+=L;let P;while((P=B.indexOf(`
59
- `))>=0){let Z=B.slice(0,P).trim();if(B=B.slice(P+1),!Z)continue;try{J(JSON.parse(Z))}catch{}}}),$.stderr.on("data",(L)=>{N+=L});let U=()=>{$.kill("SIGTERM"),process.exit(143)};process.on("SIGTERM",U),$.on("error",(L)=>{process.removeListener("SIGTERM",U),z(Error(`claude spawn failed: ${L.message}`))}),$.on("close",(L)=>{process.removeListener("SIGTERM",U);let P=B.trim();if(P)try{J(JSON.parse(P))}catch{}let Z=H?.result??"",A=L!==0||H?.is_error===!0||H==null;G({status:A?1:0,threadId:H?.session_id??V,turnId:null,finalMessage:Z,tokens:AY(H?.usage),model:H?.modelUsage&&Object.keys(H.modelUsage).join("+")||Y.model||null,error:A?{message:Z||N.trim()||`claude exited ${L}`}:null})})})}import Y2 from"node:fs";import DY from"node:os";import Q3 from"node:path";import{spawnSync as X2}from"node:child_process";function Y3(Q){X2("claude",["plugin","marketplace","remove","coder-plugins"],{encoding:"utf8"});let Y=X2("claude",["plugin","marketplace","add",Q],{encoding:"utf8"}),X=X2("claude",["plugin","install","coder@coder-plugins"],{encoding:"utf8"}),W=Y.status===0&&X.status===0;return{marketplace:Q,installed:W,note:W?"Plugin installed; restart any running Claude Code session to load it.":`Automatic install failed (${(X.stderr||Y.stderr||"claude not found").trim()}); run: claude plugin marketplace add "${Q}" && claude plugin install coder@coder-plugins`}}function X3(){return Q3.join(DY.homedir(),".agents","skills","coder")}function $4(){try{let Q=Y2.readFileSync(Q3.join(X3(),"SKILL.md"),"utf8");return/^\s*version:\s*(\S+)/m.exec(Q)?.[1]??null}catch{return null}}function W3(Q){let Y=X3();try{let X=Q3.join(Q,"plugins","agents","skills","coder");Y2.rmSync(Y,{recursive:!0,force:!0}),Y2.mkdirSync(Y,{recursive:!0}),Y2.cpSync(X,Y,{recursive:!0});let W=Q3.join(Y,"SKILL.md"),q=Y2.readFileSync(W,"utf8").replace(`
60
- ---
61
- `,`
62
- metadata:
63
- version: ${a()}
64
- ---
65
- `);return Y2.writeFileSync(W,q),{marketplace:Y,installed:!0,note:"Skill installed to ~/.agents/skills/coder; restart running sessions to load it."}}catch(X){return{marketplace:Y,installed:!1,note:`Skill install failed: ${X instanceof Error?X.message:String(X)}`}}}function q3(Q){if(Q.available)return null;let Y=X2("npm",["install","-g","@openai/codex@latest"],{encoding:"utf8"});return Y.status===0?{installed:!0,note:"codex CLI installed (runs your custom models; no login needed for them)"}:{installed:!1,note:`custom models run on the codex CLI and it is not installed; auto-install failed: ${(Y.stderr||"npm not found").trim()}. Run: npm install -g @openai/codex`}}var p9="0.144.0";function FY(Q){let Y=/(\d+\.\d+\.\d+)/.exec(String(Q??""));return Y?Y[1]:null}function l9(Q){if(!Q.available)return null;let Y=FY(Q.detail);if(!Y||D3(Y,p9)>=0)return null;let X=X2("codex",["update"],{encoding:"utf8"});if(X.status!==0)X=X2("npm",["install","-g","@openai/codex@latest"],{encoding:"utf8"});return X.status===0?{updated:!0,from:Y}:{updated:!1,from:Y,note:`codex ${Y} is too old for the default GPT-5.6 model (needs >= ${p9}); auto-update failed: ${(X.stderr||"codex/npm not found").trim()}. Run: codex update`}}import RY from"node:http";import EY from"node:process";var MY=0;function _Y(Q){let Y=[];if(typeof Q.instructions==="string"&&Q.instructions)Y.push({role:"system",content:Q.instructions});let X=Array.isArray(Q.input)?Q.input:[];for(let W of X)switch(W?.type){case"message":{let q=Array.isArray(W.content)?W.content.map((K)=>K?.text??"").join(""):String(W.content??"");Y.push({role:W.role==="developer"?"system":W.role,content:q});break}case"function_call":{let q={id:W.call_id,type:"function",function:{name:W.name,arguments:W.arguments??"{}"}},K=Y.at(-1);if(K?.role==="assistant"&&K.tool_calls)K.tool_calls.push(q);else Y.push({role:"assistant",content:null,tool_calls:[q]});break}case"function_call_output":{let q=W.output;Y.push({role:"tool",tool_call_id:W.call_id,content:typeof q==="string"?q:JSON.stringify(q??"")});break}default:break}return Y}function TY(Q){let Y=(Array.isArray(Q.tools)?Q.tools:[]).filter((W)=>W?.type==="function").map((W)=>({type:"function",function:{name:W.name,description:W.description??"",parameters:W.parameters??{type:"object",properties:{}}}})),X=Q.text?.format;return{model:Q.model,messages:_Y(Q),...Y.length?{tools:Y,tool_choice:Q.tool_choice??"auto"}:{},...typeof Q.parallel_tool_calls==="boolean"?{parallel_tool_calls:Q.parallel_tool_calls}:{},...X?.type==="json_schema"?{response_format:{type:"json_schema",json_schema:{name:X.name,schema:X.schema,strict:X.strict??!1}}}:{},stream:!0,stream_options:{include_usage:!0}}}class r9{send;model;responseId=`resp_bridge_${++MY}`;text="";textOpen=!1;toolCalls=new Map;usage=null;buffer="";constructor(Q,Y){this.model=Q,this.send=Y,this.send({type:"response.created",response:{id:this.responseId,object:"response",status:"in_progress",model:Q,output:[]}})}push(Q){this.buffer+=Q;let Y=this.buffer.split(`
66
- `);this.buffer=Y.pop()??"";for(let X of Y){let W=X.trim();if(!W.startsWith("data:"))continue;let q=W.slice(5).trim();if(!q||q==="[DONE]")continue;let K;try{K=JSON.parse(q)}catch{continue}if(K.usage)this.usage=K.usage;let G=K.choices?.[0]?.delta;if(!G)continue;if(typeof G.content==="string"&&G.content){if(!this.textOpen)this.textOpen=!0,this.send({type:"response.output_item.added",output_index:0,item:{type:"message",id:"msg_bridge_0",status:"in_progress",role:"assistant",content:[]}});this.text+=G.content,this.send({type:"response.output_text.delta",item_id:"msg_bridge_0",output_index:0,content_index:0,delta:G.content})}for(let z of G.tool_calls??[]){let $=this.toolCalls.get(z.index)??{id:"",name:"",args:""};if(z.id)$.id=z.id;if(z.function?.name)$.name+=z.function.name;if(z.function?.arguments)$.args+=z.function.arguments;this.toolCalls.set(z.index,$)}}}finish(){let Q=[];if(this.text){let X={type:"message",id:"msg_bridge_0",status:"completed",role:"assistant",content:[{type:"output_text",text:this.text,annotations:[]}]};Q.push(X),this.send({type:"response.output_item.done",output_index:0,item:X})}let Y=Q.length;for(let X of this.toolCalls.values()){let W={type:"function_call",id:`fc_bridge_${Y}`,call_id:X.id||`call_bridge_${Y}`,name:X.name,arguments:X.args||"{}",status:"completed"};Q.push(W),this.send({type:"response.output_item.done",output_index:Y,item:W}),Y+=1}this.send({type:"response.completed",response:{id:this.responseId,object:"response",status:"completed",model:this.model,output:Q,usage:{input_tokens:this.usage?.prompt_tokens??0,input_tokens_details:{cached_tokens:this.usage?.prompt_tokens_details?.cached_tokens??0},output_tokens:this.usage?.completion_tokens??0,output_tokens_details:{reasoning_tokens:this.usage?.completion_tokens_details?.reasoning_tokens??0},total_tokens:this.usage?.total_tokens??0}}})}}async function d9(Q,Y="chat"){let X=Y==="responses",W=e0(Q.baseUrl,X?"responses":"chat/completions"),q=null,K=Q.envKey?EY.env[Q.envKey]:void 0;async function G(N){let H=q?[q]:W,V=null;for(let J of H)if(V=await fetch(J,{method:"POST",headers:{"content-type":"application/json",...K?{authorization:`Bearer ${K}`}:{}},body:N}),V.status!==404)return q=J,V;return V}let z=RY.createServer((N,H)=>{if(N.method!=="POST"||!N.url?.replace(/\/+$/,"").endsWith("/responses")){H.writeHead(404,{"content-type":"application/json"}),H.end(JSON.stringify({error:{message:"coder chat bridge: only POST /responses is supported"}}));return}let V="";N.on("data",(J)=>V+=J),N.on("end",async()=>{let J;try{J=JSON.parse(V)}catch{H.writeHead(400,{"content-type":"application/json"}),H.end(JSON.stringify({error:{message:"invalid JSON"}}));return}try{if(X){let Z=await G(V);if(H.writeHead(Z.status,{"content-type":Z.headers.get("content-type")??"application/json","cache-control":"no-store"}),Z.body)for await(let A of Z.body)H.write(A);H.end();return}let U=await G(JSON.stringify(TY(J)));if(!U.ok||!U.body){let Z=await U.text().catch(()=>"");H.writeHead(U.status,{"content-type":"application/json"}),H.end(Z||JSON.stringify({error:{message:`upstream HTTP ${U.status}`}}));return}H.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-store"});let L=new r9(J.model,(Z)=>H.write(`data: ${JSON.stringify(Z)}
67
-
68
- `)),P=new TextDecoder;for await(let Z of U.body)L.push(P.decode(Z,{stream:!0}));L.finish(),H.end()}catch(U){let L=U instanceof Error?U.message:String(U);H.writeHead(502,{"content-type":"application/json"}),H.end(JSON.stringify({error:{message:`coder chat bridge: ${L}`}}))}})});await new Promise((N)=>z.listen(0,"127.0.0.1",N));let $=z.address();return{url:`http://127.0.0.1:${typeof $==="object"&&$?$.port:0}/v1`,close:()=>new Promise((N)=>{z.close(()=>N()),z.closeAllConnections?.()})}}import IY from"node:process";async function n9(Q,Y,X){let W=Q.envKey?IY.env[Q.envKey]:void 0,q=!1;for(let K of e0(Q.baseUrl,Y))try{let G=await fetch(K,{method:"POST",headers:{"content-type":"application/json",...W?{Authorization:`Bearer ${W}`}:{}},body:JSON.stringify(X),signal:AbortSignal.timeout(5000)});if(q=!0,G.status!==404&&G.status!==405&&G.status!==501)return{baseUrl:K.slice(0,-(Y.length+1))}}catch{}return{reachable:q}}async function K3(Q){let Y=await n9(Q,"responses",{model:Q.model,input:[],stream:!1});if("baseUrl"in Y)return{wireApi:"responses",baseUrl:Y.baseUrl};let X=await n9(Q,"chat/completions",{model:Q.model,messages:[],stream:!1});if("baseUrl"in X)return{wireApi:"chat",baseUrl:X.baseUrl};return Y.reachable||X.reachable?{wireApi:"chat"}:null}var o9=/usage|quota|rate.?limit|429|401|unauthorized|not authenticated|login|insufficient|exhausted|not available|ENOENT/i,i9="CODER_WORKER",SY=`
69
- You are running inside a coder task: do the work yourself, directly.
70
- Do not load the coder skill (recursive), and never dispatch through the \`coder\` CLI - nested dispatch is disabled.
71
- When finished, provide a concise implementation result summary.
72
- `.trim();function t9(Q){if(Q.resumeThreadId)return Q.prompt??"";let Y=Q.system?`
73
- -------
74
- ${Q.system}`:"";return`<system>
75
- ${SY}${Y}
76
- </system>
77
-
78
- ${Q.prompt??""}`}function CY(Q,Y){let X=Q.agent;if(!X&&Q.model){if(Q.model in M2)X="claude";else if(Q.model in a0)X="codex";else if(Q.model in(Y.models??{}))X="custom"}if(X=X??Y.chain[0]??"codex",X!=="codex"&&X!=="claude"&&X!=="custom"){let $=X in a0||X in M2||X in(Y.models??{})?` "${X}" is a model; use --model ${X}.`:"";D(`Invalid --agent "${X}". Use codex, claude, or custom.${$}`)}let W=Y.agents[X]??{},q=Q.model??W.model??null,K=Q.effort??W.effort??null,G=Q.permissions??W.permissions??"auto";if(X==="custom"){let $=Object.keys(Y.models??{});if(!q&&$.length===1)q=$[0];if(!q||!(q in(Y.models??{})))D(q?`No custom model named "${q}". Configured: ${$.join(", ")||"none"}.`:"No custom model to run: pass --model <name> or set agents.custom.model.",{hint:"Add one: coder model add <name> --base-url <url> --model <id>"})}let z=X==="claude"?"claude":"codex";if(!(G in _2))D(`Invalid --permissions "${G}". Use one of: ${Object.keys(_2).join(", ")}`);if(z==="codex"&&K&&!K4.has(K))D(`Invalid codex --effort "${K}". Use one of: ${[...K4].join(", ")}`);if(z==="claude"&&K&&!z4.has(K))D(`Invalid claude --effort "${K}". Use one of: ${[...z4].join(", ")}`);return{engine:z,agent:X,model:q,effort:K,permissions:G}}function a9(Q,Y){let X=0;return()=>{if(Date.now()-X>=1e4)X=Date.now(),h4(Q,Y)}}function s9(Q,Y,{echo:X}){return(W)=>{let q=typeof W==="string"?{message:W}:W;if(V0(Q,Y,q),X&&q.message)v.stderr.write(`[coder] ${q.message}
79
- `)}}async function xY(Q,Y,{echo:X}){let W=Y0(Q),q=C(Q,Y.id),K=o(Q),G=s9(Q,Y.id,{echo:X}),z=_2[Y.permissions??"auto"]??_2.auto,$=z.approvalPolicy==="never"?void 0:B9({workspaceRoot:W,jobDir:q,mode:z.approvalMode,escalationTimeoutMs:K.approvals.escalationTimeoutMs,allowedNetworkHosts:K.approvals.allowedNetworkHosts,onEvent:(V)=>{if(V0(Q,Y.id,V),X&&V.message)v.stderr.write(`[coder] ${V.message}
80
- `)}}),B=Y.model?K.models?.[Y.model]:void 0;if(B&&!B.wireApi&&Y.model){let V=await K3(B);if(V)B={...B,...V},K.models[Y.model]=B,b9(Q,Y.model,V),V0(Q,Y.id,{kind:"info",message:`detected wire api for ${Y.model}: ${V.wireApi} @ ${B.baseUrl}`})}if(B?.envKey&&!v.env[B.envKey])throw Error(`Missing environment variable: \`${B.envKey}\`.`);let N=B?await d9(B,B.wireApi??"chat"):null,H=g9(K,Y.model,N??void 0);try{let V=await C9(Q,{prompt:t9(Y),model:H?.model??y9(Y.model),modelProvider:H?.modelProvider??null,configOverrides:H?.configOverrides??null,effort:Y.effort,sandbox:z.sandbox,approvalPolicy:z.approvalPolicy,onApprovalRequest:$,onHeartbeat:a9(Q,Y.id),resumeThreadId:Y.resumeThreadId??null,onProgress:(U)=>{G(U);let L=typeof U==="object"?U.threadId:null,P=typeof U==="object"?U.turnId:null;if(L||P)m(Q,Y.id,{status:"running",...L?{threadId:L}:{},...P?{turnId:P}:{}})}}),J=V.status===0?"completed":"failed";return m(Q,Y.id,{status:J,threadId:V.threadId,turnId:V.turnId,completedAt:new Date().toISOString()}),E0.writeFileSync(I2.join(q,"result.json"),`${JSON.stringify(V,null,2)}
81
- `,"utf8"),V}finally{await N?.close()}}async function kY(Q,Y,{echo:X}){let W=C(Q,Y.id),q=s9(Q,Y.id,{echo:X}),K=await f9(Q,{prompt:t9(Y),model:Y.model,effort:Y.effort,permissions:Y.permissions,resumeSessionId:Y.resumeThreadId??null,onHeartbeat:a9(Q,Y.id),onProgress:(G)=>{if(q(G),G.threadId)m(Q,Y.id,{status:"running",threadId:G.threadId})}});return m(Q,Y.id,{status:K.status===0?"completed":"failed",threadId:K.threadId,completedAt:new Date().toISOString()}),E0.writeFileSync(I2.join(W,"result.json"),`${JSON.stringify(K,null,2)}
82
- `,"utf8"),K}function e9(Q){return Q.engine==="claude"?kY:xY}async function jY(Q,Y){for(let X=0;X<2;){let W=r(Q,Y);if(!W||W.status==="failed"||W.status==="cancelled")return;let q=m4(Q,Y);if(q.length===0){X+=1,await new Promise((K)=>setTimeout(K,300));continue}X=0;for(let K of q){let G=m(Q,Y,{status:"running",prompt:K,resumeThreadId:W.threadId??null});V0(Q,Y,{message:"Running steered follow-up."});try{await e9(G)(Q,G,{echo:!1})}catch(z){let $=z instanceof Error?z.message:String(z);m(Q,Y,{status:"failed",error:$}),V0(Q,Y,{kind:"error",message:$});return}}}}async function W2(Q){if(v.env[i9])D("Nested dispatch refused: this shell is already inside a coder task. Do the work yourself, directly in this session - ignore any skill or instruction telling you to orchestrate via the coder CLI.");let{options:Y,positionals:X}=T(Q,S({...b,agent:j,model:j,effort:j,permissions:j,resume:j,host:j,name:j,system:j,background:_,wait:_,"simulate-approval":_})),W=I(Y),q=X.join(" ").trim();if(!q)D("Missing task text.",{hint:['Usage: coder run "<task text>"',"Help: coder task run --help"]});let K=o(W),G=CY(Y,K),z=async(M,u)=>{let c=K.chain[K.chain.indexOf(M)+1];if(!c)E({error:`${M} failed to start: ${u}`,fallback:{action:"run-native-subagent",reason:"no-engine-available",permissions:G.permissions,note:"Every coder engine failed to start. Spawn your own native subagent and forward the task verbatim; tell it to never run git write operations (commit, checkout, stash, reset, push, ...) and to honor the permissions.",...Y.system?{system:Y.system}:{},task:q}}),v.exit(3);v.stderr.write(`[coder] ${M} failed to start (${u}); falling back to ${c}.
83
- `),await W2([q,"--agent",c,"--cwd",W,...Y.wait?["--wait"]:[],...Y.json?["--json"]:[],...Y.permissions?["--permissions",Y.permissions]:[],...Y.system?["--system",Y.system]:[]]),v.exit(0)},$=(M)=>{let u="read-only unavailable on this host: the OS sandbox failed to start (Linux/WSL2 needs bubblewrap + socat). Re-dispatch with --permissions auto (or workspace-write) if writes are acceptable, or install the sandbox deps.";if(Y.json)E({error:u,code:"read-only-unavailable",detail:M});else v.stderr.write(`[coder] ${u}
84
- `);v.exit(1)},B=(M)=>G.permissions==="read-only"&&x9.test(M??"");{let M=G.engine==="codex"?B0(W):Q2();if(!M.available&&G.model&&G.model in(K.models??{})){let u=q3(M);v.stderr.write(`[coder] ${u.note}
85
- `),M=B0(W)}if(!M.available)await z(G.agent,M.detail)}let N=null;if(Y.resume)N=y0(W,Y.resume)?.threadId??Y.resume;let H=j4(),V=m(W,H,{status:"queued",kind:"task",name:Y.name??null,system:Y.system??null,agent:G.agent,engine:G.engine,prompt:q,model:G.model,effort:G.effort,permissions:G.permissions,resumeThreadId:N,cwd:W,background:!Y.wait,...Y["simulate-approval"]?{simulateApproval:!0}:{}}),J=C(W,H),U=E0.openSync(I2.join(J,"worker.log"),"a"),L=wY(v.execPath,[A0,"_worker",H,"--cwd",W],{cwd:W,detached:!0,stdio:["ignore",U,U],env:{...v.env,[i9]:"1"}});L.unref(),E0.closeSync(U),m(W,H,{pid:L.pid??null});let P=Number.MAX_SAFE_INTEGER,Z=Date.now()+15000,A=V,R=null,y=null;while(Date.now()<(y??Z)){if(A=r(W,H)??A,A.status==="failed"||A.status==="completed")break;if(A.threadId&&R===null)R=H0(W,H,P).length,y=Date.now()+2000;if(R!==null&&H0(W,H,P).length>R){A=r(W,H)??A;break}await new Promise((M)=>setTimeout(M,150))}if(A.status==="failed"){let M=I2.join(J,"result.json"),u=E0.existsSync(M)?JSON.parse(E0.readFileSync(M,"utf8")).error?.message??"":"",c=H0(W,H,5).map((Q0)=>Q0.message??"").join(`
86
- `),i=u||c;if(B(i))$(i);if(o9.test(i))await z(G.agent,i);if(Y.json)E({taskId:H,status:"failed",detail:i}),v.exit(1);D(`Task ${H} failed to start.${i?`
87
- ${i}`:""}`,{hint:`See: coder task result ${H}`})}let z0=[` result: coder task result ${H}`,` steer: coder task steer ${H} "<follow-up>"`].join(`
88
- `);if(Y.wait){if(!Y.json)v.stderr.write(`${O.dim("[coder]")} task ${O.cyan(H)} started (${A.status}); waiting for it to finish — Ctrl-C to detach (it keeps running).
89
- `),v.stderr.write(`${O.dim(z0)}
90
- `);let M=()=>{v.stderr.write(`
91
- ${O.dim(`[coder] detached — task still running: coder task result ${H}`)}
92
- `),v.exit(130)};v.on("SIGINT",M);let u=await t2(W,A);if(v.off("SIGINT",M),u.reason==="approval")y2(H,u.approval,Y.json);let c=u.job,i=I2.join(J,"result.json"),Q0=E0.existsSync(i)?JSON.parse(E0.readFileSync(i,"utf8")):null,w=Q0?.error?.message??"";if(c.status==="failed"&&B(w))$(w);if(c.status==="failed"&&o9.test(w))await z(G.agent,w);if(Y.json)E({taskId:H,status:c.status,finalMessage:Q0?.finalMessage,...w?{error:w}:{},tokens:Q0?.tokens??null,model:Q0?.model??c.model??null});else{v.stdout.write(`
93
- ${Q0?.finalMessage||(w?`${O.red("error:")} ${w}`:"(no final message)")}
94
-
95
- `);let t=Q0?.tokens?` tokens=${u0(Q0.tokens,Q0.model??c.model)}`:"";v.stderr.write(`${O.dim(`[coder] task=${H} status=${c.status}${t}`)}
96
- `)}v.exit(c.status==="completed"?0:1)}if(Y.json){E({taskId:H,status:A.status,startupCheck:A.threadId?"passed":"pending",commands:{result:`coder task result ${H}`,steer:`coder task steer ${H} "<follow-up>"`,stop:`coder task stop ${H}`,watch:`coder task stream ${H}`}});return}v.stdout.write(`${O.dim("[coder]")} task ${O.cyan(H)} started in the background (${A.status}).
97
- `),v.stdout.write(`${O.dim(z0)}
98
- `)}async function Q8(Q){let{options:Y,positionals:X}=T(Q,S({cwd:j})),W=I(Y),q=X[0],K=r(W,q);if(!K)D(`Worker: task ${q} not found.`);m(W,q,{status:"running",pid:v.pid});try{if(K.simulateApproval){let G=await $9(C(W,q),{onEvent:(z)=>V0(W,q,z)});if(V0(W,q,{message:`simulated approval: ${G}`}),G==="decline"){m(W,q,{status:"cancelled",completedAt:new Date().toISOString(),error:"simulated approval denied"});return}}await e9(K)(W,K,{echo:!1}),await jY(W,q)}catch(G){let z=G instanceof Error?G.message:String(G);m(W,q,{status:"failed",error:z}),V0(W,q,{kind:"error",message:z}),v.exit(1)}}import Y8 from"node:fs";import vY from"node:path";import z3 from"node:process";async function B4(Q){let{options:Y,positionals:X}=T(Q,S({...b,tail:d(S0([C0("all"),O0.number().check(w0(),Z2())],{error:'expected a number or "all"'})),wait:_}));f(X,1,"task result");let W=I(Y),q=p(W,X[0]);if(Y.wait){if(J0.includes(q.status))z3.stderr.write(`${O.dim(`[coder] waiting for task ${q.id} to finish...`)}
99
- `);let A=await t2(W,q);if(q=A.job,A.reason==="approval")y2(q.id,A.approval,Y.json)}let K=Y.tail===void 0?0:Y.tail==="all"?Number.MAX_SAFE_INTEGER:Y.tail,G=K>0?H0(W,q.id,K):[],z=o0(C(W,q.id)).filter((A)=>!A.response),$=vY.join(C(W,q.id),"result.json"),B=Y8.existsSync($)?JSON.parse(Y8.readFileSync($,"utf8")):null,N=J0.includes(q.status),H=N?H0(W,q.id,1)[0]:void 0,V=N?x2(W,q):q.updatedAt,J=B2(V),U=N&&z.length===0&&J>b2,L=()=>{if(Y.wait)z3.exit(q.status==="completed"?0:1)};if(Y.json)return E({taskId:q.id,name:q.name??null,prompt:q.prompt??null,system:q.system??null,status:q.status,agent:q.agent,model:q.model??null,...N?{idleMs:J,lastActivityAt:V??null,stalled:U}:{},pendingApprovals:z.map((A)=>({id:A.id,summary:A.summary})),...G.length?{steps:G}:{},result:B}),L();let P=O,Z=[`${P.dim("task")} ${P.cyan(q.id)}`,...q.name?[`${P.dim("name")} ${q.name}`]:[],`${P.dim("status")} ${g2(q.status)}`,`${P.dim("agent")} ${(q.agent??"-")+(q.model?`/${q.model}`:"")}`,...B?.tokens?[`${P.dim("tokens")} ${u0(B.tokens,B.model??q.model)}`]:[]];if(q.prompt)Z.push("",...h2(q.prompt,P));if(z.length){Z.push("",P.dim("pending approvals:"));for(let A of z)Z.push(` ${P.cyan(A.id)} ${A.summary}`)}if(G.length){Z.push("",P.dim("steps:"));for(let A of G){let R=A.message??A.kind;if(R)Z.push(` ${P.dim(c0(R))}`)}}if(N&&H){let A=H.message??H.kind??"";Z.push(`${P.dim("last")} ${P.dim(`${c0(A)} (${H2(J)} ago)`)}`)}if(Z.push(""),B)Z.push(v2(B,q.error,"(no final message)",P));else if(N)Z.push(P.dim(U?`Result pending, but no progress for ${H2(J)} — the task may be stalled.`:"Result pending — task is still running."));else Z.push(P.dim("(no result)"));if(N&&!Y.wait){let A=[`Wait for it: coder task result ${q.id} --wait`,`Follow live: coder task stream ${q.id}`];if(U)A.push(`Check the transcript: coder task result ${q.id} --tail all`);Z.push("",_0(A,P))}if(z3.stdout.write(`${Z.join(`
100
- `)}
101
- `),B?.touchedFiles?.length)z3.stderr.write(`[coder] touched files: ${B.touchedFiles.join(", ")}
102
- `);return L()}import X8 from"node:fs";import hY from"node:path";import k0 from"node:process";async function G3(Q){let{options:Y,positionals:X}=T(Q,S({...b,tail:d(S0([C0("all"),O0.number().check(w0(),Z2())],{error:'expected a number or "all"'})),trim:d(S0([C0("none"),O0.number().check(w0(),I0())],{error:'expected a positive integer or "none"'}))}));f(X,1,"task stream");let W=I(Y),q=p(W,X[0]),K=new Set(["completed","failed","cancelled"]),G=Number.MAX_SAFE_INTEGER,z=Y.tail,$=z===void 0?1:z==="all"?G:z,B=Y.trim,N=B===void 0?_3:B==="none"?Number.MAX_SAFE_INTEGER:B,H=Math.max(0,H0(W,q.id,G).length-$),V=()=>{let P=H0(W,q.id,G);for(let Z of P.slice(H))if(Y.json){let A=Z.message?{...Z,message:c0(Z.message,N,{plain:!0})}:Z;k0.stdout.write(`${JSON.stringify(A)}
103
- `)}else{let A=Z.message??Z.kind;if(A)k0.stdout.write(`${O.dim("[coder]")} ${c0(A,N)}
104
- `)}H=P.length},J=q;if(!Y.json){if(k0.stdout.write(`${O.dim(`[coder] task ${q.id} ${J.status} — streaming (Ctrl-C to stop)`)}
105
- `),q.prompt)k0.stdout.write(`${h2(q.prompt,O).join(`
106
- `)}
107
- `)}V();while(!K.has(J.status))await new Promise((P)=>setTimeout(P,400)),J=b0(W,r(W,q.id)??J),V();V();let U=hY.join(C(W,q.id),"result.json"),L=X8.existsSync(U)?JSON.parse(X8.readFileSync(U,"utf8")):null;if(Y.json)E({taskId:q.id,status:J.status,result:L});else{let Z=J.status==="completed"?"(no final message)":`(task ${J.status})`;k0.stdout.write(`
108
- ${v2(L,J.error,Z)}
109
- `);let A=L?.tokens?` tokens=${u0(L.tokens,L.model??J.model)}`:"";k0.stderr.write(`${O.dim(`[coder] task=${q.id} status=${J.status}${A}`)}
110
- `)}k0.exit(J.status==="completed"?0:1)}import W8 from"node:fs";import bY from"node:path";import j0 from"node:process";async function H4(Q){let{options:Y,positionals:X}=T(Q,S({...b,model:j,effort:j,permissions:j,background:_,wait:_})),W=I(Y),[q,...K]=X,G=K.join(" ").trim();if(!q||!G)D("Missing task id or follow-up text.",{hint:['Usage: coder task steer <task-id> "<follow-up>" [--wait]',"Help: coder task steer --help"]});let z=p(W,q);if(!z.threadId)D(`Task ${z.id} has no thread to steer yet (status: ${z.status}).`,{hint:`Wait for it to start: coder task stream ${z.id}`});if(z.status==="running"){if(z.engine!=="claude"){if((await S9(W,{threadId:z.threadId,text:G})).steered)return q8(W,z.id,{queued:!1,options:Y})}let B=r(W,z.id)??z;if(J0.includes(B.status))return y4(W,B.id,G),q8(W,B.id,{queued:!0,options:Y})}let $=[G,"--resume",z.id,"--cwd",W,...z.agent?["--agent",z.agent]:[],...Y.model?["--model",Y.model]:z.model?["--model",z.model]:[],...Y.effort?["--effort",Y.effort]:z.effort?["--effort",z.effort]:[],...Y.permissions?["--permissions",Y.permissions]:z.permissions?["--permissions",z.permissions]:[],...Y.wait?["--wait"]:[]];await W2($)}async function q8(Q,Y,{queued:X,options:W}){if(X){if(W.json){E({taskId:Y,steered:"queued"});return}if(j0.stdout.write(`${O.dim("[coder]")} follow-up queued for task ${O.cyan(Y)}; it runs when the current turn finishes.
111
- `),W.wait)j0.stdout.write(`
112
- ${O.dim(`[coder] --wait is not available for a queued follow-up; check: coder task result ${Y}`)}
113
- `);return}if(!W.wait){if(W.json){E({taskId:Y,steered:"live"});return}j0.stdout.write(`${O.dim("[coder]")} steered follow-up into running task ${O.cyan(Y)}.
114
- `),j0.stdout.write(`
115
- ${O.dim(` result: coder task result ${Y}`)}
116
- `);return}let q=r(Q,Y),K=q?await b4(Q,q):null,G=bY.join(C(Q,Y),"result.json"),z=W8.existsSync(G)?JSON.parse(W8.readFileSync(G,"utf8")):null;if(W.json)E({taskId:Y,status:K?.status??null,finalMessage:z?.finalMessage??null});else j0.stdout.write(`
117
- ${z?.finalMessage||"(no final message)"}
118
-
119
- `),j0.stderr.write(`${O.dim(`[coder] task=${Y} status=${K?.status??"unknown"}`)}
120
- `);j0.exitCode=K?.status==="completed"?0:1}import K8 from"node:process";async function N4(Q){let{options:Y,positionals:X}=T(Q,S(b));f(X,1,"task stop");let W=I(Y),q=p(W,X[0]),K=q.engine==="claude"?{detail:"claude worker terminated"}:await w9(W,{threadId:q.threadId,turnId:q.turnId});if(q.pid&&q.status==="running")try{K8.kill(q.pid,"SIGTERM")}catch{}if(m(W,q.id,{status:"cancelled",completedAt:new Date().toISOString()}),Y.json){E({taskId:q.id,status:"cancelled",interrupt:K.detail});return}K8.stdout.write(`Stopped task ${O.cyan(q.id)} ${O.dim(`(${K.detail})`)}
121
- `)}import $8 from"node:path";import w2 from"node:process";import{spawn as gY}from"node:child_process";import J4 from"node:process";function z8(Q,Y){if(!Y.length)return;try{gY(J4.execPath,[A0,"_archiveSweep","--cwd",Q,...Y],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function G8(Q){let{options:Y,positionals:X}=T(Q,S({cwd:j})),W=I(Y);for(let q of X){let K=y0(W,q);if(K)h0(W,K)}}async function V4(Q){let{options:Y,positionals:X}=T(Q,S({...b,"all-stopped":_}));f(X,1,"task archive");let W=I(Y);if(Y["all-stopped"]){let G=z2(W).filter(($)=>Z0.includes($.status));for(let $ of G)h0(W,$);let z=G.map(($)=>$.id);if(Y.json){E({archived:z,count:z.length});return}J4.stdout.write(z.length?`Archived ${z.length} stopped task${z.length===1?"":"s"}.
122
- `:`${O.dim("No stopped tasks to archive.")}
123
- `);return}let q=X[0];if(!q)D("Missing task id.",{hint:["Archive one: coder task archive <task-id>","Archive all stopped: coder task archive --all-stopped"]});let K=p(W,q);if(h0(W,K),Y.json){E({taskId:K.id,archived:!0});return}J4.stdout.write(`Archived task ${O.cyan(K.id)}.
124
- `)}var yY=300000;async function U4(Q){let{options:Y,positionals:X}=T(Q,S({cwd:j,dir:j,limit:d(S0([C0("all"),O0.number().check(w0(),I0())],{error:'expected a positive integer or "all"'})),json:_,running:_,stopped:_,archived:_}));f(X,0,"task list");let W=I(Y),q=Y.limit==="all"?void 0:Y.limit,K=(J)=>Z0.includes(J.status),G=[],z=z2(W).filter((J)=>{if(!K(J))return!0;let U=J.completedAt??J.updatedAt??J.createdAt;if(B2(U)<=yY)return!0;return P3(W,J),G.push(J.id),!1});if(z8(W,G),Y.archived)z=g0(W);else if(Y.running)z=z.filter((J)=>J0.includes(J.status));else if(Y.stopped)z=z.filter(K);let $=Y.dir??Y.cwd;if($){let J=Y0($8.resolve(String($)));z=z.filter((U)=>U.cwd&&Y0(U.cwd)===J)}if(!Y.archived&&!Y.running&&!Y.stopped){let J=(U)=>U.status==="failed"?0:J0.includes(U.status)?1:U.status==="completed"?3:2;z=[...z].sort((U,L)=>J(U)-J(L))}let B=q!==void 0?Math.max(0,z.length-q):0;if(q!==void 0)z=z.slice(0,q);let N=z.map((J)=>({taskId:J.id,status:J.status,agent:J.agent??null,model:J.model??null,name:J.name??null,cwd:J.cwd??null,prompt:String(J.prompt??"").slice(0,80),updatedAt:J.updatedAt,archived:J.archived??!1,idleMs:J0.includes(J.status)?B2(x2(W,J)):null}));if(Y.json){E(N);return}if(!N.length){let J=Y.archived?"archived tasks":Y.running?"running tasks":Y.stopped?"recently stopped tasks":"recent tasks";w2.stdout.write(`No ${J}.
125
- `);let U=[];if(!Y.archived){let L=g0(W,{migrate:!1}).length;if(L)U.push(`${L} archived: coder task list --archived [--limit N]`)}if(U.length)w2.stdout.write(`
126
- ${_0(U,O)}
127
- `);return}let H=O;for(let J of N){let U=J.archived?` ${H.dim("(archived)")}`:"",L=J.name?J.name:H.dim(J.prompt),P=J.idleMs!==null&&J.idleMs>=n4?` ${(J.idleMs>b2?H.red:H.dim)(`· idle ${H2(J.idleMs)}`)}`:"";w2.stdout.write(`${H.cyan(J.taskId.padEnd(24))} ${g2(J.status,10)} ${H.dim(((J.agent??"-")+(J.model?`/${J.model}`:"")).padEnd(14))} ${H.dim((J.cwd?$8.basename(J.cwd):"-").padEnd(12))} ${L}${P}${U}
128
- `)}if(B)w2.stdout.write(H.dim(`
129
- ... ${B} more not shown (--limit ${q})
130
- `));let V=["Result: coder task result <task-id>"];if(!Y.archived)V.push("Older tasks: coder task list --archived [--limit N]");w2.stdout.write(`
131
- ${_0(V,H)}
132
- `)}import H8 from"node:process";import L4 from"node:fs";import mY from"node:os";import P4 from"node:path";function uY(){let Q=process.env.CLAUDE_CONFIG_DIR||P4.join(mY.homedir(),".claude");return P4.join(Q,"projects")}function B8(Q){if(!Q)return!1;let Y=uY(),X=!1;try{for(let W of L4.readdirSync(Y)){let q=P4.join(Y,W,`${Q}.jsonl`);if(L4.existsSync(q))L4.rmSync(q,{force:!0}),X=!0}}catch{}return X}function N8(Q){if(!Q.threadId)return;if(Q.engine==="codex")S4(Q.threadId);else if(Q.engine==="claude")B8(Q.threadId)}async function O4(Q){let{options:Y,positionals:X}=T(Q,S({...b,"all-archived":_}));f(X,1,"task delete");let W=I(Y);if(Y["all-archived"]){let z=g0(W).filter(($)=>{return N8($),O3(W,$.id)}).map(($)=>$.id);if(Y.json){E({deleted:z,count:z.length});return}H8.stdout.write(z.length?`Deleted ${z.length} archived task${z.length===1?"":"s"}.
133
- `:`${O.dim("No archived tasks to delete.")}
134
- `);return}let q=X[0];if(!q)D("Missing task id.",{hint:["Delete one: coder task delete <task-id>","Delete all archived: coder task delete --all-archived"]});let K=p(W,q);if(K.status==="running")D(`Task ${K.id} is still running.`,{hint:`Stop it first: coder task stop ${K.id}`});if(N8(K),O3(W,K.id),Y.json){E({taskId:K.id,deleted:!0});return}H8.stdout.write(`Deleted task ${O.cyan(K.id)}.
135
- `)}import Z4 from"node:process";async function A4(Q){let{options:Y,positionals:X}=T(Q,S(b));f(X,1,"task approvals");let W=I(Y),q=p(W,X[0]),K=o0(C(W,q.id)).map((z)=>({id:z.id,summary:z.summary,createdAt:z.createdAt,answered:z.response?.decision??null}));if(Y.json){E(K);return}if(!K.length){Z4.stdout.write(`${O.dim(`No approvals for task ${q.id}.`)}
136
- `);return}let G=O;for(let z of K){let $=z.answered??"pending";Z4.stdout.write(`${G.cyan(z.id)} ${$.padEnd(8)} ${G.dim(z.summary)}
137
- `)}}async function D4(Q){let{options:Y,positionals:X}=T(Q,S({...b,deny:_}));f(X,2,"task approve");let W=I(Y),[q,K]=X;if(!q||!K)D("Missing task id or approval id.",{hint:["List them: coder task approvals <task-id>","Usage: coder task approve <task-id> <id> [--deny]"]});let G=p(W,q),z=Y.deny?"decline":"accept";if(G9(C(W,G.id),K,z),Y.json){E({taskId:G.id,approvalId:K,decision:z});return}Z4.stdout.write(`${Y.deny?"Denied":"Approved"} ${O.cyan(K)} on task ${O.cyan(G.id)}.
138
- `)}import $3 from"node:fs";import J8 from"node:path";import F4 from"node:process";async function V8(Q){let{options:Y,positionals:X}=T(Q,S({...b,workspace:_})),W=I(Y),[q="list",K,...G]=X,z=Y.workspace?J8.join(Y0(W),"coder.config.json"):N0(),$=(R,y)=>y.split(".").reduce((z0,M)=>z0==null?void 0:z0[M],R);if(q==="list"){let R=o(W);if(Y.json){E(R);return}let y=O,z0=(M)=>[M?.model,M?.effort,M?.permissions].filter(Boolean).join("/")||"-";F4.stdout.write([`${y.dim("chain")} ${R.chain.join(" -> ")}`,`${y.dim("codex")} ${z0(R.agents.codex)}`,`${y.dim("claude")} ${z0(R.agents.claude)}`,`${y.dim("approvals")} timeout=${R.approvals.escalationTimeoutMs}ms hosts=[${R.approvals.allowedNetworkHosts.join(", ")}]`,`${y.dim("file")} ${N0()}`].join(`
139
- `)+`
140
- `);return}if(q==="get"){if(!K)D("Usage: coder config get <key> (e.g. chain, agents.codex.model)");let R=$(o(W),K);if(Y.json||R===null||typeof R==="object"&&R!==void 0){E(R===void 0?null:R);return}F4.stdout.write(`${R===void 0?"(unset)":String(R)}
141
- `);return}if(q!=="set"&&q!=="unset")D("Usage: coder config [get|set|unset] <key> [value] [--workspace]");if(!K||q==="set"&&G.length===0)D(`Usage: coder config ${q} <key>${q==="set"?" <value>":""}`);let B=G.join(" "),N;try{N=JSON.parse(B)}catch{N=B.includes(",")?B.split(",").map((R)=>R.trim()).filter(Boolean):B}let H=$3.existsSync(z)?JSON.parse($3.readFileSync(z,"utf8")):{},V=K.split("."),J=V.at(-1),U=H;for(let R of V.slice(0,-1)){if(typeof U[R]!=="object"||U[R]===null)U[R]={};U=U[R]}if(q==="set")U[J]=N;else delete U[J];let L=s0(H);if(L.length)D(`Refusing to write invalid config:
142
- ${L.join(`
143
- `)}`);$3.mkdirSync(J8.dirname(z),{recursive:!0}),$3.writeFileSync(z,`${JSON.stringify(H,null,2)}
144
- `,"utf8");let P=$(o(W),K)??null;if(Y.json){E({file:z,key:K,...q==="set"?{value:N}:{unset:!0},effective:P});return}let Z=O,A=q==="set"?`${Z.cyan(K)} = ${JSON.stringify(N)}`:`unset ${Z.cyan(K)}`;F4.stdout.write(`${A} ${Z.dim(`(${z})`)}
145
- `)}import cY from"node:fs";import B3 from"node:process";import{fileURLToPath as fY}from"node:url";async function H3(Q){let{options:Y,positionals:X}=T(Q,S({...b,codex:_,claude:_,agents:_})),W=I(Y),q=["claude","codex","agents"];for(let w of X){if(!q.includes(w))D(`Unknown host "${w}". Use claude, codex, or agents.`,{hint:"Codex, Pi, OpenCode, and other Agent Skills hosts: coder setup-host agents"});Y[w]=!0}let K=B3.stdout.isTTY&&!B3.env.NO_COLOR,G=(w,t)=>K?`\x1B[${w}m${t}\x1B[0m`:t,z=(w)=>` ${G("32","✔")} ${w}`,$=(w)=>` ${G("31","✘")} ${w}`,B=(w)=>G("1",w),N=(w)=>G("38;5;245",w);if(!Y.json)B3.stdout.write(`${B("Coder host setup")}
146
-
147
- `);let H=B0(W),V=l9(H);if(V?.updated)H=B0(W);let J=H.available?await I9(W):{loggedIn:!1,detail:H.detail},U=Q2(),L=U.available?c9():{loggedIn:!1,detail:U.detail},P=N0();if(!cY.existsSync(P)){let w=H.available?["codex","claude"]:U.available?["claude","codex"]:["codex","claude"];m9({...q4,chain:w})}let Z=k2(),A=Y.claude?Y3(Z):null,R=Y.agents||Y.codex?W3(Z):null,y=o(W),z0=H.available&&J.loggedIn||U.available&&L.loggedIn;if(Y.json){E({codex:{available:H.available,detail:H.detail,auth:J.detail,loggedIn:J.loggedIn},...V?{codexUpdate:V}:{},claude:{available:U.available,detail:U.detail,auth:L.detail,loggedIn:L.loggedIn},configFile:P,runtime:fY(new URL("../bin/coder.mjs",import.meta.url)),...A?{claudePlugin:A}:{},...R?{agentsSkill:R}:{},config:y,ready:z0});return}let M=[],u=H.available?J.loggedIn?z(`codex ${N(`${H.detail}; ${J.detail}`)}`):$(`codex not logged in ${N(`(${J.detail})`)} - run: codex login`):$("codex CLI not installed - run: npm install -g @openai/codex"),c=U.available?L.loggedIn?z(`claude ${N(`${U.detail}; ${L.detail}`)}`):$("claude not logged in - run: claude auth login"):$("claude CLI not installed - run: npm install -g @anthropic-ai/claude-code");if(M.push(B("Available Engines"),u,c,` ${N("custom models (local/provider endpoints): coder model --help")}`),V?.updated)M.push(z(`codex ${N(`updated ${V.from} -> ${H.detail} (GPT-5.6 support)`)}`));else if(V)M.push($(`codex ${V.note}`));M.push("");let i=(w)=>{let t=y.agents?.[w]??{};return[t.model,t.effort,t.permissions].filter(Boolean).join("/")};M.push(B("Config"),` chain: ${(y.chain??[]).join(" -> ")} codex: ${i("codex")} claude: ${i("claude")}`,` ${N(P)} ${N("(coder config set <key> <value> to change)")}`,"");let Q0=[["claude plugin",A],["agents skill ",R]];for(let[w,t]of Q0)if(t)M.push(t.installed?z(`${w} ${N(t.note)}`):$(`${w} ${t.note}`),"");M.push(z0?z(`ready - try: coder run --wait "explain this repo's layout"`):$("not ready - install an engine CLI to run tasks: codex (npm install -g @openai/codex, then codex login) or claude (npm install -g @anthropic-ai/claude-code, then claude auth login)")),B3.stdout.write(`${M.join(`
148
- `)}
149
- `)}import N3 from"node:fs";import L8 from"node:path";import v0 from"node:process";var pY=new Set(["codex","claude","custom",...Object.keys(a0),...Object.keys(M2)]);async function R4(Q){let Y=Q.envKey?v0.env[Q.envKey]:void 0,X=e0(Q.baseUrl,"models"),W=null;for(let q of X)try{let K=await fetch(q,{headers:Y?{Authorization:`Bearer ${Y}`}:{},signal:AbortSignal.timeout(5000)});if(!K.ok){W=K.status===404?{reachable:!0,modelListed:null,detail:"endpoint reachable (no model list to verify against)"}:{reachable:!1,modelListed:null,detail:`${q} -> HTTP ${K.status}`};continue}let G=await K.json().catch(()=>null),z=Array.isArray(G?.data)?G.data.map((B)=>B.id):null;if(!z)return{reachable:!0,modelListed:null,detail:"endpoint reachable"};let $=z.includes(Q.model);return{reachable:!0,modelListed:$,detail:$?`endpoint reachable; model "${Q.model}" listed`:`endpoint reachable, but "${Q.model}" is not in its model list`}}catch(K){let G=K instanceof Error?K.message:String(K);W={reachable:!1,modelListed:null,detail:`${q} unreachable (${G})`}}return W}function P8(Q,Y){let X=N3.existsSync(Q)?JSON.parse(N3.readFileSync(Q,"utf8")):{};if(X.models=X.models??{},Y(X.models),Object.keys(X.models).length===0)delete X.models;let W=s0(X);if(W.length)D(`Refusing to write invalid config:
150
- ${W.join(`
151
- `)}`);N3.mkdirSync(L8.dirname(Q),{recursive:!0}),N3.writeFileSync(Q,`${JSON.stringify(X,null,2)}
152
- `,"utf8")}var J3=S({...b,"base-url":j,model:j,"env-key":j,workspace:_});function O8(Q,Y){return Q.workspace?L8.join(Y0(Y),"coder.config.json"):N0()}async function Z8(Q){let{options:Y,positionals:X}=T(Q,J3);if(X.length)D("model list takes no arguments.",{hint:"Usage: coder model list [--json]"});let W=I(Y),q=O,K=o(W),G=Object.entries(K.models??{});if(Y.json){let $=await Promise.all(G.map(async([B,N])=>({name:B,...N,probe:await R4(N)})));E({models:$});return}if(!G.length){v0.stdout.write(`No custom models configured.
153
- `),v0.stdout.write(`
154
- ${q.dim("Add one: coder model add <name> --base-url <url> --model <id> [--env-key VAR]")}
155
- `);return}let z=[q.bold("Custom models"),""];for(let[$,B]of G){let N=await R4(B),H=N.reachable?q.green("✔"):q.red("✘");z.push(` ${H} ${$.padEnd(14)} ${B.model} ${q.dim(`@ ${B.baseUrl} — ${N.detail}`)}`)}z.push("",q.dim('Use one: coder run --model <name> "<task>" (or coder run --agent custom)')),v0.stdout.write(`${z.join(`
156
- `)}
157
- `)}async function A8(Q,Y,X,W,q){let K=O8(X,W),G=O,z=await K3(Y),$=z?.wireApi==="responses";if(z)Y.wireApi=z.wireApi,Y.baseUrl=z.baseUrl??Y.baseUrl;else delete Y.wireApi;P8(K,(P)=>{P[Q]=Y});let B=await R4(Y),N=q3(B0(W)),H=B0(W),V=Y.envKey&&!v0.env[Y.envKey];if(X.json){E({name:Q,...Y,file:K,probe:B,codex:H,...N?{codexInstall:N}:{},ready:B.reachable&&H.available});return}let J=(P)=>` ${G.green("✔")} ${P}`,U=(P)=>` ${G.red("✘")} ${P}`,L=[`${q} ${G.cyan(Q)} -> ${Y.model} @ ${Y.baseUrl} ${G.dim(`(${K})`)}`,"",B.reachable?J(`${B.detail} ${G.dim(`(${$?"responses api, direct":"chat api, auto-translated"})`)}`):U(B.detail),H.available?J(N?.installed?`${N.note} ${G.dim(`(${H.detail})`)}`:`codex engine ${G.dim(`(${H.detail})`)}`):U(N?.note??"codex CLI not installed - run: npm install -g @openai/codex")];if(V)L.push(U(`env var ${Y.envKey} is not set in this shell`));L.push("",G.dim([`Use it: coder run --model ${Q} "<task>"`,`Make default: coder config set agents.custom.model ${Q}`].join(`
158
- `))),v0.stdout.write(`${L.join(`
159
- `)}
160
- `)}function lY(Q,Y){if(!Q)D("Missing model name.",{hint:Y});if(!/^[a-z][a-z0-9-]*$/.test(Q))D(`Invalid model name "${Q}". Use lowercase kebab-case (e.g. qwen-local).`);if(pY.has(Q))D(`"${Q}" is a built-in alias; pick another name.`);return Q}async function U8(Q){let{options:X,positionals:W}=T(Q,J3),q=I(X),K=lY(W[0],"Usage: coder model add <name> --base-url <url> --model <id> [--env-key VAR]");if(o(q).models?.[K])D(`Custom model "${K}" already exists.`,{hint:`Change it: coder model update ${K} [--base-url|--model|--env-key], or remove it first.`});if(!X["base-url"]||!X.model)D("Missing --base-url or --model.",{hint:"Usage: coder model add <name> --base-url <url> --model <id> [--env-key VAR]"});let G={baseUrl:T2(X["base-url"]),model:X.model,...X["env-key"]?{envKey:X["env-key"]}:{}};await A8(K,G,X,q,"saved")}async function rY(Q){let{options:X,positionals:W}=T(Q,J3),q=I(X),K=W[0],G=K?o(q).models?.[K]:void 0;if(!K||!G)D(K?`No custom model named "${K}".`:"Missing model name.",{hint:K?"List them: coder model list":"Usage: coder model update <name> [--base-url <url>] [--model <id>] [--env-key VAR]"});if(!X["base-url"]&&!X.model&&!X["env-key"])D("Nothing to update: pass --base-url, --model, or --env-key.",{hint:"Usage: coder model update <name> [--base-url <url>] [--model <id>] [--env-key VAR]"});let z={...G,...X["base-url"]?{baseUrl:T2(X["base-url"])}:{},...X.model?{model:X.model}:{},...X["env-key"]?{envKey:X["env-key"]}:{}};await A8(K,z,X,q,"updated")}async function dY(Q){let{options:Y,positionals:X}=T(Q,J3),W=I(Y),q=X[0];if(!q||!o(W).models?.[q])D(q?`No custom model named "${q}".`:"Missing model name.",{hint:q?"List them: coder model list":"Usage: coder model remove <name>"});let K=O8(Y,W);if(P8(K,(G)=>{delete G[q]}),Y.json){E({removed:q,file:K});return}v0.stdout.write(`removed ${O.cyan(q)} ${O.dim(`(${K})`)}
161
- `)}var nY={list:Z8,add:U8,setup:U8,update:rY,remove:dY};async function D8(Q){let[Y,...X]=Q;if(Y===void 0||Y.startsWith("-")){await Z8(Q);return}let W=nY[Y];if(!W)D(`Unknown model subcommand "${Y}". Use list, add, update, or remove.`,{hint:"Help: coder model --help"});await W(X)}import oY from"node:fs";import iY from"node:path";import q2 from"node:process";import{spawnSync as tY}from"node:child_process";async function E4(Q){let{options:Y}=T(Q,S({pm:j,"cli-only":_,"plugins-only":_,codex:_,claude:_})),X=!Y["plugins-only"],W=!Y["cli-only"],q=q2.stdout.isTTY&&!q2.env.NO_COLOR,K=(U,L)=>q?`\x1B[${U}m${L}\x1B[0m`:L,G=(U)=>K("1",U),z=(U)=>K("38;5;245",U),$=(U)=>` ${K("32","✔")} ${U}`,B=(U)=>` ${K("31","✘")} ${U}`,N=(U,L)=>L&&U&&L!==U?`${U} ${z("->")} ${G(L)}`:`${L??U??"?"} ${z("(unchanged)")}`,H=k2(),V=iY.join(H,"plugins/claude/.claude-plugin/plugin.json"),J={cli:a(),claude:E3(V)};if(X){let U=l4(A0),[L,...P]=Y.pm==="npm"?["npm","install","-g","@wular/coder@latest"]:Y.pm==="pnpm"?["pnpm","add","-g","@wular/coder@latest"]:Y.pm==="yarn"?["yarn","global","add","@wular/coder@latest"]:Y.pm==="bun"?["bun","add","-g","@wular/coder@latest"]:U.command,Z=Y.pm??U.pm;q2.stdout.write(`${G("Updating coder CLI")} ${z(`via ${Z}...`)}
162
- `);let A=tY(L,P,{encoding:"utf8"});if(A.error?.code==="ENOENT")D(`${Z} not found on PATH. Re-run with --pm <npm|pnpm|yarn|bun>, or update manually: ${L} ${P.join(" ")}`);if(A.status!==0){let y=(A.stderr||A.stdout||"").trim();D(`CLI update failed (${Z}).${y?`
163
- ${y}`:""}
164
- Run manually: ${L} ${P.join(" ")}`)}c4();let R=a();q2.stdout.write(R!==J.cli?`${$(`coder CLI ${N(J.cli,R)}`)}
165
- `:`${$(`coder CLI ${J.cli} ${z("(already latest)")}`)}
166
- `)}if(W){if(Y.claude||!Y.codex&&Q2().available){let L=Y3(H),P=E3(V);q2.stdout.write(`${L.installed?$(`claude plugin ${N(J.claude,P)} ${z(`- ${L.note}`)}`):B(`claude plugin ${L.note}`)}
167
- `)}if(oY.existsSync(X3())){let L=$4(),P=W3(H),Z=$4();q2.stdout.write(`${P.installed?$(`agents skill ${N(L,Z)} ${z(`- ${P.note}`)}`):B(`agents skill ${P.note}`)}
168
- `)}}}var aY={run:W2,list:U4,stream:G3,result:B4,steer:H4,stop:N4,archive:V4,delete:O4,approvals:A4,approve:D4};async function sY(Q){let[Y,...X]=Q;if(Y===void 0||Y==="help"||Y==="-h"||Y==="--help"){e.stdout.write(J2());return}let W=aY[Y];if(!W)e.stdout.write(J2()),D(`Unknown task subcommand "${Y}".`,{hint:'Run a task: coder run "<text>"'});if(c2(X)){e.stdout.write(N2(`task ${Y}`)??J2());return}await W(X)}var eY={task:sY,run:W2,list:U4,stream:G3,result:B4,steer:H4,stop:N4,archive:V4,delete:O4,approvals:A4,approve:D4,watch:G3,config:V8,"setup-host":H3,"host-setup":H3,setup:H3,model:D8,upgrade:E4,update:E4,_worker:Q8,_refreshUpdate:async()=>p4(a()),_archiveSweep:G8};async function Q6(){let[Q,...Y]=e.argv.slice(2);if(Q==="--version"||Q==="-v"){e.stdout.write(`${a()}
169
- `);return}if(Q===void 0||Q==="help"||Q==="--help"||Q==="-h"){if(Y[0]==="task"&&Y[1]===void 0){e.stdout.write(J2());return}if(Y[0]==="model"&&Y[1]===void 0){e.stdout.write(I3());return}let W=Y.map((q)=>(q==="task"||q==="model")&&Y[1]?`${q} ${Y[1]}`:m2[q]??q).find((q)=>f0[q]);e.stdout.write(W&&N2(W)||u2());return}if(Q!=="_worker"&&Q!=="_refreshUpdate"&&Q!=="_archiveSweep")f4(a(),A0);let X=eY[Q];if(!X)e.stdout.write(u2()),D(`Unknown command "${Q}".`,{hint:"See all commands: coder --help"});if(Q==="model"&&c2(Y)){let W=Y.find((q)=>!q.startsWith("-"));e.stdout.write(W&&N2(`model ${W}`)||I3());return}if(Q!=="task"&&c2(Y)){let W=m2[Q]??Q;e.stdout.write(N2(W)??u2());return}try{await X(Y)}catch(W){let q=W instanceof Error?W.message:String(W);if(/^(Unknown option|Missing value)/.test(q)){let K=m2[Q]??Q;if(f0[K])D(q,{hint:`Help: coder ${Q} --help`})}throw W}}Q6().catch((Q)=>{e.stderr.write(`${Q instanceof Error?Q.message:String(Q)}
170
- `),e.exit(1)});
45
+ agent default in config. Alias: \`coder model setup\`.`,flags:[[`--base-url <url>`,`OpenAI-compatible API base (e.g. http://localhost:11434/v1)`],[`--model <id>`,`the provider's model id (e.g. qwen2.5-coder:32b)`],[`--env-key <VAR>`,`env var holding the API key (omit for keyless local endpoints)`],[`--workspace`,`write to <repo>/coder.config.json instead of the user file`],H],examples:[[`coder model add qwen --base-url http://localhost:11434/v1 --model qwen2.5-coder:32b`,`local Ollama model, no key`],[`coder model add kimi --base-url https://openrouter.ai/api/v1 --model moonshotai/kimi-k2 --env-key OPENROUTER_API_KEY`,`third-party provider via OpenRouter`],[`coder run --model qwen "explain this repo"`,`dispatch a task on it`]],seeAlso:`model list · model update · setup-host · config`},"model update":{list:[`model update <name> [--base-url|--model|--env-key]`,`change a custom model in place`],usage:`coder model update <name> [--base-url <url>] [--model <id>] [--env-key VAR]`,summary:`Update a configured custom model. Only the flags you pass change; the endpoint
46
+ is re-probed and the wire protocol re-detected.`,flags:[[`--base-url <url>`,`new API base`],[`--model <id>`,`new provider model id`],[`--env-key <VAR>`,`new API-key env var`],[`--workspace`,`write to <repo>/coder.config.json instead of the user file`],H],seeAlso:`model list · model remove`},"model remove":{list:[`model remove <name>`,`delete a custom model`],usage:`coder model remove <name>`,summary:`Remove a configured custom model.`,flags:[[`--workspace`,`target <repo>/coder.config.json instead of the user file`],H],seeAlso:`model list · model add`},"model disable":{list:[`model disable <name>`,`turn off a model (built-in, custom, or alias)`],usage:`coder model disable <name> [--workspace]`,summary:`Disable a model - built-in, custom, or alias. Requests for it fail until re-enabled.`,flags:[[`--workspace`,`target <repo>/coder.config.json instead of the user file`],H],seeAlso:`model enable · model list`},"model enable":{list:[`model enable <name>`,`re-enable a disabled model`],usage:`coder model enable <name> [--workspace]`,summary:`Re-enable a disabled model.`,flags:[[`--workspace`,`target <repo>/coder.config.json instead of the user file`],H],seeAlso:`model disable · model list`},"model alias":{list:[`model alias <name> <spec>`,`add or replace a user alias`],usage:`coder model alias <name> <spec> [--workspace]`,summary:`Save an alias for an agent spec, e.g. fast -> codex:spark. An alias may reuse a
47
+ built-in name to override it.`,flags:[[`--workspace`,`target <repo>/coder.config.json instead of the user file`],H],seeAlso:`model unalias · model list`},"model unalias":{list:[`model unalias <name>`,`remove a user alias`],usage:`coder model unalias <name> [--workspace]`,summary:`Remove a user-defined alias.`,flags:[[`--workspace`,`target <repo>/coder.config.json instead of the user file`],H],seeAlso:`model alias · model list`},docs:{list:[`docs [topic]`,`print bundled documentation (for agents to read)`],usage:`coder docs [topic] [--json]`,summary:`Print bundled documentation. With no topic, list the available topics; with a
48
+ topic, print that doc's raw markdown to stdout (unstyled, for an agent to
49
+ consume).`,flags:[[`--json`,`list topics as JSON (bare listing only)`]],examples:[[`coder docs`,`list the available topics`],[`coder docs flows`,`print the Flows doc`]]},upgrade:{list:[`upgrade [--cli-only|--plugins-only]`,`update the CLI and host plugins (alias: update)`],usage:`coder upgrade [--cli-only] [--plugins-only] [--codex] [--claude] [--pm <mgr>]`,summary:`Update the coder CLI through whichever package manager installed it, then refresh
50
+ the host plugins to match. Alias: update.`,flags:[[`--cli-only`,`update just the CLI`],[`--plugins-only`,`refresh just the host plugins`],[`--codex`,`limit the refresh to the Agent Skills copy (Codex, Pi, ...)`],[`--claude`,`limit the refresh to the Claude Code plugin`],[`--pm <npm|pnpm|yarn|bun>`,`force a package manager instead of auto-detecting`]]}},W={run:`task run`,list:`task list`,stream:`task stream`,watch:`task stream`,result:`task result`,steer:`task steer`,stop:`task stop`,archive:`task archive`,delete:`task delete`,approvals:`task approvals`,approve:`task approve`,setup:`setup-host`,"host-setup":`setup-host`,update:`upgrade`},Ke=[{usage:`list`,blurb:`list built-ins, custom models, and aliases`},{usage:`add <name> --base-url <url> --model <id> [--env-key VAR]`,blurb:`connect a model (alias: setup)`},{usage:`update <name> [--base-url|--model|--env-key]`,blurb:`change a model in place`},{usage:`remove <name>`,blurb:`delete a custom model`},{usage:`disable <name>`,blurb:`turn off a model (built-in, custom, or alias)`},{usage:`enable <name>`,blurb:`re-enable a disabled model`},{usage:`alias <name> <spec>`,blurb:`name a spec, e.g. fast codex:spark`},{usage:`unalias <name>`,blurb:`remove an alias`}],qe=[{usage:`run <name|path> [--wait] [--args ...]`,blurb:`run a flow in the background (--wait to follow it live)`},{usage:`list`,blurb:`recent flow runs (running + just stopped)`},{usage:`discover`,blurb:`list flows runnable here (workspace + global)`},{usage:`result [run-id]`,blurb:`progress and result of a run`},{usage:`stream [run-id]`,blurb:`watch a run live (replay + follow)`},{usage:`stop [run-id]`,blurb:`stop a run and its still-running tasks`},{usage:`resume [run-id]`,blurb:`continue a stopped or edited run`},{usage:`archive <run-id> | --all-stopped`,blurb:`hide a run (or all stopped) from the list`},{usage:`delete <run-id> | --all-archived`,blurb:`delete a run's record (or all archived)`}];function G(){let e=N,t=qe.map(t=>` ${e.cyan(t.usage.padEnd(44))}${e.dim(t.blurb)}`);return`${[e.bold(`Usage:`),` coder flow <subcommand>`,``,`Orchestrate many coder tasks with a plain TypeScript file: dispatch, gates,`,`concurrency, journaling, and resume. Flows live in .coder/flows/ (workspace)`,"or ~/.coder/flows/ (global). See `coder docs flows`.",``,e.bold(`Subcommands:`),...t,``,e.dim(`Run 'coder flow <subcommand> --help' for details on any subcommand.`)].join(`
51
+ `)}\n`}function Je(){let e=N,t=Ke.map(t=>` ${e.cyan(t.usage.padEnd(60))}${e.dim(t.blurb)}`);return`${[e.bold(`Usage:`),` coder model <subcommand>`,``,"Manage the models coder can dispatch to. `add` connects any OpenAI-compatible",`endpoint (Ollama, vLLM, OpenRouter, ...) as the custom agent, alongside the`,"built-in codex/claude models. Name your own shortcuts with `alias`",`(e.g. fast -> codex:spark); disable/enable turns any model off and on.`,``,e.bold(`Subcommands:`),...t,``,e.dim(`Run 'coder model <subcommand> --help' for details on any subcommand.`)].join(`
52
+ `)}\n`}function Ye(e,t){return e.map(([e,n])=>` ${t.cyan(e.padEnd(30))}${t.dim(n)}`)}function K(e){let t=U[e];if(!t)return null;let n=N,r=[n.bold(`Usage:`),` ${t.usage}`];if(t.summary&&r.push(``,t.summary),t.flags?.length&&r.push(``,n.bold(`Flags:`),...Ye(t.flags,n)),t.examples?.length){r.push(``,n.bold(`Examples:`));for(let[e,i]of t.examples)r.push(` ${n.cyan(e)}`,` ${n.dim(i)}`)}return t.seeAlso&&r.push(``,n.dim(`Related: ${t.seeAlso}`)),`${r.join(`
53
+ `)}\n`}function q(){let e=N,t=Ge.map(t=>{let n=t.alias?e.dim(` (coder ${t.alias})`):``;return` ${e.cyan(t.usage.padEnd(30))}${e.dim(t.blurb)}${n}`});return`${[e.bold(`Usage:`),` coder task <subcommand>`,``,e.bold(`Subcommands:`),...t,``,e.dim(`Run 'coder task <subcommand> --help' for details on any subcommand.`)].join(`
54
+ `)}\n`}function J(){let e=N,t=([t,n])=>` ${e.cyan(t.padEnd(41))}${e.dim(n)}`,n=Ge.filter(e=>e.alias).map(e=>t([e.usage.replace(/^\S+/,e.alias),e.blurb]));return`${[`${e.bold(`Coder`)} ${e.dim(`v${l()}`)}`,`Delegate a coding task to the best available engine and steer it while it runs.`,``,e.bold(`Get started:`),` ${e.cyan(`coder setup-host claude`)} ${e.dim(`# or agents (Codex, Pi, ...); installs the host plugin/skill`)}`,` ${e.cyan(`coder run "explain this repo's layout"`)}`,``,e.bold(`Usage:`),` coder <command>`,``,e.bold(`Commands:`),...n,` ${e.cyan(`task <cmd>`.padEnd(41))}${e.dim(`more task commands (steer, stop, approve, ...): `)}${e.light(`coder task --help`)}`,` ${e.cyan(`flow <cmd>`.padEnd(41))}${e.dim(`orchestrate a wave of tasks: `)}${e.light(`coder flow --help`)}`,t(U.config.list),t([`model <list|add|alias|disable>`,`manage models: built-ins, aliases, custom endpoints`]),t(U.docs.list),t(U.upgrade.list),``,e.bold(`Global:`),t([`-h, --help`,`show help (top-level, or for a command)`]),t([`-v, --version`,`print the coder version`]),t([`--json`,`JSON output instead of human-readable text`]),t(V)].join(`
55
+ `)}\n`}function Y(e){let t=e.indexOf(`--`),n=t===-1?e:e.slice(0,t);return n.includes(`-h`)||n.includes(`--help`)}const X=`CODER_FLOW_ATTACH`;function Xe(e){let t={};for(let n of e){let e=n.indexOf(`=`);e===-1&&y(`Invalid argument "${n}": expected key=value.`,{hint:`Help: coder flow run --help`});let r=n.slice(0,e),i=n.slice(e+1);try{t[r]=JSON.parse(i)}catch{t[r]=i}}return t}function Ze(e,t){if(e!==void 0)try{return JSON.parse(e)}catch(e){y(`Invalid --args JSON: ${e instanceof Error?e.message:String(e)}`)}return t.length?Xe(t):{}}function Qe(){try{return He(`bun`,[`--version`],{stdio:`ignore`}).status===0}catch{return!1}}function $e(e){if(!e.endsWith(`.ts`)||L.versions.bun||L.features.typescript)return;Qe()||y(`This flow is a TypeScript file (${e}) and this Node cannot run TypeScript.`,{hint:[`Upgrade to Node 23.6+ or install bun: https://bun.sh`,`Or write the flow as .mjs / .js`]});let t=He(`bun`,[s,...L.argv.slice(2)],{stdio:`inherit`});L.exit(t.status??1)}function et(e){L.once(`SIGINT`,()=>{(async()=>{let{runId:t}=e,n=R.existsSync(z.join(P(t),Se));if(L.stderr.write(`\n[flow] stopping run ${t} — no new tasks will dispatch.\n`),n){let t=e.runningIds();t.length&&L.stderr.write(`[flow] left running: ${t.join(`, `)}\n`)}else{let n=await le(t,e.runningIds());n.length&&L.stderr.write(`[flow] stopped tasks: ${n.join(`, `)}\n`)}L.stderr.write(`[flow] resume with: coder flow resume ${t}\n`),e.requestStop(),L.exit(130)})()})}const tt=[`⣾`,`⣽`,`⣻`,`⢿`,`⡿`,`⣟`,`⣯`,`⣷`];function Z(e,t=!1){let n=N;return t?_(`[${rt(e)}]`,10):e===`completed`?n.bold(n.green(`✔`)):e===`failed`||e===`cancelled`||e===`stopped`?n.bold(n.red(`✘`)):e===`running`?n.bold(n.cyan(`●`)):n.dim(`○`)}function nt(){return _(`[start]`,10)}function rt(e){return e===`completed`?`done`:e===`cancelled`?`failed`:e}function it(e,t){return e??t.replace(/\s+/g,` `).trim().slice(0,60)}function Q(e,t,n,r,i,a){let o=N,s=_(t??n,32);return[`${e} ${a?o.bold(s):s}`,o.dim(_(n,24)),o.light(_(i??``,20)),r?o.light(`${v(r.total)} tok`):``].join(` `).trimEnd()}function at(e){let t=z.join(P(e),`events.jsonl`);return R.existsSync(t)?R.readFileSync(t,`utf8`).split(`
56
+ `).filter(Boolean).flatMap(e=>{try{return[JSON.parse(e)]}catch{return[]}}):[]}function ot(e,t=!1){let n=N;return`${Z(e.ok?`completed`:`failed`,t)} ${n.dim(`gate`)} ${n.light(e.cmd)}${e.ok?``:n.dim(` · exit ${e.code}`)}`}function st(e,t,n){let r=N,i=n!==void 0&&n>=1e3?r.dim(` · ${E(n)}`):``;return`${t} ${r.dim(`gate`)} ${r.light(e)}${i}`}function ct(e,t=!1){return N.dim(`${`│ `.repeat(e)}${t?`└─`:`├─`}`)}function lt(e){return N.dim(`${`│ `.repeat(e)}│ `)}function ut(e){return`${` `.repeat(e.depth)}${e.log?`${_(`[log]`,10)} `:``}${e.body}`}function dt(e,t,n=!1){return n?ut(e):`${e.log?lt(e.depth):ct(e.depth,t)} ${e.body}`}function ft(e){return N.dim(`${`│ `.repeat(Math.max(0,e))}│`)}function pt(e,t=!1){let n=N;if(t)return e.map(ut);let r=(t,n)=>{for(let r=t+1;r<e.length;r+=1){let t=e[r].depth;if(t<n)return!1;if(t===n)return!0}return!1};return e.map((e,t)=>{let i=``;for(let n=0;n<e.depth;n+=1)i+=r(t,n)?`│ `:` `;return i+=e.log?`│ `:r(t,e.depth)?`├─`:`└─`,`${n.dim(i)} ${e.body}`})}var mt=class{stream;names=new Map;active=new Map;activeGates=new Map;pending;previews=new Map;frame=0;hasCommitted=!1;timer;tty;region;constructor(e=L.stdout){this.stream=e,this.tty=!!e.isTTY,this.region=new me(e)}emit(e){let t=N;switch(e.kind){case`task-start`:{let t={name:it(e.name,e.prompt),agent:e.agent,depth:e.depth??0};if(this.names.set(e.taskId,t),!this.tty){this.final(t.depth,Q(nt(),t.name,e.taskId,null,t.agent));return}this.active.set(e.taskId,t),this.spin(!0),this.repaint();return}case`task-end`:{this.active.delete(e.taskId),this.previews.delete(e.taskId),this.idle();let t=this.names.get(e.taskId);this.final(t?.depth??0,Q(Z(e.status,!this.tty),t?.name??null,e.taskId,e.tokens,t?.agent));return}case`gate-start`:{let t={cmd:e.cmd,depth:e.depth??0,startedAt:Date.now()};if(!this.tty){this.final(t.depth,st(t.cmd,nt()));return}this.activeGates.set(e.gateId,t),this.spin(!0),this.repaint();return}case`gate`:e.gateId&&this.activeGates.delete(e.gateId),this.idle(),this.final(e.depth??0,ot(e,!this.tty));return;case`log`:for(let n of e.message.split(`
57
+ `))this.final(e.depth??0,t.light(n),!0);return;case`flow-start`:this.final(e.depth-1,t.bold(`flow ${e.name}`));return;case`replay`:this.final(0,t.dim(`replayed ${e.count} steps from journal`),!0)}}done(){this.spin(!1),this.flush(0),this.tty&&this.repaint(),this.region.done()}flush(e){this.pending&&=(this.region.commit(`${dt(this.pending,e<this.pending.depth,!this.tty)}\n`),this.hasCommitted=!0,void 0)}final(e,t,n=!1){if(!this.tty){this.region.commit(`${ut({depth:e,body:t,log:n})}\n`),this.hasCommitted=!0;return}this.flush(e),this.pending={depth:e,body:t,log:n},this.tty&&this.repaint()}repaint(){let e=[],t=[];if(this.pending){let n=dt(this.pending,!1);e.push(n),t.push(n)}let n=this.timer?N.bold(N.cyan(tt[this.frame%tt.length])):Z(`running`);for(let[r,i]of this.active){let a=`${ct(i.depth??0)} ${Q(n,i.name,r,null,i.agent,!0)}`;(e.length||this.hasCommitted)&&e.push(ft(i.depth??0)),e.push(a),t.push(a);let o=this.previews.get(r);o&&e.push(`${lt(i.depth??0)} ${N.dim(o)}`)}for(let r of this.activeGates.values()){let i=`${ct(r.depth)} ${st(r.cmd,n,Date.now()-r.startedAt)}`;(e.length||this.hasCommitted)&&e.push(ft(r.depth)),e.push(i),t.push(i)}let r=(_e(this.stream)??1/0)-1,i=e.length<=r?e:t;if(i.length>r){let e=Math.max(0,r-1);i=[N.dim(`… +${i.length-e} more running`),...i.slice(-e)]}this.region.set(i)}refreshPreviews(){for(let e of this.active.keys())try{let t=r(L.cwd(),e,1)[0]?.message?.replace(/\s+/g,` `).trim();if(!t)continue;let n=(Ce(this.stream)??120)-8;this.previews.set(e,t.length>n?`${t.slice(0,n-1)}…`:t)}catch{}}idle(){!this.active.size&&!this.activeGates.size&&this.spin(!1)}spin(e){e&&!this.timer?this.timer=setInterval(()=>{this.frame++,this.frame%4==0&&this.refreshPreviews(),this.repaint()},120).unref():!e&&this.timer&&(clearInterval(this.timer),this.timer=void 0)}};function ht(e){if(e.json)return{};let t=new mt,n=e=>t.emit(e);return{onTaskStart:e=>n({kind:`task-start`,...e}),onTaskEnd:e=>n({kind:`task-end`,...e}),onGateStart:e=>n({kind:`gate-start`,...e}),onGate:e=>n({kind:`gate`,...e}),onLog:(e,t)=>n({kind:`log`,message:e,depth:t}),onFlowStart:e=>n({kind:`flow-start`,...e}),onReplay:e=>n({kind:`replay`,count:e})}}function gt(e){let t=z.join(P(e),`events.jsonl`),n=e=>{try{R.appendFileSync(t,`${JSON.stringify(e)}\n`,`utf8`)}catch{}};return{onStart:e=>et(e),onTaskStart:e=>n({kind:`task-start`,...e}),onTaskEnd:e=>n({kind:`task-end`,...e}),onGateStart:e=>n({kind:`gate-start`,...e}),onGate:e=>n({kind:`gate`,...e}),onLog:(e,t)=>n({kind:`log`,message:e,depth:t}),onFlowStart:e=>n({kind:`flow-start`,...e}),onReplay:e=>n({kind:`replay`,count:e})}}async function _t(e,t){try{await se(e,t,gt(e)),L.exit(0)}catch(t){ve(e,t instanceof Error?t.message:String(t)),L.exit(1)}}function vt(e,t){let n=P(e.runId);R.writeFileSync(z.join(n,`events.jsonl`),``,`utf8`);let r=R.openSync(z.join(n,`flow.log`),`a`),i=Ve(L.execPath,[s,...L.argv.slice(2)],{detached:!0,stdio:[`ignore`,r,r],env:{...L.env,[X]:e.runId}});return i.unref(),R.closeSync(r),t.wait?i.pid:t.json?(k({runId:e.runId,status:`running`}),i.pid):(L.stdout.write(`${N.dim(`[flow]`)} run ${N.cyan(e.runId)} started in the background (running).\n`),L.stdout.write(`\n${h([`Result: coder flow result ${e.runId}`,`Runs: coder flow list`],N)}\n`),i.pid)}async function yt(e,t,n){let r=!!(t.stream&&t.json);!t.json&&(j(e)?.status??`running`)===`running`&&L.stderr.write(`${N.dim(`[flow]`)} run ${N.cyan(e)} started (running); waiting for it to finish — Ctrl-C to detach (it keeps running).\n\n`);let i=t.json?()=>{}:x(),a=()=>{i(),r||(L.stderr.write(`\n${N.dim(`[flow] detached — run still going.`)}\n`),L.stderr.write(`\n${h([`Result: coder flow result ${e}`,`Stop it: coder flow stop ${e}`],N)}\n`)),L.exit(130)};L.on(`SIGINT`,a);let o=new mt;for await(let i of D(e,n,{tail:t.tail}))r?L.stdout.write(`${JSON.stringify(i)}\n`):t.json||o.emit(i);o.done(),i(),L.off(`SIGINT`,a);let s=j(e);s||y(`[flow] run ${e} vanished while following.`,{hint:`Recent runs: coder flow list`}),r&&(L.stdout.write(`${JSON.stringify(Ot(s))}\n`),L.exit(s.status===`completed`?0:1)),s.status===`completed`&&(St({runId:e,name:s.name,status:`completed`,result:s.result,tokens:s.ledger,taskCount:s.taskCount},t.json),L.exit(0)),s.status===`stopped`&&(t.json?k({runId:e,name:s.name,status:`stopped`,taskCount:s.taskCount}):L.stdout.write(`\n${N.dim(`[flow] run ${e} stopped — resume: coder flow resume ${e}`)}\n`),L.exit(1)),L.stdout.write(`\n${N.red(`error:`)} ${s.error??`unknown error`}\n`),L.stdout.write(`\n${h([`Resume: coder flow resume ${e}`],N)}\n`),L.exit(1)}const bt={cwd:f,json:d,args:f,wait:d,concurrency:f,"max-tasks":f,"dry-run":d},$=e=>e?Number(e):void 0;async function xt(e,t,n){let r=L.env[X];if(r&&(delete L.env[X],await _t(r,t)),e[`dry-run`])return!1;let i=n(),a=vt(i,e);return e.wait&&await yt(i.runId,e,a),!0}function St(e,t){if(t){k(e);return}let n=!L.stdout.isTTY,r=n?``:`${N.dim(`└─`)} `;L.stdout.write(`${r}${Z(`completed`,n)} run ${N.cyan(e.runId)} completed ${N.dim(`(${e.taskCount} tasks)`)}\n`),L.stdout.write(`\n${ae(e.result)}\n`),Tt(e.tokens)}function Ct(e,t,n){if(e instanceof S&&e.code===`flow-failed`){let r=n?`
58
+ [flow] dry-run ended early: a downstream step depends on real task output (stub it or run for real).`:``;y(`[flow] ${t} ${e.runId} failed: ${e.message}${r}`,{hint:`Resume${t===`resume`?` again`:``}: coder flow resume ${e.runId}`})}throw e}async function wt(e){let{options:t,positionals:n}=c(e,B.object(bt)),[r,...i]=n;r||y(`Missing flow name or path.`,{hint:[`Usage: coder flow run <name|path>`,`List: coder flow discover`]});let a=p(t);$e(pe(r,a).path);let o={args:Ze(t.args,i),cwd:a,dryRun:t[`dry-run`],concurrency:$(t.concurrency),maxTasks:$(t[`max-tasks`])};if(!await xt(t,o,()=>fe(r,o)))try{St(await ke(r,o,ht(t)),t.json)}catch(e){Ct(e,`run`,o.dryRun)}}function Tt(e){let t=Object.keys(e);if(t.length){L.stdout.write(`\n${N.bold(`Tokens:`)}\n`);for(let n of t)L.stdout.write(` ${N.dim(ie(e[n],n))}\n`)}}async function Et(e){let{options:t,positionals:n}=c(e,B.object({cwd:f,json:d,archived:d,limit:a}));A(n,0,`flow list`);let r=t.limit===`all`?void 0:t.limit,{runs:i,clipped:o}=ye({archived:t.archived,limit:r});if(t.json){k(i);return}if(!i.length){L.stdout.write(t.archived?`No archived flow runs.
59
+ `:`No recent flow runs.
60
+ `),L.stdout.write(`\n${h([`Run one: coder flow run <name>`,`Runnable flows: coder flow discover`],N)}\n`);return}let s=N;L.stdout.write(s.bold(s.light(`${`run-id`.padEnd(24)} ${`name`.padEnd(20)} ${`status`.padEnd(10)} ${`tasks`.padEnd(9)} ${`tokens`.padEnd(10)} age\n`)));for(let e of i){let t=Object.values(e.ledger).reduce((e,t)=>e+t.total,0);L.stdout.write(`${s.cyan(_(e.runId,24))} ${_(e.name,20)} ${b(e.status,10)} ${s.light(_(`${e.taskCount} tasks`,9))} ${s.light(_(t?`${v(t)} tok`:`-`,10))} ${s.light(E(ne(e.startedAt)))}\n`)}o&&L.stdout.write(s.dim(`\n... ${o} more not shown (--limit ${r})\n`)),L.stdout.write(`\n${h([`Result: coder flow result <run-id>`,`Tasks: coder list`,`Runnable flows: coder flow discover`],s)}\n`)}async function Dt(e){let{options:t,positionals:n}=c(e,B.object({cwd:f,json:d}));A(n,0,`flow discover`);let r=p(t),i=m(r);if(t.json){k(i);return}if(!i.length){L.stdout.write(`No flows found in .coder/flows/ (workspace) or ~/.coder/flows/ (global).
61
+ `),L.stdout.write(`\n${h([`Authoring guide: coder docs flows`],N)}\n`);return}let a=N;L.stdout.write(a.bold(a.light(`${`name`.padEnd(24)} ${`scope`.padEnd(10)} path\n`)));for(let e of i){let t=e.scope===`workspace`?z.relative(r,e.path)||e.path:e.path.replace(Ue.homedir(),`~`);L.stdout.write(`${a.cyan(e.name.padEnd(24))} ${a.light(e.scope.padEnd(10))} ${a.light(t)}\n`)}L.stdout.write(`\n${h([`Run one: coder flow run <name>`,`Recent runs: coder flow list`],a)}\n`)}function Ot(e){let t=Ee(`${P(e.runId)}/journal.jsonl`);return{...e,journal:t.map(e=>({kind:e.kind,taskId:e.taskId,tokens:e.tokens}))}}function kt(e,t,n=`all`){if(t){k(Ot(e));return}let r=N,a=!L.stdout.isTTY;L.stdout.write(`${r.bold(`Flow`)} ${r.cyan(e.name)} ${r.dim(`(${e.runId})`)} — ${r.bold(b(e.status))}\n`);let o=xe(e.runId),s=o.filter(e=>i.includes(e.status)).length,c=e.status===`running`?`${s}/${o.length} tasks`:`${e.taskCount} tasks`;if(L.stdout.write(`${r.dim(`started ${e.startedAt}${e.endedAt?` · ended ${e.endedAt}`:``} · ${c}`)}\n`),n!==0){let t=at(e.runId),i=new Map,s=new Map,c=new Map,l=[];for(let e of t)if(e.kind===`task-start`){let t={name:it(e.name,e.prompt),agent:e.agent,depth:e.depth??0};i.set(e.taskId,t),s.set(e.taskId,t)}else if(e.kind===`task-end`){s.delete(e.taskId);let t=i.get(e.taskId);l.push({depth:t?.depth??0,body:Q(Z(e.status,a),t?.name??null,e.taskId,e.tokens,t?.agent)})}else if(e.kind===`gate-start`)c.set(e.gateId,{cmd:e.cmd,depth:e.depth??0});else if(e.kind===`gate`)e.gateId&&c.delete(e.gateId),l.push({depth:e.depth??0,body:ot(e,a)});else if(e.kind===`log`)for(let t of e.message.split(`
62
+ `))l.push({depth:e.depth??0,body:r.light(t),log:!0});else e.kind===`flow-start`&&l.push({depth:e.depth-1,body:r.bold(`flow ${e.name}`)});for(let[e,t]of s)l.push({depth:t.depth??0,body:Q(Z(`running`,a),t.name,e,null,t.agent)+(a?``:` ${r.light(`running`)}`)});for(let e of c.values())l.push({depth:e.depth,body:st(e.cmd,Z(`running`,a))+(a?``:` ${r.light(`running`)}`)});if(!l.length)for(let t of n===`all`?o:xe(e.runId,n))l.push({depth:0,body:Q(Z(t.status,a),t.name,t.taskId??`-`,t.tokens)});let u=pt(l,a),d=n===`all`?u:u.slice(-n);d.length&&L.stdout.write(`\n${d.join(`
63
+ `)}\n`)}e.endedAt&&e.result!==void 0&&L.stdout.write(`\n${r.bold(`Result:`)}\n${ae(e.result)}\n`),e.error&&L.stdout.write(`\n${r.red(`error:`)} ${e.error}\n`),Tt(e.ledger);let l=e.status===`running`?[`Follow live: coder flow stream ${e.runId}`,`Stop it: coder flow stop ${e.runId}`]:e.status===`stopped`||e.status===`failed`?[`Resume: coder flow resume ${e.runId}`]:[];l.length&&L.stdout.write(`\n${h(l,r)}\n`)}async function At(e){let{options:t,positionals:n}=c(e,B.object({cwd:f,json:d,tail:o})),r=n[0]?j(n[0]):M();if(!r){if(t.json){k(null);return}y(n[0]?`No flow run "${n[0]}".`:`No flow runs yet.`,{hint:`Run one: coder flow run <name>`})}kt(r,!!t.json,t.tail)}async function jt(e){let{options:t,positionals:n}=c(e,B.object({cwd:f,json:d,tail:o})),r=n[0]?j(n[0]):M();r||y(n[0]?`No flow run "${n[0]}".`:`No flow runs yet.`,{hint:`Run one: coder flow run <name>`}),await yt(r.runId,{json:t.json,stream:!0,tail:t.tail})}async function Mt(e){let{options:t,positionals:n}=c(e,B.object({cwd:f,json:d,"keep-tasks":d}));A(n,1,`flow stop`);try{let e=await De(n[0],{keepTasks:t[`keep-tasks`]});if(t.json){k(e);return}let r=N;e.status===`failed`?L.stdout.write(`${r.dim(`[flow]`)} run ${r.cyan(e.runId)} orchestrator died — marked ${b(`failed`)}.\n`):L.stdout.write(`${r.dim(`[flow]`)} run ${r.cyan(e.runId)} ${b(e.status)}.\n`),e.stoppedTasks.length&&L.stdout.write(`${r.dim(`[flow]`)} stopped tasks: ${e.stoppedTasks.join(`, `)}\n`),e.keptTasks.length&&L.stdout.write(`${r.dim(`[flow]`)} left running: ${e.keptTasks.join(`, `)}\n`),L.stdout.write(`\n${h([`Resume: coder flow resume ${e.runId}`],r)}\n`)}catch(e){throw e instanceof S&&e.code===`flow-failed`&&y(e.message,e.hint?{hint:e.hint}:{}),e}}async function Nt(e){let{options:t,positionals:n}=c(e,B.object(bt)),r=n[0]?j(n[0]):M();r||y(n[0]?`No flow run "${n[0]}".`:`No flow runs to resume.`,{hint:`Run one: coder flow run <name>`}),$e(r.script);let i={cwd:p(t),dryRun:t[`dry-run`],concurrency:$(t.concurrency),maxTasks:$(t[`max-tasks`]),...t.args===void 0?{}:{args:Ze(t.args,[])}};if(!await xt(t,i,()=>fe(``,i,r.runId)))try{St(await se(r.runId,i,ht(t)),t.json)}catch(e){Ct(e,`resume`,i.dryRun)}}function Pt(e){let t=j(e);return t||y(`No flow run "${e}".`,{hint:`Recent runs: coder flow list`}),(t.status===`running`||t.status===`queued`)&&y(`Run ${t.runId} is still running.`,{hint:`Stop it first: coder flow stop ${t.runId}`}),t}async function Ft(e){let{options:t,positionals:n}=c(e,B.object({cwd:f,json:d,"all-stopped":d}));if(A(n,1,`flow archive`),t[`all-stopped`]){let e=ue().filter(e=>e.status!==`running`&&e.status!==`queued`);for(let t of e)ge(t);let n=e.map(e=>e.runId);if(t.json){k({archived:n,count:n.length});return}L.stdout.write(n.length?`Archived ${n.length} stopped run${n.length===1?``:`s`}.\n`:`${N.dim(`No stopped runs to archive.`)}\n`);return}let r=n[0];r||y(`Missing run id.`,{hint:[`Archive one: coder flow archive <run-id>`,`Archive all stopped: coder flow archive --all-stopped`]});let i=Pt(r);if(ge(i),t.json){k({runId:i.runId,archived:!0});return}L.stdout.write(`Archived run ${N.cyan(i.runId)}.\n`)}async function It(e){let{options:t,positionals:n}=c(e,B.object({cwd:f,json:d,"all-archived":d}));if(A(n,1,`flow delete`),t[`all-archived`]){let e=we().filter(e=>ce(e.runId)).map(e=>e.runId);if(t.json){k({deleted:e,count:e.length});return}L.stdout.write(e.length?`Deleted ${e.length} archived run${e.length===1?``:`s`}.\n`:`${N.dim(`No archived runs to delete.`)}\n`);return}let r=n[0];r||y(`Missing run id.`,{hint:[`Delete one: coder flow delete <run-id>`,`Delete all archived: coder flow delete --all-archived`]});let i=Pt(r);if(ce(i.runId),t.json){k({runId:i.runId,deleted:!0});return}L.stdout.write(`Deleted run ${N.cyan(i.runId)}.\n`)}const Lt={run:wt,list:Et,discover:Dt,result:At,stream:jt,stop:Mt,resume:Nt,archive:Ft,delete:It};async function Rt(e){let[t,...n]=e;if(t===void 0||t===`help`||t===`-h`||t===`--help`){L.stdout.write(G());return}let r=Lt[t];if(r||(L.stdout.write(G()),L.stdout.write(`
64
+ `),y(`Unknown flow subcommand "${t}".`,{hint:`Run a flow: coder flow run <name>`})),Y(n)){L.stdout.write(K(`flow ${t}`)??G());return}await r(n)}async function zt(i){let{options:a,positionals:s}=c(i,B.object({...u,tail:o,wait:d}));A(s,1,`task result`);let l=p(a),f=T(l,s[0]);if(a.wait){e.includes(f.status)&&L.stderr.write(`${N.dim(`[coder] waiting for task ${f.id} to finish...`)}\n`);let t=await Te(l,f);f=t.job,t.reason===`approval`&&de(f.id,t.approval,a.json)}let{steps:m,result:g}=re(l,f.id,{tail:a.tail}),_=Oe(n(l,f.id)).filter(e=>!e.response),v=e.includes(f.status),y=v?r(l,f.id,1)[0]:void 0,x=v?t(l,f):f.updatedAt,S=ne(x),C=v&&_.length===0&&S>6e5,w=()=>{a.wait&&L.exit(f.status===`completed`?0:1)};if(a.json)return k({taskId:f.id,name:f.name??null,prompt:f.prompt??null,system:f.system??null,status:f.status,agent:f.agent,model:f.model??null,effort:f.effort??null,permissions:f.permissions??null,cwd:f.cwd??null,...v?{idleMs:S,lastActivityAt:x??null,stalled:C}:{},pendingApprovals:_.map(e=>({id:e.id,summary:e.summary})),...m.length?{steps:m}:{},result:g}),w();let D=N,O=[`${D.dim(`task`)} ${D.cyan(f.id)}`,...f.name?[`${D.dim(`name`)} ${f.name}`]:[],`${D.dim(`status`)} ${b(f.status)}`,`${D.dim(`agent`)} ${je(f)}`,...ee(f,D),...g?.tokens?[`${D.dim(`tokens`)} ${ie(g.tokens,g.model??f.model)}`]:[]];if(f.prompt&&O.push(``,...oe(f.prompt,D)),_.length){O.push(``,D.dim(`pending approvals:`));for(let e of _)O.push(` ${D.cyan(e.id)} ${e.summary}`)}if(m.length){O.push(``,D.dim(`steps:`));for(let e of m){let t=e.message??e.kind;t&&O.push(` ${D.dim(be(t))}`)}}if(v&&y){let e=y.message??y.kind??``;O.push(`${D.dim(`last`)} ${D.dim(`${be(e)} (${E(S)} ago)`)}`)}if(O.push(``),g?O.push(te({...g,error:g.error??void 0},f.error,`(no final message)`,D)):v?O.push(D.dim(C?`Result pending, but no progress for ${E(S)} — the task may be stalled.`:`Result pending — task is still running.`)):O.push(D.dim(`(no result)`)),v&&!a.wait){let e=[`Wait for it: coder task result ${f.id} --wait`,`Follow live: coder task stream ${f.id}`];C&&e.push(`Check the transcript: coder task result ${f.id} --tail all`),O.push(``,h(e,D))}return L.stdout.write(`${O.join(`
65
+ `)}\n`),g?.touchedFiles?.length&&L.stderr.write(`[coder] touched files: ${g.touchedFiles.join(`, `)}\n`),w()}async function Bt(e){let{options:t,positionals:r}=c(e,B.object(u));A(r,1,`task approvals`);let i=p(t),a=T(i,r[0]),o=Oe(n(i,a.id)).map(e=>({id:e.id,summary:e.summary,createdAt:e.createdAt,answered:e.response?.decision??null}));if(t.json){k(o);return}if(!o.length){L.stdout.write(`${N.dim(`No approvals for task ${a.id}.`)}\n`);return}let s=N;for(let e of o){let t=e.answered??`pending`;L.stdout.write(`${s.cyan(e.id)} ${t.padEnd(8)} ${s.dim(e.summary)}\n`)}}async function Vt(e){let{options:t,positionals:r}=c(e,B.object({...u,deny:d}));A(r,2,`task approve`);let i=p(t),[a,o]=r;(!a||!o)&&y(`Missing task id or approval id.`,{hint:[`List them: coder task approvals <task-id>`,`Usage: coder task approve <task-id> <id> [--deny]`]});let s=T(i,a),l=t.deny?`decline`:`accept`;if(Ae(n(i,s.id),o,l),t.json){k({taskId:s.id,approvalId:o,decision:l});return}L.stdout.write(`${t.deny?`Denied`:`Approved`} ${N.cyan(o)} on task ${N.cyan(s.id)}.\n`)}L.stdout.on(`error`,e=>{throw e.code===`EPIPE`&&L.exit(0),e});const Ht={run:Ne,list:Be,stream:I,result:zt,steer:Pe,stop:O,archive:g,delete:ze,approvals:Bt,approve:Vt};async function Ut(e){let[t,...n]=e;if(t===void 0||t===`help`||t===`-h`||t===`--help`){L.stdout.write(q());return}let r=Ht[t];if(r||(L.stdout.write(q()),y(`Unknown task subcommand "${t}".`,{hint:`Run a task: coder run "<text>"`})),Y(n)){L.stdout.write(K(`task ${t}`)??q());return}await r(n)}const Wt={task:Ut,flow:Rt,run:Ne,list:Be,stream:I,result:zt,steer:Pe,stop:O,archive:g,delete:ze,approvals:Bt,approve:Vt,watch:I,config:Ie,"setup-host":F,"host-setup":F,setup:F,model:Fe,docs:Le,upgrade:Re,update:Re,_worker:Me,_refreshUpdate:async()=>he(l()),_archiveSweep:C};async function Gt(){let[e,...t]=L.argv.slice(2);if(e===`--version`||e===`-v`){L.stdout.write(`${l()}\n`);return}if(e===void 0||e===`help`||e===`--help`||e===`-h`){if(t[0]===`task`&&t[1]===void 0){L.stdout.write(q());return}if(t[0]===`model`&&t[1]===void 0){L.stdout.write(Je());return}if(t[0]===`flow`&&t[1]===void 0){L.stdout.write(G());return}let e=t.map(e=>(e===`task`||e===`model`||e===`flow`)&&t[1]?`${e} ${t[1]}`:W[e]??e).find(e=>U[e]);L.stdout.write(e&&K(e)||J());return}e!==`_worker`&&e!==`_refreshUpdate`&&e!==`_archiveSweep`&&w(l(),s);let n=Wt[e];if(n||(L.stdout.write(J()),L.stdout.write(`
66
+ `),y(`Unknown command "${e}".`,{hint:`See all commands: coder --help`})),e===`model`&&Y(t)){let e=t.find(e=>!e.startsWith(`-`));L.stdout.write(e&&K(`model ${e}`)||Je());return}if(e!==`task`&&e!==`flow`&&Y(t)){let t=W[e]??e;L.stdout.write(K(t)??J());return}try{await n(t)}catch(t){let n=t instanceof Error?t.message:String(t);throw/^(Unknown option|Missing value)/.test(n)&&U[W[e]??e]&&y(n,{hint:`Help: coder ${e} --help`}),t}}Gt().catch(e=>{L.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),L.exit(1)});export{};