@crewx/sdk 0.9.0-rc.215 → 0.9.0-rc.217

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.
@@ -42,7 +42,7 @@ ${r.join(`
42
42
  AND ((${t.cleanup_pending} = 1 AND ${t.vault_handle} IS NOT NULL)
43
43
  OR (${t.cleanup_pending} = 0 AND ${t.vault_handle} IS NULL)))
44
44
  ))
45
- )`),conflictSupersededCheck:check("app_sync_conflicts_superseded_ck",sql`${t.state} != 'superseded' OR ${t.superseded_by} IS NOT NULL`),conflictResolutionCheck:check("app_sync_conflicts_resolution_ck",sql`(${t.resolution_request_id} IS NULL AND ${t.resolution_choice} IS NULL) OR (length(${t.resolution_request_id}) BETWEEN 1 AND 128 AND ${t.resolution_choice} IN ('keep_local', 'use_cloud', 'keep_both'))`),conflictTimeCheck:check("app_sync_conflicts_time_ck",sql`${t.updated_at} >= ${t.created_at}`),conflictBindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[wn.binding_id]}).onDelete("cascade"),conflictIdentityUnique:uniqueIndex("app_sync_conflicts_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.local_version,t.remote_revision,t.remote_fingerprint),conflictLookup:index("app_sync_conflicts_lookup_idx").on(t.account_key,t.binding_id,t.state,t.updated_at)})),sqliteTable("app_sync_conflict_resolutions",{request_id:text("request_id").primaryKey().notNull(),conflict_id:text("conflict_id").notNull(),account_key:text("account_key").notNull(),human_identity:text("human_identity").notNull(),choice:text("choice").notNull(),expected_local_version:text("expected_local_version").notNull(),expected_remote_revision:integer("expected_remote_revision").notNull(),expected_remote_fingerprint:text("expected_remote_fingerprint").notNull(),state:text("state").notNull().default("pending"),error_code:text("error_code"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({resolutionRequestIdCheck:check("app_sync_conflict_resolutions_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),resolutionAccountCheck:check("app_sync_conflict_resolutions_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resolutionIdentityCheck:check("app_sync_conflict_resolutions_human_identity_ck",sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),resolutionChoiceCheck:check("app_sync_conflict_resolutions_choice_ck",sql`${t.choice} IN ('keep_local', 'use_cloud', 'keep_both')`),resolutionLocalVersionCheck:check("app_sync_conflict_resolutions_local_version_ck",sql`length(${t.expected_local_version}) BETWEEN 1 AND 256 AND instr(${t.expected_local_version}, '/') = 0 AND instr(${t.expected_local_version}, char(92)) = 0`),resolutionRemoteCheck:check("app_sync_conflict_resolutions_remote_ck",sql`${t.expected_remote_revision} >= 0 AND length(${t.expected_remote_fingerprint}) = 71 AND substr(${t.expected_remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.expected_remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),resolutionStateCheck:check("app_sync_conflict_resolutions_state_ck",sql`${t.state} IN ('pending', 'unknown', 'resolved', 'stale', 'failed')`),resolutionTimeCheck:check("app_sync_conflict_resolutions_time_ck",sql`${t.updated_at} >= ${t.created_at}`),resolutionConflictFk:foreignKey({columns:[t.conflict_id],foreignColumns:[S_.conflict_id]}).onDelete("cascade"),resolutionConflictIdx:index("app_sync_conflict_resolutions_conflict_idx").on(t.conflict_id,t.created_at),resolutionActiveUnique:uniqueIndex("app_sync_conflict_resolutions_one_active_uq").on(t.conflict_id).where(sql`${t.state} IN ('pending', 'unknown')`)})),sqliteTable("app_sync_account_data_purges",{request_id:text("request_id").primaryKey().notNull(),binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),root_fingerprint:text("root_fingerprint").notNull(),human_identity:text("human_identity").notNull(),state:text("state").notNull().default("pending"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({purgeRequestIdCheck:check("app_sync_account_data_purges_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),purgeAccountCheck:check("app_sync_account_data_purges_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),purgeWorkspaceCheck:check("app_sync_account_data_purges_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),purgeRootCheck:check("app_sync_account_data_purges_root_fingerprint_ck",sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),purgeHumanIdentityCheck:check("app_sync_account_data_purges_human_identity_ck",sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),purgeStateCheck:check("app_sync_account_data_purges_state_ck",sql`${t.state} IN ('pending', 'complete')`),purgeTimeCheck:check("app_sync_account_data_purges_time_ck",sql`${t.updated_at} >= ${t.created_at}`),purgeAccountIndex:index("app_sync_account_data_purges_account_idx").on(t.account_key,t.state,t.updated_at)}));});var bd=x(()=>{g();sqliteTable("route_states",{workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),config_revision:text("config_revision").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),updated_at:text("updated_at").notNull()},t=>({pk_route_state_workspace:primaryKey({columns:[t.workspace_key,t.route_id]})})),sqliteTable("route_sticky_bindings",{workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),thread_id:text("thread_id").notNull(),candidate_id:text("candidate_id").notNull(),updated_at:text("updated_at").notNull()},t=>({uniq_route_sticky_thread:uniqueIndex("uniq_route_sticky_thread").on(t.workspace_key,t.route_id,t.thread_id),idx_route_sticky_candidate:index("idx_route_sticky_candidate").on(t.workspace_key,t.route_id,t.candidate_id)})),sqliteTable("route_decisions",{id:text("id").primaryKey(),workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),task_id:text("task_id").notNull(),config_revision:text("config_revision").notNull(),candidate_id:text("candidate_id").notNull(),provider:text("provider").notNull(),model:text("model").notNull(),reason:text("reason").notNull(),eligible_ids:text("eligible_ids").notNull(),blocked_causes:text("blocked_causes").notNull(),link_errors:text("link_errors").notNull(),created_at:text("created_at").notNull()},t=>({uniq_route_task_decision:uniqueIndex("uniq_route_task_decision").on(t.workspace_key,t.route_id,t.task_id),idx_route_decisions_workspace_created:index("idx_route_decisions_workspace_created").on(t.workspace_key,t.route_id,t.created_at)})),sqliteTable("route_quota_observations",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),model:text("model"),status:text("status",{enum:["ok","blocked"]}).notNull(),source:text("source").notNull(),reset_at:text("reset_at"),observed_at:text("observed_at").notNull()},t=>({uniq_route_quota_observation:uniqueIndex("uniq_route_quota_observation").on(t.provider,t.account_ref,t.model,t.source),idx_route_quota_observations_reset:index("idx_route_quota_observations_reset").on(t.reset_at)}));});var on=x(()=>{g();Gr();kn();Ma();Ha();Xn();Fa();Wa();Ga();Ka();Ja();Va();Qa();Za();td();rd();od();id();ad();cd();pd();ms();kd();Td();wd();Id();Ad();Nd();Od();vd();Cd();xd();bd();});function or(t){return typeof t=="string"&&Pt.includes(t)}function Dd(t){if(!t||!t.includes("workflow"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.workflowRunId;if(typeof r=="string"&&r!=="")return r;let o=n.workflow;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let s=o.exec_id;if(typeof s=="string"&&s!=="")return s}return null}var Pt,ro=x(()=>{g();Pt=["workflow_card","workflow_ui_instance","workflow_run"];});var En,As,Pd,Ns=x(()=>{g();En={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5-5":{input:4,cachedInput:.2,output:20},"claude-opus-5-5-medium":{input:4,cachedInput:.2,output:20},"claude-opus-5":{input:5,cachedInput:.5,output:25},"claude-opus-4-8":{input:5,cachedInput:.5,output:25},"claude-opus-4-7":{input:5,cachedInput:.5,output:25},"claude-opus-4-6":{input:5,cachedInput:.5,output:25},"claude-sonnet-5-5":{input:2,cachedInput:.1,output:10},"claude-sonnet-5-5-medium":{input:2,cachedInput:.1,output:10},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-5-5":{input:.1,cachedInput:.01,output:.5},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-6.1-sol":{input:2,cachedInput:.1,output:10},"gpt-6.1-terra":{input:1,cachedInput:.05,output:5},"gpt-6-sol":{input:2,cachedInput:.2,output:10},"gpt-6-luna":{input:.1,cachedInput:.01,output:.5},"gpt-5.6-sol":{input:4,cachedInput:.4,output:20},"gpt-5.6-terra":{input:2,cachedInput:.2,output:12},"gpt-5.6-luna":{input:.2,cachedInput:.02,output:1.2},"gpt-5.5":{input:5,cachedInput:.5,output:30},"gpt-5.4":{input:2.5,cachedInput:.25,output:15},"gpt-5.4-mini":{input:.75,cachedInput:.075,output:4.5},"gpt-5.3-codex":{input:1.75,cachedInput:.175,output:14},"gpt-5-mini":{input:.4,cachedInput:.1,output:1.6},"gpt-4.1":{input:2,cachedInput:.5,output:8},"gpt-4o":{input:2.5,cachedInput:1.25,output:10},"glm-5.3-flash":{input:.15,cachedInput:.03,output:.5},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"deepseek-v4.1-flash":{input:.3,cachedInput:.006,output:1.2},"qwen3.8-flash":{input:.164,cachedInput:.018,output:.514},"minimax-m3":{input:.3,cachedInput:.06,output:1.2},"kimi-k2.7-code":{input:.95,cachedInput:.19,output:4},"gemini-3.7-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-3.6-flash":{input:1.5,cachedInput:.15,output:7.5},"grok-4.7":{input:2,cachedInput:.5,output:6},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},As=new Set(["gpt-5.3-codex-spark","claude-opus-4-6-thinking","gpt-oss-120b","glm-5.3-flash-free","deepseek-v4.1-flash-free"]),Pd=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-haiku-5-5","claude-opus-4-6","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7","claude-opus-4-7[1m]","claude-opus-4-8","claude-opus-4-8[1m]","claude-opus-5","claude-opus-5-5","claude-opus-5-5-medium","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","claude-sonnet-5-5-medium","deepseek-v4.1-flash","deepseek-v4.1-flash-free","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","gemini-3.8-flash","gemini-4-argon","glm-5.1","glm-5.2","glm-5.3-flash","glm-5.3-flash-free","gpt-4.1","gpt-4o","gpt-5-mini","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini","gpt-5.5","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra","gpt-6-luna","gpt-6-sol","gpt-6.1-sol","gpt-6.1-terra","gpt-oss-120b","grok-4.5","grok-4.6","grok-4.7","kimi-k2.7-code","minimax-m3","qwen3.8-flash"]);});function Os(t){let e=t.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let n=e.lastIndexOf("/");return n>=0&&(e=e.slice(n+1)),e=e.replace(/-\d{8}$/,""),e}function O_(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),sr;let e=Os(t),n=N_[e];if(n)return oo[n]??En[n]??sr;if(oo[e])return oo[e];if(En[e])return En[e];if(As.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),sr;if(Pd.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),sr;let r={...En,...oo};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),sr}function v_(t,e,n,r=0,o){let s=O_(n),i=Math.min(r,t),d=(t-i)*s.input/1e6,u=i*s.cachedInput/1e6,l=e*s.output/1e6;return d+u+l}function Ld(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:v_(e??0,n??0,o,r??0)}var N_,sr,oo,so=x(()=>{g();Ns();Ns();N_={opus:"claude-opus-4-8",sonnet:"claude-sonnet-4-6",haiku:"claude-haiku-4-5","codex-mini":"gpt-5.3-codex",codex:"gpt-5.3-codex"},sr={input:0,cachedInput:0,output:0},oo={};});function Ud(t){if(!t||!t.includes("schedule_id"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.trigger;if(typeof r!="string"||!C_.includes(r))return null;let o=n.schedule_id;return typeof o=="string"&&o!==""?o:null}var C_,qd=x(()=>{g();C_=["cron","cron_manual"];});function Cs(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function Fd(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function io(t){return Number.isSafeInteger(t)&&t>0}function M_(t){let e=t.trim();if(!e)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(e);return n?.[1]??n?.[2]??e.split(/\s+/,1)[0]??""}function $_(t,e,n){let r=n==="win32"?t.toLowerCase():t,o=n==="win32"?e.toLowerCase():e;if(!o.trim())return false;if(o==="agy"){let s=M_(t).split(/[\\/]/).pop()??"",i=n==="win32"?s.toLowerCase():s;return i==="agy"||n==="win32"&&(i==="agy.exe"||i==="agy.cmd")}return r.includes(o)}function H_(t,e,n){return e.some(r=>$_(t,r,n))}function U_(t,e){try{let n=spawnSync(t,e,{encoding:"utf8",timeout:vs,windowsHide:!0});return {status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",error:n.error}}catch(n){return {status:null,stdout:"",stderr:"",error:Cs(n)}}}function q_(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(u){n({status:null,stdout:"",stderr:"",error:Cs(u)});return}let o="",s="",i=false,c,d=setTimeout(()=>{try{r.kill();}catch{}c({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${vs}ms`)});},vs);c=u=>{i||(i=true,clearTimeout(d),n(u));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",u=>{o+=String(u);}),r.stderr?.on("data",u=>{s+=String(u);}),r.once("error",u=>{c({status:null,stdout:o,stderr:s,error:u});}),r.once("close",u=>{c({status:u,stdout:o,stderr:s});});})}async function xs(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):q_(t,e)}function F_(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function B_(){return new Promise(t=>{setImmediate(t);})}function Lt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return Fd(n)==="ESRCH"?"not_found":Fd(n)==="EPERM"?"alive":"unknown"}}function W_(t,e){let n=Lt(-t,e),r=Lt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function Wd(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??P_),i=Date.now()+o,c,d=o===0,u=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(l=>{c=setTimeout(l,o);});u.then(()=>{d=true;});try{for(await B_();;){let l=W_(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([u,F_(Math.min(s,p))]);}}finally{c!==void 0&&clearTimeout(c);}}async function Bd(t,e,n,r,o){let s=await Wd(t,e,o.hardConfirmMs??L_,{...o,sleep:void 0});return s==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:s==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function Gd(t,e,n={}){if(!io(t))return "unknown";let r=n.platform??process.platform,o=r==="win32"?"powershell.exe":"ps",s=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],i;try{i=await xs(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let c=i.stdout.trim();return c?H_(c,e,r)?"owned":"not_owned":"not_found"}function z_(t){let e=G_.exec(t.trim());if(!e)return;let[,n="0",r="0",o="0",s="0"]=e;return ((Number(n)*24+Number(r))*60+Number(o))*60+Number(s)}function J_(t){let e=t.trim(),n=K_.exec(e);if(n){let[,o,s,i,c,d,u,l,p]=n;return Date.UTC(Number(o),Number(s)-1,Number(i),Number(c),Number(d),Number(u),Math.trunc(Number(l)/1e3))-Number(p)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function jd(t,e){return e==="win32"?{command:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write($p.CreationDate.ToUniversalTime().ToString('o')) }`]}:{command:"ps",args:["-p",String(t),"-o","pgid=","-o","etime=","-o","stat="]}}function Kd(t,e,n){if(t.error)return {status:"unknown"};let r=t.stdout.trim();if(!r)return t.status===0||t.status===1?{status:"not_found"}:{status:"unknown"};if(t.status!==0)return {status:"unknown"};if(e==="win32"){let i=J_(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let o=j_.exec(r),s=o?z_(o[2]):void 0;return !o||s===void 0?{status:"unknown"}:o[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-s*1e3,groupId:Number(o[1])}}function zd(t,e={}){if(!io(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=jd(t,n),s=e.runCommand??U_,i;try{i=s(r,o);}catch{return {status:"unknown"}}return Kd(i,n,Date.now())}async function Jd(t,e={}){if(!io(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=jd(t,n),s;try{s=await xs(r,o,e);}catch{return {status:"unknown"}}return Kd(s,n,Date.now())}async function $t(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=_=>({status:"failed",pid:t,method:r,error:_});if(!io(t))return o("Invalid process ID");let s=e.kill??process.kill,i=Lt(t,s);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let _;try{_=await xs("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){_={status:null,stdout:"",stderr:"",error:Cs(m)};}let h=Lt(t,s);return h==="not_found"?_.status===0&&!_.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let c,d=e.signal??"SIGKILL";try{s(-t,d);}catch(_){c=_;}if(d==="SIGKILL")return Bd(t,s,c,r,e);if(await Wd(t,s,e.graceMs??D_,e)==="not_found")return c?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{s(-t,"SIGKILL");}catch(_){l=_;}let p=await Bd(t,s,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?c?p:{status:"terminated",pid:t,method:r}:o(p.error??"Process termination failed")}var vs,Mt,D_,P_,L_,ao,G_,j_,K_,co=x(()=>{g();vs=3e3,Mt="SIGINT",D_=2e3,P_=25,L_=100;ao=3e3,G_=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,j_=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,K_=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function Zd(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new f("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new f("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Yd(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new f("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>Zd(r,o))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function ec(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new f("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new f("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new f("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Qd(t){return {taskId:t.id,source:ec(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function ef(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var uo,tc=x(()=>{g();xt();zt();Jt();Ct();on();uo=class extends Ce{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?Kt(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new f("NOT_FOUND","Database not found");let r=q(n);if(e)try{We(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new f("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,i)=>Zd(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new f("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let c=this.requireStateRowInTransaction(i,e),d=ec(c);if(d==="blob"){let _=Yd(e,c.logs);if(i.update(a).set({logs:JSON.stringify([..._,...r]),log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:c.log_revision+1,lastSeq:c.last_log_seq}}let u=c.last_log_seq+1,l=c.last_log_seq+r.length;if(i.insert(_t).values(r.map((_,h)=>({task_id:e,seq:u+h,timestamp:_.timestamp,level:_.level,message:_.message}))).run(),i.update(a).set({last_log_seq:l,log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:c.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?Qd(r):void 0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return ef(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=Qd(s);if(i.source==="blob"){let l=Yd(e,s.logs).map((p,_)=>({...p,seq:_+1}));return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let c=o.select({seq:_t.seq,timestamp:_t.timestamp,level:_t.level,message:_t.message}).from(_t).where(eq(_t.task_id,e)).orderBy(n===void 0?asc(_t.seq):desc(_t.seq)),u=(n===void 0?c.all():c.limit(n).all()).map(({seq:l,timestamp:p,level:_,message:h})=>({seq:l,timestamp:p,level:_,message:h}));return n!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var sf,lo,rc=x(()=>{g();xt();zt();Jt();Ct();on();sf=50,lo=class extends Ce{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=`${e.dbRoot}/.crewx/crewx.db`);}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(){let e=this.resolveDbPath(),n=q(e);try{return We(n.db,e),n}catch(r){throw n.close(),r}}recordAccepted(e){if(e.actorKind!=="human"||!e.workspaceId||!e.actorId||!e.agentId)return false;let n;try{n=this.openHandle();let r=e.acceptedAt??new Date().toISOString();return n.db.insert(He).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[He.workspace_id,He.actor_id,He.agent_id],set:{last_accepted_at:sql`MAX(${He.last_accepted_at}, excluded.last_accepted_at)`}}).run(),!0}catch(r){return console.error("[AgentSendHistoryRepository] Failed to record accepted agent send",r),false}finally{n?.close();}}findRecentAgents(e,n){let r;try{return r=this.openHandle(),r.db.select({agentId:He.agent_id,lastAcceptedAt:He.last_accepted_at}).from(He).where(and(eq(He.workspace_id,e),eq(He.actor_id,n))).orderBy(desc(He.last_accepted_at),asc(He.agent_id)).limit(sf).all()}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to find recent agent sends",o)}finally{r?.close();}}};});var oc=x(()=>{g();});var af,G,Ht=x(()=>{g();af=new Set(["ACCOUNT_SETTING_REQUIRED","MODEL_RETIRED","SUBSCRIPTION_REQUIRED"]),G=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=af.has(this.code)?"config":o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs,this.settingReason=o?.settingReason,this.replacementModel=o?.replacementModel,this.providerReason=o?.providerReason;}providerStr;code;kind;retryAfterMs;settingReason;replacementModel;providerReason;stdout};});var sn,bs=x(()=>{g();Ht();sn=class extends G{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function po(t){if(typeof t!="string")return;let e=t.trim();if(e)return e=e.replace(/^\s*at\s+[^\r\n]+(?:\r?\n|$)/gim,""),e=e.replace(/(^|[\r\n])\s*(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-auth-token|cookie|set-cookie)\s*:\s*[^\r\n]*/gim,`$1[HTTP HEADER ${Oe}]`),e=cf(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${Oe}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,Oe),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,Oe),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,Oe),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,Oe),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,Oe),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,Oe),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,Oe),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,Oe),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Oe),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${Oe}${r}${Oe}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${Oe}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,sc),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,sc),e=e.replace(/[\r\n]{3,}/g,`
45
+ )`),conflictSupersededCheck:check("app_sync_conflicts_superseded_ck",sql`${t.state} != 'superseded' OR ${t.superseded_by} IS NOT NULL`),conflictResolutionCheck:check("app_sync_conflicts_resolution_ck",sql`(${t.resolution_request_id} IS NULL AND ${t.resolution_choice} IS NULL) OR (length(${t.resolution_request_id}) BETWEEN 1 AND 128 AND ${t.resolution_choice} IN ('keep_local', 'use_cloud', 'keep_both'))`),conflictTimeCheck:check("app_sync_conflicts_time_ck",sql`${t.updated_at} >= ${t.created_at}`),conflictBindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[wn.binding_id]}).onDelete("cascade"),conflictIdentityUnique:uniqueIndex("app_sync_conflicts_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.local_version,t.remote_revision,t.remote_fingerprint),conflictLookup:index("app_sync_conflicts_lookup_idx").on(t.account_key,t.binding_id,t.state,t.updated_at)})),sqliteTable("app_sync_conflict_resolutions",{request_id:text("request_id").primaryKey().notNull(),conflict_id:text("conflict_id").notNull(),account_key:text("account_key").notNull(),human_identity:text("human_identity").notNull(),choice:text("choice").notNull(),expected_local_version:text("expected_local_version").notNull(),expected_remote_revision:integer("expected_remote_revision").notNull(),expected_remote_fingerprint:text("expected_remote_fingerprint").notNull(),state:text("state").notNull().default("pending"),error_code:text("error_code"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({resolutionRequestIdCheck:check("app_sync_conflict_resolutions_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),resolutionAccountCheck:check("app_sync_conflict_resolutions_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resolutionIdentityCheck:check("app_sync_conflict_resolutions_human_identity_ck",sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),resolutionChoiceCheck:check("app_sync_conflict_resolutions_choice_ck",sql`${t.choice} IN ('keep_local', 'use_cloud', 'keep_both')`),resolutionLocalVersionCheck:check("app_sync_conflict_resolutions_local_version_ck",sql`length(${t.expected_local_version}) BETWEEN 1 AND 256 AND instr(${t.expected_local_version}, '/') = 0 AND instr(${t.expected_local_version}, char(92)) = 0`),resolutionRemoteCheck:check("app_sync_conflict_resolutions_remote_ck",sql`${t.expected_remote_revision} >= 0 AND length(${t.expected_remote_fingerprint}) = 71 AND substr(${t.expected_remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.expected_remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),resolutionStateCheck:check("app_sync_conflict_resolutions_state_ck",sql`${t.state} IN ('pending', 'unknown', 'resolved', 'stale', 'failed')`),resolutionTimeCheck:check("app_sync_conflict_resolutions_time_ck",sql`${t.updated_at} >= ${t.created_at}`),resolutionConflictFk:foreignKey({columns:[t.conflict_id],foreignColumns:[S_.conflict_id]}).onDelete("cascade"),resolutionConflictIdx:index("app_sync_conflict_resolutions_conflict_idx").on(t.conflict_id,t.created_at),resolutionActiveUnique:uniqueIndex("app_sync_conflict_resolutions_one_active_uq").on(t.conflict_id).where(sql`${t.state} IN ('pending', 'unknown')`)})),sqliteTable("app_sync_account_data_purges",{request_id:text("request_id").primaryKey().notNull(),binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),root_fingerprint:text("root_fingerprint").notNull(),human_identity:text("human_identity").notNull(),state:text("state").notNull().default("pending"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({purgeRequestIdCheck:check("app_sync_account_data_purges_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),purgeAccountCheck:check("app_sync_account_data_purges_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),purgeWorkspaceCheck:check("app_sync_account_data_purges_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),purgeRootCheck:check("app_sync_account_data_purges_root_fingerprint_ck",sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),purgeHumanIdentityCheck:check("app_sync_account_data_purges_human_identity_ck",sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),purgeStateCheck:check("app_sync_account_data_purges_state_ck",sql`${t.state} IN ('pending', 'complete')`),purgeTimeCheck:check("app_sync_account_data_purges_time_ck",sql`${t.updated_at} >= ${t.created_at}`),purgeAccountIndex:index("app_sync_account_data_purges_account_idx").on(t.account_key,t.state,t.updated_at)}));});var bd=x(()=>{g();sqliteTable("route_states",{workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),config_revision:text("config_revision").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),updated_at:text("updated_at").notNull()},t=>({pk_route_state_workspace:primaryKey({columns:[t.workspace_key,t.route_id]})})),sqliteTable("route_sticky_bindings",{workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),thread_id:text("thread_id").notNull(),candidate_id:text("candidate_id").notNull(),updated_at:text("updated_at").notNull()},t=>({uniq_route_sticky_thread:uniqueIndex("uniq_route_sticky_thread").on(t.workspace_key,t.route_id,t.thread_id),idx_route_sticky_candidate:index("idx_route_sticky_candidate").on(t.workspace_key,t.route_id,t.candidate_id)})),sqliteTable("route_decisions",{id:text("id").primaryKey(),workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),task_id:text("task_id").notNull(),config_revision:text("config_revision").notNull(),candidate_id:text("candidate_id").notNull(),provider:text("provider").notNull(),model:text("model").notNull(),reason:text("reason").notNull(),eligible_ids:text("eligible_ids").notNull(),blocked_causes:text("blocked_causes").notNull(),link_errors:text("link_errors").notNull(),created_at:text("created_at").notNull()},t=>({uniq_route_task_decision:uniqueIndex("uniq_route_task_decision").on(t.workspace_key,t.route_id,t.task_id),idx_route_decisions_workspace_created:index("idx_route_decisions_workspace_created").on(t.workspace_key,t.route_id,t.created_at)})),sqliteTable("route_quota_observations",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),model:text("model"),status:text("status",{enum:["ok","blocked"]}).notNull(),source:text("source").notNull(),reset_at:text("reset_at"),observed_at:text("observed_at").notNull()},t=>({uniq_route_quota_observation:uniqueIndex("uniq_route_quota_observation").on(t.provider,t.account_ref,t.model,t.source),idx_route_quota_observations_reset:index("idx_route_quota_observations_reset").on(t.reset_at)}));});var on=x(()=>{g();Gr();kn();Ma();Ha();Xn();Fa();Wa();Ga();Ka();Ja();Va();Qa();Za();td();rd();od();id();ad();cd();pd();ms();kd();Td();wd();Id();Ad();Nd();Od();vd();Cd();xd();bd();});function or(t){return typeof t=="string"&&Pt.includes(t)}function Dd(t){if(!t||!t.includes("workflow"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.workflowRunId;if(typeof r=="string"&&r!=="")return r;let o=n.workflow;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let s=o.exec_id;if(typeof s=="string"&&s!=="")return s}return null}var Pt,ro=x(()=>{g();Pt=["workflow_card","workflow_ui_instance","workflow_run"];});var En,As,Pd,Ns=x(()=>{g();En={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5-5":{input:4,cachedInput:.2,output:20},"claude-opus-5-5-medium":{input:4,cachedInput:.2,output:20},"claude-opus-5":{input:5,cachedInput:.5,output:25},"claude-opus-4-8":{input:5,cachedInput:.5,output:25},"claude-opus-4-7":{input:5,cachedInput:.5,output:25},"claude-opus-4-6":{input:5,cachedInput:.5,output:25},"claude-sonnet-5-5":{input:2,cachedInput:.1,output:10},"claude-sonnet-5-5-medium":{input:2,cachedInput:.1,output:10},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-5-5":{input:.1,cachedInput:.01,output:.5},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-6.1-sol":{input:2,cachedInput:.1,output:10},"gpt-6.1-terra":{input:1,cachedInput:.05,output:5},"gpt-6-sol":{input:2,cachedInput:.2,output:10},"gpt-6-luna":{input:.1,cachedInput:.01,output:.5},"gpt-5.6-sol":{input:4,cachedInput:.4,output:20},"gpt-5.6-terra":{input:2,cachedInput:.2,output:12},"gpt-5.6-luna":{input:.2,cachedInput:.02,output:1.2},"gpt-5.5":{input:5,cachedInput:.5,output:30},"gpt-5.4":{input:2.5,cachedInput:.25,output:15},"gpt-5.4-mini":{input:.75,cachedInput:.075,output:4.5},"gpt-5.3-codex":{input:1.75,cachedInput:.175,output:14},"gpt-5-mini":{input:.4,cachedInput:.1,output:1.6},"gpt-4.1":{input:2,cachedInput:.5,output:8},"gpt-4o":{input:2.5,cachedInput:1.25,output:10},"glm-5.3-flash":{input:.15,cachedInput:.03,output:.5},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"deepseek-v4.1-flash":{input:.3,cachedInput:.006,output:1.2},"qwen3.8-flash":{input:.164,cachedInput:.018,output:.514},"minimax-m3":{input:.3,cachedInput:.06,output:1.2},"kimi-k2.7-code":{input:.95,cachedInput:.19,output:4},"gemini-3.8-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-4-argon":{input:4,cachedInput:.2,output:20},"gemini-3.7-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-3.6-flash":{input:1.5,cachedInput:.15,output:7.5},"grok-4.7":{input:2,cachedInput:.5,output:6},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},As=new Set(["gpt-5.3-codex-spark","claude-opus-4-6-thinking","gpt-oss-120b","glm-5.3-flash-free","deepseek-v4.1-flash-free"]),Pd=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-haiku-5-5","claude-opus-4-6","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7","claude-opus-4-7[1m]","claude-opus-4-8","claude-opus-4-8[1m]","claude-opus-5","claude-opus-5-5","claude-opus-5-5-medium","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","claude-sonnet-5-5-medium","deepseek-v4.1-flash","deepseek-v4.1-flash-free","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","gemini-3.8-flash","gemini-4-argon","glm-5.1","glm-5.2","glm-5.3-flash","glm-5.3-flash-free","gpt-4.1","gpt-4o","gpt-5-mini","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini","gpt-5.5","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra","gpt-6-luna","gpt-6-sol","gpt-6.1-sol","gpt-6.1-terra","gpt-oss-120b","grok-4.5","grok-4.6","grok-4.7","kimi-k2.7-code","minimax-m3","qwen3.8-flash"]);});function Os(t){let e=t.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let n=e.lastIndexOf("/");return n>=0&&(e=e.slice(n+1)),e=e.replace(/-\d{8}$/,""),e}function O_(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),sr;let e=Os(t),n=N_[e];if(n)return oo[n]??En[n]??sr;if(oo[e])return oo[e];if(En[e])return En[e];if(As.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),sr;if(Pd.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),sr;let r={...En,...oo};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),sr}function v_(t,e,n,r=0,o){let s=O_(n),i=Math.min(r,t),d=(t-i)*s.input/1e6,u=i*s.cachedInput/1e6,l=e*s.output/1e6;return d+u+l}function Ld(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:v_(e??0,n??0,o,r??0)}var N_,sr,oo,so=x(()=>{g();Ns();Ns();N_={opus:"claude-opus-4-8",sonnet:"claude-sonnet-4-6",haiku:"claude-haiku-4-5","codex-mini":"gpt-5.3-codex",codex:"gpt-5.3-codex"},sr={input:0,cachedInput:0,output:0},oo={};});function Ud(t){if(!t||!t.includes("schedule_id"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.trigger;if(typeof r!="string"||!C_.includes(r))return null;let o=n.schedule_id;return typeof o=="string"&&o!==""?o:null}var C_,qd=x(()=>{g();C_=["cron","cron_manual"];});function Cs(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function Fd(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function io(t){return Number.isSafeInteger(t)&&t>0}function M_(t){let e=t.trim();if(!e)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(e);return n?.[1]??n?.[2]??e.split(/\s+/,1)[0]??""}function $_(t,e,n){let r=n==="win32"?t.toLowerCase():t,o=n==="win32"?e.toLowerCase():e;if(!o.trim())return false;if(o==="agy"){let s=M_(t).split(/[\\/]/).pop()??"",i=n==="win32"?s.toLowerCase():s;return i==="agy"||n==="win32"&&(i==="agy.exe"||i==="agy.cmd")}return r.includes(o)}function H_(t,e,n){return e.some(r=>$_(t,r,n))}function U_(t,e){try{let n=spawnSync(t,e,{encoding:"utf8",timeout:vs,windowsHide:!0});return {status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",error:n.error}}catch(n){return {status:null,stdout:"",stderr:"",error:Cs(n)}}}function q_(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(u){n({status:null,stdout:"",stderr:"",error:Cs(u)});return}let o="",s="",i=false,c,d=setTimeout(()=>{try{r.kill();}catch{}c({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${vs}ms`)});},vs);c=u=>{i||(i=true,clearTimeout(d),n(u));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",u=>{o+=String(u);}),r.stderr?.on("data",u=>{s+=String(u);}),r.once("error",u=>{c({status:null,stdout:o,stderr:s,error:u});}),r.once("close",u=>{c({status:u,stdout:o,stderr:s});});})}async function xs(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):q_(t,e)}function F_(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function B_(){return new Promise(t=>{setImmediate(t);})}function Lt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return Fd(n)==="ESRCH"?"not_found":Fd(n)==="EPERM"?"alive":"unknown"}}function W_(t,e){let n=Lt(-t,e),r=Lt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function Wd(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??P_),i=Date.now()+o,c,d=o===0,u=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(l=>{c=setTimeout(l,o);});u.then(()=>{d=true;});try{for(await B_();;){let l=W_(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([u,F_(Math.min(s,p))]);}}finally{c!==void 0&&clearTimeout(c);}}async function Bd(t,e,n,r,o){let s=await Wd(t,e,o.hardConfirmMs??L_,{...o,sleep:void 0});return s==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:s==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function Gd(t,e,n={}){if(!io(t))return "unknown";let r=n.platform??process.platform,o=r==="win32"?"powershell.exe":"ps",s=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],i;try{i=await xs(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let c=i.stdout.trim();return c?H_(c,e,r)?"owned":"not_owned":"not_found"}function z_(t){let e=G_.exec(t.trim());if(!e)return;let[,n="0",r="0",o="0",s="0"]=e;return ((Number(n)*24+Number(r))*60+Number(o))*60+Number(s)}function J_(t){let e=t.trim(),n=K_.exec(e);if(n){let[,o,s,i,c,d,u,l,p]=n;return Date.UTC(Number(o),Number(s)-1,Number(i),Number(c),Number(d),Number(u),Math.trunc(Number(l)/1e3))-Number(p)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function jd(t,e){return e==="win32"?{command:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write($p.CreationDate.ToUniversalTime().ToString('o')) }`]}:{command:"ps",args:["-p",String(t),"-o","pgid=","-o","etime=","-o","stat="]}}function Kd(t,e,n){if(t.error)return {status:"unknown"};let r=t.stdout.trim();if(!r)return t.status===0||t.status===1?{status:"not_found"}:{status:"unknown"};if(t.status!==0)return {status:"unknown"};if(e==="win32"){let i=J_(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let o=j_.exec(r),s=o?z_(o[2]):void 0;return !o||s===void 0?{status:"unknown"}:o[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-s*1e3,groupId:Number(o[1])}}function zd(t,e={}){if(!io(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=jd(t,n),s=e.runCommand??U_,i;try{i=s(r,o);}catch{return {status:"unknown"}}return Kd(i,n,Date.now())}async function Jd(t,e={}){if(!io(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=jd(t,n),s;try{s=await xs(r,o,e);}catch{return {status:"unknown"}}return Kd(s,n,Date.now())}async function $t(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=_=>({status:"failed",pid:t,method:r,error:_});if(!io(t))return o("Invalid process ID");let s=e.kill??process.kill,i=Lt(t,s);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let _;try{_=await xs("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){_={status:null,stdout:"",stderr:"",error:Cs(m)};}let h=Lt(t,s);return h==="not_found"?_.status===0&&!_.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let c,d=e.signal??"SIGKILL";try{s(-t,d);}catch(_){c=_;}if(d==="SIGKILL")return Bd(t,s,c,r,e);if(await Wd(t,s,e.graceMs??D_,e)==="not_found")return c?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{s(-t,"SIGKILL");}catch(_){l=_;}let p=await Bd(t,s,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?c?p:{status:"terminated",pid:t,method:r}:o(p.error??"Process termination failed")}var vs,Mt,D_,P_,L_,ao,G_,j_,K_,co=x(()=>{g();vs=3e3,Mt="SIGINT",D_=2e3,P_=25,L_=100;ao=3e3,G_=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,j_=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,K_=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function Zd(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new f("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new f("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Yd(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new f("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>Zd(r,o))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function ec(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new f("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new f("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new f("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Qd(t){return {taskId:t.id,source:ec(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function ef(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var uo,tc=x(()=>{g();xt();zt();Jt();Ct();on();uo=class extends Ce{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?Kt(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new f("NOT_FOUND","Database not found");let r=q(n);if(e)try{We(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new f("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,i)=>Zd(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new f("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let c=this.requireStateRowInTransaction(i,e),d=ec(c);if(d==="blob"){let _=Yd(e,c.logs);if(i.update(a).set({logs:JSON.stringify([..._,...r]),log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:c.log_revision+1,lastSeq:c.last_log_seq}}let u=c.last_log_seq+1,l=c.last_log_seq+r.length;if(i.insert(_t).values(r.map((_,h)=>({task_id:e,seq:u+h,timestamp:_.timestamp,level:_.level,message:_.message}))).run(),i.update(a).set({last_log_seq:l,log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:c.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?Qd(r):void 0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return ef(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=Qd(s);if(i.source==="blob"){let l=Yd(e,s.logs).map((p,_)=>({...p,seq:_+1}));return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let c=o.select({seq:_t.seq,timestamp:_t.timestamp,level:_t.level,message:_t.message}).from(_t).where(eq(_t.task_id,e)).orderBy(n===void 0?asc(_t.seq):desc(_t.seq)),u=(n===void 0?c.all():c.limit(n).all()).map(({seq:l,timestamp:p,level:_,message:h})=>({seq:l,timestamp:p,level:_,message:h}));return n!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var sf,lo,rc=x(()=>{g();xt();zt();Jt();Ct();on();sf=50,lo=class extends Ce{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=`${e.dbRoot}/.crewx/crewx.db`);}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(){let e=this.resolveDbPath(),n=q(e);try{return We(n.db,e),n}catch(r){throw n.close(),r}}recordAccepted(e){if(e.actorKind!=="human"||!e.workspaceId||!e.actorId||!e.agentId)return false;let n;try{n=this.openHandle();let r=e.acceptedAt??new Date().toISOString();return n.db.insert(He).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[He.workspace_id,He.actor_id,He.agent_id],set:{last_accepted_at:sql`MAX(${He.last_accepted_at}, excluded.last_accepted_at)`}}).run(),!0}catch(r){return console.error("[AgentSendHistoryRepository] Failed to record accepted agent send",r),false}finally{n?.close();}}findRecentAgents(e,n){let r;try{return r=this.openHandle(),r.db.select({agentId:He.agent_id,lastAcceptedAt:He.last_accepted_at}).from(He).where(and(eq(He.workspace_id,e),eq(He.actor_id,n))).orderBy(desc(He.last_accepted_at),asc(He.agent_id)).limit(sf).all()}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to find recent agent sends",o)}finally{r?.close();}}};});var oc=x(()=>{g();});var af,G,Ht=x(()=>{g();af=new Set(["ACCOUNT_SETTING_REQUIRED","MODEL_RETIRED","SUBSCRIPTION_REQUIRED"]),G=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=af.has(this.code)?"config":o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs,this.settingReason=o?.settingReason,this.replacementModel=o?.replacementModel,this.providerReason=o?.providerReason;}providerStr;code;kind;retryAfterMs;settingReason;replacementModel;providerReason;stdout};});var sn,bs=x(()=>{g();Ht();sn=class extends G{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function po(t){if(typeof t!="string")return;let e=t.trim();if(e)return e=e.replace(/^\s*at\s+[^\r\n]+(?:\r?\n|$)/gim,""),e=e.replace(/(^|[\r\n])\s*(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-auth-token|cookie|set-cookie)\s*:\s*[^\r\n]*/gim,`$1[HTTP HEADER ${Oe}]`),e=cf(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${Oe}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,Oe),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,Oe),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,Oe),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,Oe),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,Oe),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,Oe),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,Oe),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,Oe),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Oe),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${Oe}${r}${Oe}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${Oe}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,sc),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,sc),e=e.replace(/[\r\n]{3,}/g,`
46
46
 
47
47
  `).trim(),df(e,1024)||void 0}function df(t,e){let n=new TextEncoder;if(n.encode(t).byteLength<=e)return t;let r="",o=0;for(let s of t){let i=n.encode(s).byteLength;if(o+i>e)break;r+=s,o+=i;}return r}function cf(t){let e=/\b(?:request|response|http)?\s*body\s*[:=]\s*/gim,n="",r=0,o;for(;(o=e.exec(t))!==null;){if(o.index<r)continue;let s=o.index+o[0].length,i=uf(t,s),c=i>=0?i:t.indexOf(`
48
48
  `,s)>=0?t.indexOf(`
@@ -82,7 +82,7 @@ ${r.join(`
82
82
  time_updated = excluded.time_updated
83
83
  `);r.transaction(i=>{for(let c of i)o.run(c);})(n);}finally{r.close();}}function Og(t){if(!t)return [];let e=[];for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="-s"||r==="--session"){let o=t[n+1],s=o!==void 0&&!o.startsWith("-");e.push({sessionId:s?o:void 0}),s&&(n+=1);continue}(r.startsWith("--session=")||r.startsWith("-s="))&&e.push({sessionId:r.slice(r.indexOf("=")+1)||void 0});}return e}function vg(t){if(!t)return;let e=[];for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="-s"||r==="--session"){t[n+1]!==void 0&&!t[n+1].startsWith("-")&&(n+=1);continue}r.startsWith("--session=")||r.startsWith("-s=")||e.push(r);}return e}function wo(t){let e=vg(t.additionalArgs);return {...t,...e===void 0?{}:{additionalArgs:e},resumeSessionId:void 0}}function Cg(t,e){try{return !!t.prepare("SELECT id FROM session_v2 WHERE id = ?").get(e)}catch(n){if(n instanceof Error&&/no such table: session_v2/i.test(n.message))return false;throw n}}function xg(t,e,n){let r=new t(e,{readonly:true,fileMustExist:true});try{return Cg(r,n)}finally{r.close();}}async function Qs(t,e={}){let n;try{n=await(e.loadSqlite??wg)();}catch{throw new G("OpenCode isolation requires the optional better-sqlite3 dependency. Install it and retry.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}let r=e.crewxHome??To(),o=gr(r),s=hr(r),i=Eg(s),c=Rg(e.userDataHome),d=Ig(n,c);if(d.length>0){if(!eu(n,i))try{await(e.initializeDatabase??Ag)(o);}catch{throw new G("Could not initialize the isolated OpenCode credential database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}if(!eu(n,i))throw new G("The isolated OpenCode credential database is unavailable.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"});try{Ng(n,i,d);}catch{throw new G("Could not copy API-key credentials into the isolated OpenCode database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}let u=Og(t.additionalArgs),l=u.map(_=>_.sessionId),p=u.length>0?l[l.length-1]:t.resumeSessionId;if(!p)return u.length>0?wo(t):t;if(l.some(_=>_!==p)||!existsSync(i))return wo(t);try{return xg(n,i,p)?{...t,resumeSessionId:p}:wo(t)}catch{throw new G("Could not read the isolated OpenCode session database safely.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}var Zs=x(()=>{g();Ht();Xs();Zc();});function cn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function ei(){let t;try{let n=(await import('better-sqlite3')).default,r=join(hr(),"opencode.db");t=new n(r,{readonly:!0,fileMustExist:!0});let o=t.prepare("SELECT value FROM kv WHERE key = ?").get("models-dev:v2:catalog");if(!o||typeof o.value!="string")throw new Error("OpenCode model catalog row is unavailable");let s=JSON.parse(o.value);if(!cn(s))throw new Error("OpenCode model catalog shape is unavailable");let i=typeof s.body=="string"?JSON.parse(s.body):s.body;if(!cn(i))throw new Error("OpenCode model catalog body shape is unavailable");let c=new Map;for(let[d,u]of Object.entries(i)){if(!d||!cn(u)||!cn(u.models))throw new Error("OpenCode model provider shape is unavailable");for(let[l,p]of Object.entries(u.models)){if(!l||!cn(p))throw new Error("OpenCode model shape is unavailable");let _=p.capabilities;if(_===void 0)continue;if(!cn(_))throw new Error("OpenCode model capability shape is unavailable");let h=_.reasoning;if(h===void 0)continue;if(!cn(h))throw new Error("OpenCode reasoning capability shape is unavailable");let m=h.effort;(m===void 0||Array.isArray(m)&&m.every(k=>typeof k=="string"))&&c.set(`${d}/${l}`,Array.isArray(m)?m:[]);}}return c}catch{return console.debug("[opencode] could not read private model effort catalog; omitting effort choices"),new Map}finally{try{t?.close();}catch{}}}var nu=x(()=>{g();ni();zc();Xc();Xs();Zs();Ut();});function Hg(t){return t?$g[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Je(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ug(){let t;try{t=hr();}catch{return ei().catch(()=>new Map)}let e=Date.now();if(ru===t&&Eo&&Eo.expiresAt>e)return Eo.result;ru=t;let n=ei().catch(()=>new Map);return Eo={expiresAt:e+Mg,result:n},n}async function qg(t){let e=await Qs(t),n=t.additionalArgs??[],r=Je(n,"--model")||Je(n,"-m");if(!t.model||!t.effort||r)return e;let o=(await Ug()).get(t.model);return !o||o.includes(t.effort)?e:(console.debug("[opencode] requested effort is not listed for this model; using OpenCode default"),{...e,effort:void 0})}function du(t){let e=[],n=0,r=false,o=false,s=0;for(let c=0;c<t.length;c++){let d=t[c];if(o){o=false;continue}if(d==="\\"&&r){o=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let u=t.slice(s,c+1).trim();u&&e.push(u),s=c+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function ae(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function cu(t){let e=ae(t.part)?t.part:void 0;return t.type==="reasoning"||e?.type==="reasoning"}function Fg(t){let e=ae(t.part)?t.part:void 0;return (typeof e?.text=="string"?e.text:typeof t.text=="string"?t.text:void 0)?.trim()||void 0}function Bg(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let i=JSON.parse(o);ae(i)?e.push(i):n=!0;continue}catch{}let s=du(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of s)try{let c=JSON.parse(i);ae(c)?e.push(c):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function si(t){let e=ae(t.error)?t.error:void 0,n=e&&ae(e.data)?e.data:void 0,r=uu(e),o=ze(e?.name),s=ze(n?.message)??ze(e?.message)??ri(r)??ze(t.message)??ze(t.errorMessage)??ze(t.error),i=ze(t.ref),c=o&&s&&o!==s?`${o}: ${s}`:o??s??au;return (i?`${c} (ref: ${i})`:c).slice(0,Pg)}function ou(t){let e=ae(t.error)?t.error:void 0,n=typeof e?.type=="string"?e.type:void 0,r=typeof e?.status=="number"?e.status:Number(e?.status),o=si(t),s=uu(e),i=s&&ae(s.error)?s.error:void 0,c=typeof i?.type=="string"?i.type:void 0,d=[o,ri(s)].filter(Boolean).join(`
84
84
  `);if(r===402||Wg(d))return new G(`OpenCode subscription is required: ${o}`,Ue,{code:"SUBSCRIPTION_REQUIRED",kind:"config",providerReason:_r(o)});if(r===403&&(c==="RegionError"||c==="FreeTierError"))return new G(`OpenCode account settings are required: ${o}`,Ue,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:"access",providerReason:_r(o)});if(n==="provider.auth"||r===401||r===403)return new G(`OpenCode authentication is required: ${o}`,Ue,{code:"AUTH_REQUIRED",kind:"config"});if(r===410||c==="ModelDeprecated")return new G(`OpenCode model has been retired: ${o}`,Ue,{code:"MODEL_RETIRED",kind:"config",replacementModel:Gg(s,e,t),providerReason:_r(o)});if(n==="provider.free-limit"||r===429){let u=jg(e);return new G(`OpenCode rate limit reached: ${o}`,Ue,{code:"RATE_LIMITED",kind:"transient",...u===void 0?{}:{retryAfterMs:u}})}if(n==="provider.no-route")return new G(`OpenCode model or variant unavailable: ${o}`,Ue,{code:"MODEL_UNAVAILABLE",kind:"config"});if(n==="provider.invalid-request"&&r===400){let u=[o,ri(s)].filter(h=>h!==void 0),l=u.find(h=>/requires global regions/i.test(h)),p=u.find(h=>/trains on request data/i.test(h)),_=l?"region":p?"training_consent":void 0;if(_)return new G(`OpenCode account settings are required: ${o}`,Ue,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:_,providerReason:_r(l??p)})}return new G(`OpenCode error: ${o}`,Ue,{code:"PROVIDER_CRASHED",kind:"transient"})}function uu(t){let n=(t&&ae(t.response)?t.response:void 0)?.body;if(ae(n))return n;if(typeof n=="string")try{let r=JSON.parse(n);return ae(r)?r:void 0}catch{return}}function ri(t){let e=t&&ae(t.error)?t.error:void 0;return ze(e?.message)??ze(t?.message)}function Wg(t){return /insufficient\s+(?:balance|account funds)|credit\s+limit\s+exceeded|payment\s+required|account invoice is overdue|billing_error|please add or update your payment method|(?:GLM Coding Plan|enterprise) package has expired|your current subscription plan does not yet include access to/i.test(t)}function Gg(t,e,n){let r=t&&ae(t.metadata)?t.metadata:void 0,o=typeof r?.replacement=="string"?r.replacement.trim():void 0;if(!o)return;let s=[r?.model,e?.model,n.model,n.modelID].find(d=>typeof d=="string"&&d.trim().length>0)?.trim(),i=s&&s.includes("/")?s.slice(0,s.indexOf("/")):"opencode-go",c=o.includes("/")?o:`${i}/${o}`;return /^[A-Za-z0-9._/-]{1,128}$/.test(c)?c:void 0}function jg(t){let e=t?.retryAfterMs;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;let r=(t&&ae(t.response)?t.response:void 0)?.body,o=typeof r=="string"?Kg(r):ae(r)?r:void 0;if(o){let s=oi(o);if(s)return su(s.value,s.key==="retryafterms")}if(typeof r=="string"){let s=r.match(/retry[-_]after(?:\s*[:=]\s*|\s+)["']?([^"'\s,;}]+)/i);if(s?.[1])return su(s[1],false)}}function Kg(t){try{let e=JSON.parse(t);return ae(e)?e:void 0}catch{return}}function oi(t){if(Array.isArray(t)){for(let e of t){let n=oi(e);if(n)return n}return}if(ae(t)){for(let[e,n]of Object.entries(t)){let r=e.toLowerCase().replace(/[-_]/g,"");if(r==="retryafterms"||r==="retryafter")return {value:n,key:r}}for(let e of Object.values(t)){let n=oi(e);if(n)return n}}}function su(t,e){if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return e?t:Math.round(t*1e3);if(typeof t!="string"||!t.trim())return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return e?n:Math.round(n*1e3);if(e)return;let r=Date.parse(t);return Number.isFinite(r)?Math.max(0,r-Date.now()):void 0}function iu(t){let e=Bg(t),n=[],r=null,o=0,s=[],i=[],c,d=false;for(let u of e.events){if(cu(u))continue;let l=typeof u.type=="string"?u.type:void 0;if(l){if(l==="text"){let p=ae(u.part)?u.part:void 0,_=typeof p?.text=="string"?p.text:void 0;_?.trim()&&n.push(_.trim());continue}if(l==="result"){typeof u.result=="string"&&(r=u.result);continue}if(l==="tool_use"){o++;continue}if(l==="error"){s.push(u),i.push(si(u));continue}if(l==="step_finish"){d=true;let p=ae(u.part)?u.part:void 0;c=typeof p?.reason=="string"?p.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorEvents:s,errorMessages:i,terminalReason:c,hasTerminal:d}}function lu(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function zg(){return new G("OpenCode returned no assistant output.",Ue,{code:"EMPTY_OUTPUT",kind:"transient"})}function Jg(){return new G("OpenCode emitted malformed JSON output.",Ue,{code:"PROVIDER_CRASHED",kind:"transient"})}function Vg(t,e){switch(lu(t)){case "length":return new G("OpenCode stopped because the context window was exceeded.",Ue,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new G("OpenCode stopped because the content filter blocked the response.",Ue,{code:"UNKNOWN",kind:"permanent"});case "error":return new G(`${au} while generating a response.`,Ue,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var Dg,Ue,au,Pg,Lg,Mg,ru,Eo,$g,ii,ai=x(()=>{g();Ht();Kc();pr();On();an();nu();Zs();Dg=new Set(["step_start","step_finish"]),Ue="cli/opencode",au="OpenCode provider error",Pg=240,Lg="Follow the instructions provided on standard input.",Mg=3e5,$g={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};ii={command:"opencode",prepare:qg,meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Je(o,"--format")||o.push("--format","json"),Je(o,"--thinking")||o.push("--thinking"),!Je(o,"--standalone")&&!Je(o,"--server")&&o.push("--standalone"),e.resumeSessionId&&!Je(o,"-s")&&!Je(o,"--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=Hg(e.mode);Je(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!Je(o,"--auto")&&o.push("--auto");let c=Je(o,"--model")||Je(o,"-m");if(e.model&&!c){let d=e.effort?`${e.model}#${e.effort}`:e.model;o.push("--model",d);}else e.effort&&!e.model&&!c&&console.debug("[opencode] ignoring effort because no model is configured");return o.push(Lg),{args:o,stdinMessage:t,env:gr()}},extractText(t){let e=iu(t),n=e.errorEvents[0];if(n)throw ou(n);let r=Vg(e.terminalReason??"");if(r)throw r;let o=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(o!==void 0)return o;if(e.resultText?.trim())return e.resultText;if(e.malformed)throw Jg();let s=lu(e.terminalReason);if(e.hasTerminal&&s==="tool-calls"&&e.toolUseCount>0)return "";throw zg()},interpretExit(t,e,n=""){if(t===0)return null;let o=iu(n).errorEvents[0];return o?ou(o):null},parseResultMeta(t){let e=Cn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e,n){let r=e??new Date().toISOString(),o=[],s=new Map,i;try{JSON.parse(t),i=[t];}catch{i=du(t),i.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let c of i){let d;try{d=JSON.parse(c);}catch{continue}let u=rt(d,r),l=d.type;if(cu(d)){let p=Fg(d);if(!p)continue;let _=ae(d.part)?d.part:void 0,h=typeof _?.id=="string"?_.id:typeof d.id=="string"?d.id:void 0,m=p;if(h){let k=`opencode.reasoning:${h}`,E=n?.state.get(k),D=typeof E=="string"?E:s.get(h);if(typeof D=="string"&&(D===p||D.startsWith(p))||typeof D=="string"&&p.startsWith(D)&&(m=p.slice(D.length).trim(),!m))continue;s.set(h,p),n?.state.set(k,p);}o.push({timestamp:u,type:"thinking",content:m});continue}if(l){if(l==="text"){let _=d.part?.text;_&&o.push({timestamp:u,type:"text",content:_});continue}if(l==="tool_use"){let p=d.part;if(!p)continue;let _=String(p.tool||""),h=String(p.callID||p.id||""),m=p.state,k=String(m?.status||""),E=m?.input,D=nt(E);if(o.push({timestamp:u,type:"tool_use",toolName:_,toolUseId:h,toolInput:D}),k==="completed"&&m?.output!==void 0){let T=m.output,L=typeof T=="string"?T:JSON.stringify(T);o.push({timestamp:u,type:"tool_result",toolUseId:h,resultPreview:L,isError:false});}else k==="error"&&o.push({timestamp:u,type:"tool_result",toolUseId:h,resultPreview:String(m?.error||"tool error"),isError:true});continue}if(l==="error"){let p=si(d);o.push({timestamp:u,type:"error",content:p,errorMessage:p});continue}}}return o},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Dg.has(r):!1}catch{return false}}};});var pu=x(()=>{g();});function Ro(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function eh(t,e){let n=[];for(let r=0;r<t.length;r+=1){let o=t[r],s=[...e].find(i=>o===i||o.startsWith(`${i}=`));s?o===s&&r+1<t.length&&(r+=1):n.push(o);}return n}function th(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],o=r.indexOf("="),s=o>0?r.slice(0,o):r;if(!Qg.has(s)){e.push(r);continue}r===s&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function Ve(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function nh(t,e){if(!(t?Yg.has(t)||At(di).some(s=>s.id===t):false)||!t)return e;let r=vn(di,t),o=Ws(di)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}function Nt(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function li(t){return t.kind==="step_update"?typeof t.step.conversation_id=="string"?t.step.conversation_id:void 0:typeof t.envelope.conversation_id=="string"?t.envelope.conversation_id:void 0}function pi(t){return t.step.step_index}function ie(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&po(e)?.slice(0,500).trim()||void 0}function rh(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&Zg.has(n))return n;let r=`${n} ${e??""}`.toLowerCase();return /quota|resource_exhausted|usage[ _-]?limit|credits?.{0,20}exhaust/.test(r)?"QUOTA_EXHAUSTED":/rate[ _-]?limit|throttl/.test(r)?"RATE_LIMITED":/auth|sign[ _-]?in|log(?:ged)?[ _-]?in|unauthori[sz]ed|credential/.test(r)?"AUTH_REQUIRED":[/unknown (?:flag|option)/,/flag provided but not defined/,/unrecognized (?:flag|option)/,/invalid value for (?:flag|option)/,/invalid (?:flag|option)/].some(s=>s.test(r))?"INVALID_PROVIDER_FORMAT":/invalid.{0,24}model|model.{0,24}(unknown|unavailable|not found|not recognized)|config/.test(r)?"MODEL_UNAVAILABLE":"UNKNOWN"}function oh(t){return t==="AUTH_REQUIRED"||t==="TIMEOUT_IDLE"||t==="TIMEOUT_TOTAL"||t==="TIMEOUT_RESUME"||t==="PROVIDER_CRASHED"?"permanent":t==="MODEL_UNAVAILABLE"||t==="INVALID_PROVIDER_FORMAT"||t==="PROVIDER_NOT_FOUND"?"config":"transient"}function gu(t){let e=Ve(t)?t:void 0,n=e&&Ve(e.error)?e.error:void 0,r=e?ie(e.code)??ie(e.error_code)??ie(n?.code)??ie(n?.error_code):void 0,o=typeof t=="string"?ie(t):e?ie(e.message)??ie(e.error)??ie(e.reason)??ie(n?.message)??ie(n?.error)??ie(n?.reason):void 0,s=rh(r,o),i=e?Nt(e.retry_after_ms)??Nt(e.retryAfterMs)??Nt(n?.retry_after_ms)??Nt(n?.retryAfterMs):void 0;return {code:s,kind:oh(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function Io(t){let e=gu(t);return new G(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function _i(t){return new G(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function sh(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=ui))throw new G(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${ui} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function ci(){return new G("Antigravity CLI returned empty output with exit code 0. agy may have hidden an auth/quota/model error in its log file; inspect ~/.gemini/antigravity-cli/log for details.","cli/antigravity",{code:"EMPTY_OUTPUT",kind:"transient"})}function Ao(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function No(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n&&(n.kind==="result"||n.kind==="legacy_result"||n.kind==="agy_error"))return {event:n,index:e}}}function ih(t){let e=No(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||Ao(e.event)?.status!=="SUCCESS"||So(t))return false;let r=new Map;for(let o of t){if(o.kind!=="step_update"||o.step.step_type!=="agent_response")continue;let s=li(o),i=pi(o);!s||!Number.isSafeInteger(i)||r.set(JSON.stringify([s,i]),o.step);}if(r.size===0)return false;for(let o of r.values())if(o.state!=="DONE"||!Ve(o.usage)||Nt(o.usage.input_tokens)===void 0||Nt(o.usage.output_tokens)===void 0)return false;return true}function ah(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function dh(t,e){return Ve(t)&&Ve(e)?{...e,...t}:Ve(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&Ve(e)?{...e,message:t}:t??e}function ch(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let s of e){let i=Ve(s)?s:void 0,c=typeof s=="string"?ie(s):ie(i?.display_name)??ie(i?.action);c&&!n.includes(c)&&n.length<5&&n.push(c.slice(0,80));}let r=Math.max(0,e.length-n.length),o=n.length>0?` (${n.join(", ")}${r>0?`, +${r} more`:""})`:"";return new G(`Permission denied: Antigravity blocked ${e.length} requested action${e.length===1?"":"s"}${o}.`,"cli/antigravity",{code:"UNKNOWN",kind:"permanent"})}function So(t){let e=No(t);if(!e)return;if(e.event.kind==="agy_error")return Io(e.event.error);let n=Ao(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return ch(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return _i("Antigravity returned a result with an unsupported status.");let r=n.error,o=dh(r==null||r===""?n:r,ah(t,e.index));return Io(o)}function hu(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function uh(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function lh(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function mu(t){let e=hu(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function ph(t){let e=Ve(t)?t:void 0,n=e&&Ve(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,o=(ie(e?.type)??ie(e?.code)??ie(e?.error_type)??ie(n?.type)??ie(n?.code)??ie(n?.error_type)??ie(r)??"TOOL_ERROR").slice(0,60),s=gu(t).message.slice(0,250);return mu({type:o,message:s})??"Antigravity reported a tool error."}function _u(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function fu(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var di,Yg,Qg,ui,Zg,fi,gi=x(()=>{g();Ht();pu();Ds();cr();Ut();lr();Hs();di="antigravity",Yg=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),Qg=new Set(["--conversation","--resume","--continue"]),ui=18e4,Zg=new Set(["QUOTA_EXHAUSTED","RATE_LIMITED","EMPTY_OUTPUT","AUTH_REQUIRED","MODEL_UNAVAILABLE","TIMEOUT_IDLE","TIMEOUT_TOTAL","TIMEOUT_RESUME","PROVIDER_NOT_FOUND","INVALID_PROVIDER_FORMAT","PROVIDER_CRASHED","UNKNOWN"]);fi={command:"agy",maxInitialInputBytes:ui,meta:{displayName:"Antigravity",models:kc(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=ar(t);if(e?.kind!=="init")return null;let n=e.envelope.conversation_id;return typeof n=="string"&&n.trim().length>0?n.trim():null},buildArgs(t,e,n){sh(t);let{model:r,effort:o}=qt(e.model),s=Fs(r),i=s.model,c=e.effort??o??s.effort,d=nh(i,c),u=e.additionalArgs??[],l=th(eh(u,new Set(["--input-format","--output-format"]))),p=i&&!Ro(u,"--model")?["--model",i]:[],_=Ro(u,"--effort")?[]:xc(d),h=Ro(u,"--mode")||Ro(u,"--dangerously-skip-permissions")?[]:Cc(e.mode),m=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...p,..._,...h,...m,...l],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
85
- `,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=dr(t),n=No(e)?.event,r=So(e);if(r)throw r;let o=n?Ao(n):void 0;if(o){if(o.status!=="SUCCESS")throw _i("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw _i("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw ci();return o.response}if(e.length>0)throw ci();let s=t.trim();if(!s)throw ci();return s},extractPartialText(t){let e=dr(t),n=No(e)?.event;if(!n||n.kind==="agy_error")return;let r=Ao(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=dr(n??""),o=So(r);return o||(t!==0&&e.trim()?Io(e):null)},parseResultMeta(t){let e=dr(t),n=0,r=0,o=0,s=0,i=new Set;for(let d of e){if(d.kind!=="step_update"||d.step.state!=="DONE"||!Ve(d.step.usage))continue;let u=li(d),l=pi(d);if(!u||!Number.isSafeInteger(l))continue;let p=JSON.stringify([u,l]);if(i.has(p))continue;let _=d.step.usage,h=Nt(_.input_tokens),m=Nt(_.output_tokens);h===void 0||m===void 0||(i.add(p),n+=h,r+=m,o+=Nt(_.cache_read_tokens)??0,s+=1);}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete:ih(e)},model:null}},parseEvent(t,e,n){let r=ar(t);if(!r)return [];let o=e??new Date().toISOString();if(r.kind==="agy_error")return [fu(o,Io(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let h=So([r]);return h?[fu(o,h)]:[]}if(r.kind!=="step_update")return [];let{step:s}=r,i=li(r)??"unknown",c=pi(r),d=`${i}:${c}`;if((s.state==="DONE"||s.state==="ERROR")&&_u(n,`antigravity:terminal:${d}`))return [];if(s.step_type==="agent_response")return typeof s.text_delta=="string"&&s.text_delta.length>0?[{timestamp:o,type:"text",content:s.text_delta}]:[];if(s.step_type!=="tool")return [];let u=Ve(s.tool_info)?s.tool_info:void 0,l=lh(s,u);if(!l)return [];let p=uh(s);if(s.state==="ACTIVE"){if(_u(n,`antigravity:active:${d}`))return [];let h=hu(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:l,toolUseId:p,...h===void 0?{}:{toolInput:h}}]}let _=s.state==="ERROR"?ph(u?.error):mu(u?.output);return [{timestamp:o,type:"tool_result",toolName:l,toolUseId:p,..._===void 0?{}:{resultPreview:_},...s.state==="ERROR"?{isError:true}:{}}]}};});var ku=x(()=>{g();An();On();Nn();an();});function bn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Dn(t){return bn(t)?t:void 0}function De(t){return typeof t=="string"?t:void 0}function ln(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function wh(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let c=t[i];if(n===-1){(c==="{"||c==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(c==="\\"&&o){s=true;continue}if(c==='"'){o=!o;continue}o||(c==="{"||c==="["?r+=1:(c==="}"||c==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function mr(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return bn(n)?[n]:[]}catch{return wh(e).flatMap(n=>{try{let r=JSON.parse(n);return bn(r)?[r]:[]}catch{return []}})}}function Iu(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function un(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(un).filter(n=>n!==void 0);return e.length>0?e.join(`
85
+ `,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=dr(t),n=No(e)?.event,r=So(e);if(r)throw r;let o=n?Ao(n):void 0;if(o){if(o.status!=="SUCCESS")throw _i("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw _i("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw ci();return o.response}if(e.length>0)throw ci();let s=t.trim();if(!s)throw ci();return s},extractPartialText(t){let e=dr(t),n=No(e)?.event;if(!n||n.kind==="agy_error")return;let r=Ao(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=dr(n??""),o=So(r);return o||(t!==0&&e.trim()?Io(e):null)},parseResultMeta(t){let e=dr(t),n=0,r=0,o=0,s=0,i=new Set;for(let d of e){if(d.kind!=="step_update"||d.step.state!=="DONE"||!Ve(d.step.usage))continue;let u=li(d),l=pi(d);if(!u||!Number.isSafeInteger(l))continue;let p=JSON.stringify([u,l]);if(i.has(p))continue;let _=d.step.usage,h=Nt(_.input_tokens),m=Nt(_.output_tokens);if(h===void 0||m===void 0)continue;i.add(p);let k=Nt(_.cache_read_tokens)??0;n+=h+k,r+=m,o+=k,s+=1;}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete:ih(e)},model:null}},parseEvent(t,e,n){let r=ar(t);if(!r)return [];let o=e??new Date().toISOString();if(r.kind==="agy_error")return [fu(o,Io(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let h=So([r]);return h?[fu(o,h)]:[]}if(r.kind!=="step_update")return [];let{step:s}=r,i=li(r)??"unknown",c=pi(r),d=`${i}:${c}`;if((s.state==="DONE"||s.state==="ERROR")&&_u(n,`antigravity:terminal:${d}`))return [];if(s.step_type==="agent_response")return typeof s.text_delta=="string"&&s.text_delta.length>0?[{timestamp:o,type:"text",content:s.text_delta}]:[];if(s.step_type!=="tool")return [];let u=Ve(s.tool_info)?s.tool_info:void 0,l=lh(s,u);if(!l)return [];let p=uh(s);if(s.state==="ACTIVE"){if(_u(n,`antigravity:active:${d}`))return [];let h=hu(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:l,toolUseId:p,...h===void 0?{}:{toolInput:h}}]}let _=s.state==="ERROR"?ph(u?.error):mu(u?.output);return [{timestamp:o,type:"tool_result",toolName:l,toolUseId:p,..._===void 0?{}:{resultPreview:_},...s.state==="ERROR"?{isError:true}:{}}]}};});var ku=x(()=>{g();An();On();Nn();an();});function bn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Dn(t){return bn(t)?t:void 0}function De(t){return typeof t=="string"?t:void 0}function ln(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function wh(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let c=t[i];if(n===-1){(c==="{"||c==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(c==="\\"&&o){s=true;continue}if(c==='"'){o=!o;continue}o||(c==="{"||c==="["?r+=1:(c==="}"||c==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function mr(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return bn(n)?[n]:[]}catch{return wh(e).flatMap(n=>{try{let r=JSON.parse(n);return bn(r)?[r]:[]}catch{return []}})}}function Iu(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function un(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(un).filter(n=>n!==void 0);return e.length>0?e.join(`
86
86
  `):void 0}if(bn(t)){if(typeof t.text=="string")return t.text;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error;if(t.type==="text"&&typeof t.data=="string")return t.data;for(let e of ["content","FileContent","rawOutput"]){let n=un(t[e]);if(n!==void 0)return n}}}function Eh(t){let e=i=>Array.isArray(i)&&i.every(c=>Number.isInteger(c)&&c>=0&&c<=255),n=i=>typeof i=="string"&&i.trim().length>0?i:void 0,r=i=>new TextDecoder("utf-8",{fatal:false}).decode(Uint8Array.from(i)),o=i=>{let c=JSON.stringify(i,(d,u)=>e(u)?`<bytes:${u.length}>`:u);return c===void 0?String(i):c},s=t.rawOutput;if(s!=null){let i=Dn(s);if(!i)return n(un(s))??o(s);let c;if(e(i.output)&&i.output.length>0&&(c=n(r(i.output))),!c&&e(i.stdout)&&i.stdout.length>0&&(c=n(r(i.stdout))),!c){let l=Dn(i.Result);c=n(i.output)??n(l?.output)??n(un(s));}let d=e(i.stderr)&&i.stderr.length>0?r(i.stderr):void 0;if(d!==void 0)if(c){let l=c.endsWith(`
87
87
  `)||c.endsWith("\r")?"":`
88
88
  `;c=`${c}${l}${d}`;}else c=n(d);if(c)return c;let u=n(i.summary)??n(un(t.content))??n(i.output_for_prompt);return u!==void 0?u:o(s)}if(t.content!==null&&t.content!==void 0)return un(t.content)??o(t.content);if(t.result!==null&&t.result!==void 0)return un(t.result)??o(t.result)}function Au(t){let e=Dn(t.error),n=[t.message,t.errorMessage,e?.message,e?.detail,typeof t.error=="string"?t.error:void 0].find(r=>typeof r=="string"&&r.trim().length>0);return n?Nu(n):"Grok CLI reported an error."}function Nu(t){return (t.replace(Th,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Ru(t){return yh.test(t)}function Rh(t){let e=Dn(t.modelUsage);return e?Object.keys(e)[0]??null:null}function Sh(t){let e=Dn(t.usage);if(!e)return null;let n=ln(e.cache_read_input_tokens);return {inputTokens:ln(e.input_tokens)+n,cachedInputTokens:n,outputTokens:ln(e.output_tokens),costUsd:ln(t.total_cost_usd)}}function Ih(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
@@ -42,7 +42,7 @@ ${r.join(`
42
42
  AND ((${t.cleanup_pending} = 1 AND ${t.vault_handle} IS NOT NULL)
43
43
  OR (${t.cleanup_pending} = 0 AND ${t.vault_handle} IS NULL)))
44
44
  ))
45
- )`),conflictSupersededCheck:check("app_sync_conflicts_superseded_ck",sql`${t.state} != 'superseded' OR ${t.superseded_by} IS NOT NULL`),conflictResolutionCheck:check("app_sync_conflicts_resolution_ck",sql`(${t.resolution_request_id} IS NULL AND ${t.resolution_choice} IS NULL) OR (length(${t.resolution_request_id}) BETWEEN 1 AND 128 AND ${t.resolution_choice} IN ('keep_local', 'use_cloud', 'keep_both'))`),conflictTimeCheck:check("app_sync_conflicts_time_ck",sql`${t.updated_at} >= ${t.created_at}`),conflictBindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[pr.binding_id]}).onDelete("cascade"),conflictIdentityUnique:uniqueIndex("app_sync_conflicts_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.local_version,t.remote_revision,t.remote_fingerprint),conflictLookup:index("app_sync_conflicts_lookup_idx").on(t.account_key,t.binding_id,t.state,t.updated_at)})),sqliteTable("app_sync_conflict_resolutions",{request_id:text("request_id").primaryKey().notNull(),conflict_id:text("conflict_id").notNull(),account_key:text("account_key").notNull(),human_identity:text("human_identity").notNull(),choice:text("choice").notNull(),expected_local_version:text("expected_local_version").notNull(),expected_remote_revision:integer("expected_remote_revision").notNull(),expected_remote_fingerprint:text("expected_remote_fingerprint").notNull(),state:text("state").notNull().default("pending"),error_code:text("error_code"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({resolutionRequestIdCheck:check("app_sync_conflict_resolutions_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),resolutionAccountCheck:check("app_sync_conflict_resolutions_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resolutionIdentityCheck:check("app_sync_conflict_resolutions_human_identity_ck",sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),resolutionChoiceCheck:check("app_sync_conflict_resolutions_choice_ck",sql`${t.choice} IN ('keep_local', 'use_cloud', 'keep_both')`),resolutionLocalVersionCheck:check("app_sync_conflict_resolutions_local_version_ck",sql`length(${t.expected_local_version}) BETWEEN 1 AND 256 AND instr(${t.expected_local_version}, '/') = 0 AND instr(${t.expected_local_version}, char(92)) = 0`),resolutionRemoteCheck:check("app_sync_conflict_resolutions_remote_ck",sql`${t.expected_remote_revision} >= 0 AND length(${t.expected_remote_fingerprint}) = 71 AND substr(${t.expected_remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.expected_remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),resolutionStateCheck:check("app_sync_conflict_resolutions_state_ck",sql`${t.state} IN ('pending', 'unknown', 'resolved', 'stale', 'failed')`),resolutionTimeCheck:check("app_sync_conflict_resolutions_time_ck",sql`${t.updated_at} >= ${t.created_at}`),resolutionConflictFk:foreignKey({columns:[t.conflict_id],foreignColumns:[Am.conflict_id]}).onDelete("cascade"),resolutionConflictIdx:index("app_sync_conflict_resolutions_conflict_idx").on(t.conflict_id,t.created_at),resolutionActiveUnique:uniqueIndex("app_sync_conflict_resolutions_one_active_uq").on(t.conflict_id).where(sql`${t.state} IN ('pending', 'unknown')`)})),sqliteTable("app_sync_account_data_purges",{request_id:text("request_id").primaryKey().notNull(),binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),root_fingerprint:text("root_fingerprint").notNull(),human_identity:text("human_identity").notNull(),state:text("state").notNull().default("pending"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({purgeRequestIdCheck:check("app_sync_account_data_purges_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),purgeAccountCheck:check("app_sync_account_data_purges_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),purgeWorkspaceCheck:check("app_sync_account_data_purges_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),purgeRootCheck:check("app_sync_account_data_purges_root_fingerprint_ck",sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),purgeHumanIdentityCheck:check("app_sync_account_data_purges_human_identity_ck",sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),purgeStateCheck:check("app_sync_account_data_purges_state_ck",sql`${t.state} IN ('pending', 'complete')`),purgeTimeCheck:check("app_sync_account_data_purges_time_ck",sql`${t.updated_at} >= ${t.created_at}`),purgeAccountIndex:index("app_sync_account_data_purges_account_idx").on(t.account_key,t.state,t.updated_at)}));});var Xu=x(()=>{h();sqliteTable("route_states",{workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),config_revision:text("config_revision").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),updated_at:text("updated_at").notNull()},t=>({pk_route_state_workspace:primaryKey({columns:[t.workspace_key,t.route_id]})})),sqliteTable("route_sticky_bindings",{workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),thread_id:text("thread_id").notNull(),candidate_id:text("candidate_id").notNull(),updated_at:text("updated_at").notNull()},t=>({uniq_route_sticky_thread:uniqueIndex("uniq_route_sticky_thread").on(t.workspace_key,t.route_id,t.thread_id),idx_route_sticky_candidate:index("idx_route_sticky_candidate").on(t.workspace_key,t.route_id,t.candidate_id)})),sqliteTable("route_decisions",{id:text("id").primaryKey(),workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),task_id:text("task_id").notNull(),config_revision:text("config_revision").notNull(),candidate_id:text("candidate_id").notNull(),provider:text("provider").notNull(),model:text("model").notNull(),reason:text("reason").notNull(),eligible_ids:text("eligible_ids").notNull(),blocked_causes:text("blocked_causes").notNull(),link_errors:text("link_errors").notNull(),created_at:text("created_at").notNull()},t=>({uniq_route_task_decision:uniqueIndex("uniq_route_task_decision").on(t.workspace_key,t.route_id,t.task_id),idx_route_decisions_workspace_created:index("idx_route_decisions_workspace_created").on(t.workspace_key,t.route_id,t.created_at)})),sqliteTable("route_quota_observations",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),model:text("model"),status:text("status",{enum:["ok","blocked"]}).notNull(),source:text("source").notNull(),reset_at:text("reset_at"),observed_at:text("observed_at").notNull()},t=>({uniq_route_quota_observation:uniqueIndex("uniq_route_quota_observation").on(t.provider,t.account_ref,t.model,t.source),idx_route_quota_observations_reset:index("idx_route_quota_observations_reset").on(t.reset_at)}));});var we=x(()=>{h();rs();cr();Zc();tu();no();su();au();du();uu();_u();fu();mu();ku();Tu();Eu();Ru();bu();Au();Nu();vu();Zi();Mu();Hu();Uu();ju();Wu();Gu();zu();Ku();Vu();Ju();Xu();});var Xm,po,fa=x(()=>{h();_e();ye();Ee();ke();we();Xm=50,po=class extends F{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=`${e.dbRoot}/.crewx/crewx.db`);}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(){let e=this.resolveDbPath(),n=L(e);try{return ee(n.db,e),n}catch(r){throw n.close(),r}}recordAccepted(e){if(e.actorKind!=="human"||!e.workspaceId||!e.actorId||!e.agentId)return false;let n;try{n=this.openHandle();let r=e.acceptedAt??new Date().toISOString();return n.db.insert(nt).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[nt.workspace_id,nt.actor_id,nt.agent_id],set:{last_accepted_at:sql`MAX(${nt.last_accepted_at}, excluded.last_accepted_at)`}}).run(),!0}catch(r){return console.error("[AgentSendHistoryRepository] Failed to record accepted agent send",r),false}finally{n?.close();}}findRecentAgents(e,n){let r;try{return r=this.openHandle(),r.db.select({agentId:nt.agent_id,lastAcceptedAt:nt.last_accepted_at}).from(nt).where(and(eq(nt.workspace_id,e),eq(nt.actor_id,n))).orderBy(desc(nt.last_accepted_at),asc(nt.agent_id)).limit(Xm).all()}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to find recent agent sends",o)}finally{r?.close();}}};});function kr(t){return typeof t=="string"&&Lt.includes(t)}function _o(t){if(!t||!t.includes("workflow"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.workflowRunId;if(typeof r=="string"&&r!=="")return r;let o=n.workflow;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let s=o.exec_id;if(typeof s=="string"&&s!=="")return s}return null}var Lt,yr=x(()=>{h();Lt=["workflow_card","workflow_ui_instance","workflow_run"];});var Tr,ka,Tl,ya=x(()=>{h();Tr={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5-5":{input:4,cachedInput:.2,output:20},"claude-opus-5-5-medium":{input:4,cachedInput:.2,output:20},"claude-opus-5":{input:5,cachedInput:.5,output:25},"claude-opus-4-8":{input:5,cachedInput:.5,output:25},"claude-opus-4-7":{input:5,cachedInput:.5,output:25},"claude-opus-4-6":{input:5,cachedInput:.5,output:25},"claude-sonnet-5-5":{input:2,cachedInput:.1,output:10},"claude-sonnet-5-5-medium":{input:2,cachedInput:.1,output:10},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-5-5":{input:.1,cachedInput:.01,output:.5},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-6.1-sol":{input:2,cachedInput:.1,output:10},"gpt-6.1-terra":{input:1,cachedInput:.05,output:5},"gpt-6-sol":{input:2,cachedInput:.2,output:10},"gpt-6-luna":{input:.1,cachedInput:.01,output:.5},"gpt-5.6-sol":{input:4,cachedInput:.4,output:20},"gpt-5.6-terra":{input:2,cachedInput:.2,output:12},"gpt-5.6-luna":{input:.2,cachedInput:.02,output:1.2},"gpt-5.5":{input:5,cachedInput:.5,output:30},"gpt-5.4":{input:2.5,cachedInput:.25,output:15},"gpt-5.4-mini":{input:.75,cachedInput:.075,output:4.5},"gpt-5.3-codex":{input:1.75,cachedInput:.175,output:14},"gpt-5-mini":{input:.4,cachedInput:.1,output:1.6},"gpt-4.1":{input:2,cachedInput:.5,output:8},"gpt-4o":{input:2.5,cachedInput:1.25,output:10},"glm-5.3-flash":{input:.15,cachedInput:.03,output:.5},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"deepseek-v4.1-flash":{input:.3,cachedInput:.006,output:1.2},"qwen3.8-flash":{input:.164,cachedInput:.018,output:.514},"minimax-m3":{input:.3,cachedInput:.06,output:1.2},"kimi-k2.7-code":{input:.95,cachedInput:.19,output:4},"gemini-3.7-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-3.6-flash":{input:1.5,cachedInput:.15,output:7.5},"grok-4.7":{input:2,cachedInput:.5,output:6},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},ka=new Set(["gpt-5.3-codex-spark","claude-opus-4-6-thinking","gpt-oss-120b","glm-5.3-flash-free","deepseek-v4.1-flash-free"]),Tl=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-haiku-5-5","claude-opus-4-6","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7","claude-opus-4-7[1m]","claude-opus-4-8","claude-opus-4-8[1m]","claude-opus-5","claude-opus-5-5","claude-opus-5-5-medium","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","claude-sonnet-5-5-medium","deepseek-v4.1-flash","deepseek-v4.1-flash-free","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","gemini-3.8-flash","gemini-4-argon","glm-5.1","glm-5.2","glm-5.3-flash","glm-5.3-flash-free","gpt-4.1","gpt-4o","gpt-5-mini","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini","gpt-5.5","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra","gpt-6-luna","gpt-6-sol","gpt-6.1-sol","gpt-6.1-terra","gpt-oss-120b","grok-4.5","grok-4.6","grok-4.7","kimi-k2.7-code","minimax-m3","qwen3.8-flash"]);});function Ta(t){let e=t.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let n=e.lastIndexOf("/");return n>=0&&(e=e.slice(n+1)),e=e.replace(/-\d{8}$/,""),e}function Ek(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),fo;let e=Ta(t),n=wk[e];if(n)return Es[n]??Tr[n]??fo;if(Es[e])return Es[e];if(Tr[e])return Tr[e];if(ka.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),fo;if(Tl.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),fo;let r={...Tr,...Es};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),fo}function Rk(t,e,n,r=0,o){let s=Ek(n),i=Math.min(r,t),c=(t-i)*s.input/1e6,u=i*s.cachedInput/1e6,p=e*s.output/1e6;return c+u+p}function wl(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:Rk(e??0,n??0,o,r??0)}var wk,fo,Es,Rs=x(()=>{h();ya();ya();wk={opus:"claude-opus-4-8",sonnet:"claude-sonnet-4-6",haiku:"claude-haiku-4-5","codex-mini":"gpt-5.3-codex",codex:"gpt-5.3-codex"},fo={input:0,cachedInput:0,output:0},Es={};});function bs(t){if(!t||!t.includes("schedule_id"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.trigger;if(typeof r!="string"||!Sk.includes(r))return null;let o=n.schedule_id;return typeof o=="string"&&o!==""?o:null}var Ss,El,Rl,Sl,wa,Sk,Ea=x(()=>{h();Ss="tasks_run_columns",El="idx_tasks_workflow_run_id",Rl="idx_tasks_ws_schedule_started",Sl="idx_tasks_ws_human_started",wa=[{name:El,sql:`CREATE INDEX IF NOT EXISTS ${El} ON tasks (workflow_run_id) WHERE workflow_run_id IS NOT NULL`},{name:Rl,sql:`CREATE INDEX IF NOT EXISTS ${Rl} ON tasks (workspace_id, started_at) WHERE schedule_id IS NOT NULL`},{name:Sl,sql:`CREATE INDEX IF NOT EXISTS ${Sl} ON tasks (workspace_id, started_at) WHERE actor_kind = 'human'`}],Sk=["cron","cron_manual"];});function Sa(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function bl(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function As(t){return Number.isSafeInteger(t)&&t>0}function vk(t){let e=t.trim();if(!e)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(e);return n?.[1]??n?.[2]??e.split(/\s+/,1)[0]??""}function Ck(t,e,n){let r=n==="win32"?t.toLowerCase():t,o=n==="win32"?e.toLowerCase():e;if(!o.trim())return false;if(o==="agy"){let s=vk(t).split(/[\\/]/).pop()??"",i=n==="win32"?s.toLowerCase():s;return i==="agy"||n==="win32"&&(i==="agy.exe"||i==="agy.cmd")}return r.includes(o)}function Dk(t,e,n){return e.some(r=>Ck(t,r,n))}function xk(t,e){try{let n=spawnSync(t,e,{encoding:"utf8",timeout:Ra,windowsHide:!0});return {status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",error:n.error}}catch(n){return {status:null,stdout:"",stderr:"",error:Sa(n)}}}function Lk(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(u){n({status:null,stdout:"",stderr:"",error:Sa(u)});return}let o="",s="",i=false,a,c=setTimeout(()=>{try{r.kill();}catch{}a({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${Ra}ms`)});},Ra);a=u=>{i||(i=true,clearTimeout(c),n(u));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",u=>{o+=String(u);}),r.stderr?.on("data",u=>{s+=String(u);}),r.once("error",u=>{a({status:null,stdout:o,stderr:s,error:u});}),r.once("close",u=>{a({status:u,stdout:o,stderr:s});});})}async function ba(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Lk(t,e)}function Pk(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Mk(){return new Promise(t=>{setImmediate(t);})}function En(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return bl(n)==="ESRCH"?"not_found":bl(n)==="EPERM"?"alive":"unknown"}}function $k(t,e){let n=En(-t,e),r=En(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function Il(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??Nk),i=Date.now()+o,a,c=o===0,u=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(p=>{a=setTimeout(p,o);});u.then(()=>{c=true;});try{for(await Mk();;){let p=$k(t,e);if(p==="not_found")return p;let l=i-Date.now();if(c||l<=0)return p;await Promise.race([u,Pk(Math.min(s,l))]);}}finally{a!==void 0&&clearTimeout(a);}}async function Al(t,e,n,r,o){let s=await Il(t,e,o.hardConfirmMs??Ok,{...o,sleep:void 0});return s==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:s==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function Nl(t,e,n={}){if(!As(t))return "unknown";let r=n.platform??process.platform,o=r==="win32"?"powershell.exe":"ps",s=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],i;try{i=await ba(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let a=i.stdout.trim();return a?Dk(a,e,r)?"owned":"not_owned":"not_found"}function Bk(t){let e=Hk.exec(t.trim());if(!e)return;let[,n="0",r="0",o="0",s="0"]=e;return ((Number(n)*24+Number(r))*60+Number(o))*60+Number(s)}function Fk(t){let e=t.trim(),n=qk.exec(e);if(n){let[,o,s,i,a,c,u,p,l]=n;return Date.UTC(Number(o),Number(s)-1,Number(i),Number(a),Number(c),Number(u),Math.trunc(Number(p)/1e3))-Number(l)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function Ol(t,e){return e==="win32"?{command:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write($p.CreationDate.ToUniversalTime().ToString('o')) }`]}:{command:"ps",args:["-p",String(t),"-o","pgid=","-o","etime=","-o","stat="]}}function vl(t,e,n){if(t.error)return {status:"unknown"};let r=t.stdout.trim();if(!r)return t.status===0||t.status===1?{status:"not_found"}:{status:"unknown"};if(t.status!==0)return {status:"unknown"};if(e==="win32"){let i=Fk(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let o=Uk.exec(r),s=o?Bk(o[2]):void 0;return !o||s===void 0?{status:"unknown"}:o[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-s*1e3,groupId:Number(o[1])}}function Cl(t,e={}){if(!As(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=Ol(t,n),s=e.runCommand??xk,i;try{i=s(r,o);}catch{return {status:"unknown"}}return vl(i,n,Date.now())}async function Dl(t,e={}){if(!As(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=Ol(t,n),s;try{s=await ba(r,o,e);}catch{return {status:"unknown"}}return vl(s,n,Date.now())}async function ho(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=f=>({status:"failed",pid:t,method:r,error:f});if(!As(t))return o("Invalid process ID");let s=e.kill??process.kill,i=En(t,s);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let f;try{f=await ba("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){f={status:null,stdout:"",stderr:"",error:Sa(m)};}let g=En(t,s);return g==="not_found"?f.status===0&&!f.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(g==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let a,c=e.signal??"SIGKILL";try{s(-t,c);}catch(f){a=f;}if(c==="SIGKILL")return Al(t,s,a,r,e);if(await Il(t,s,e.graceMs??Ik,e)==="not_found")return a?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let p;try{s(-t,"SIGKILL");}catch(f){p=f;}let l=await Al(t,s,p,r,e);return l.status==="terminated"?l:l.status==="not_found"?a?l:{status:"terminated",pid:t,method:r}:o(l.error??"Process termination failed")}var Ra,go,Ik,Nk,Ok,Is,Hk,Uk,qk,Aa=x(()=>{h();Ra=3e3,go="SIGINT",Ik=2e3,Nk=25,Ok=100;Is=3e3,Hk=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,Uk=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,qk=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function $l(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new _("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new _("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Pl(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new _("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new _("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>$l(r,o))}catch(r){throw r instanceof _?new _("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Hl(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new _("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new _("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new _("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Ml(t){return {taskId:t.id,source:Hl(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Vk(t){if(!Number.isInteger(t)||t<0)throw new _("VALIDATION","Task log tail limit must be a non-negative integer")}var Bn,Ns=x(()=>{h();_e();ye();Ee();ke();we();Bn=class extends F{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?it(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new _("NOT_FOUND","Database not found");let r=L(n);if(e)try{ee(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:d.id,log_storage:d.log_storage,last_log_seq:d.last_log_seq,log_revision:d.log_revision,logs:d.logs}).from(d).where(eq(d.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:d.id,log_storage:d.log_storage,last_log_seq:d.last_log_seq,log_revision:d.log_revision,logs:d.logs}).from(d).where(eq(d.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new _("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,i)=>$l(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new _("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let a=this.requireStateRowInTransaction(i,e),c=Hl(a);if(c==="blob"){let f=Pl(e,a.logs);if(i.update(d).set({logs:JSON.stringify([...f,...r]),log_revision:sql`${d.log_revision} + 1`}).where(eq(d.id,e)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:a.log_revision+1,lastSeq:a.last_log_seq}}let u=a.last_log_seq+1,p=a.last_log_seq+r.length;if(i.insert(Kt).values(r.map((f,g)=>({task_id:e,seq:u+g,timestamp:f.timestamp,level:f.level,message:f.message}))).run(),i.update(d).set({last_log_seq:p,log_revision:sql`${d.log_revision} + 1`}).where(eq(d.id,e)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:a.log_revision+1,lastSeq:p}},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?Ml(r):void 0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return Vk(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=Ml(s);if(i.source==="blob"){let p=Pl(e,s.logs).map((l,f)=>({...l,seq:f+1}));return {...i,entries:n===void 0?p:p.slice(Math.max(0,p.length-n))}}let a=o.select({seq:Kt.seq,timestamp:Kt.timestamp,level:Kt.level,message:Kt.message}).from(Kt).where(eq(Kt.task_id,e)).orderBy(n===void 0?asc(Kt.seq):desc(Kt.seq)),u=(n===void 0?a.all():a.limit(n).all()).map(({seq:p,timestamp:l,level:f,message:g})=>({seq:p,timestamp:l,level:f,message:g}));return n!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var Ul=x(()=>{h();});var Jk,J,Rn=x(()=>{h();Jk=new Set(["ACCOUNT_SETTING_REQUIRED","MODEL_RETIRED","SUBSCRIPTION_REQUIRED"]),J=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=Jk.has(this.code)?"config":o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs,this.settingReason=o?.settingReason,this.replacementModel=o?.replacementModel,this.providerReason=o?.providerReason;}providerStr;code;kind;retryAfterMs;settingReason;replacementModel;providerReason;stdout};});var Fn,Ia=x(()=>{h();Rn();Fn=class extends J{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function Os(t){if(typeof t!="string")return;let e=t.trim();if(e)return e=e.replace(/^\s*at\s+[^\r\n]+(?:\r?\n|$)/gim,""),e=e.replace(/(^|[\r\n])\s*(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-auth-token|cookie|set-cookie)\s*:\s*[^\r\n]*/gim,`$1[HTTP HEADER ${Ze}]`),e=Yk(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${Ze}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,Ze),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,Ze),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,Ze),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,Ze),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,Ze),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,Ze),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,Ze),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,Ze),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Ze),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${Ze}${r}${Ze}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${Ze}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,ql),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,ql),e=e.replace(/[\r\n]{3,}/g,`
45
+ )`),conflictSupersededCheck:check("app_sync_conflicts_superseded_ck",sql`${t.state} != 'superseded' OR ${t.superseded_by} IS NOT NULL`),conflictResolutionCheck:check("app_sync_conflicts_resolution_ck",sql`(${t.resolution_request_id} IS NULL AND ${t.resolution_choice} IS NULL) OR (length(${t.resolution_request_id}) BETWEEN 1 AND 128 AND ${t.resolution_choice} IN ('keep_local', 'use_cloud', 'keep_both'))`),conflictTimeCheck:check("app_sync_conflicts_time_ck",sql`${t.updated_at} >= ${t.created_at}`),conflictBindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[pr.binding_id]}).onDelete("cascade"),conflictIdentityUnique:uniqueIndex("app_sync_conflicts_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.local_version,t.remote_revision,t.remote_fingerprint),conflictLookup:index("app_sync_conflicts_lookup_idx").on(t.account_key,t.binding_id,t.state,t.updated_at)})),sqliteTable("app_sync_conflict_resolutions",{request_id:text("request_id").primaryKey().notNull(),conflict_id:text("conflict_id").notNull(),account_key:text("account_key").notNull(),human_identity:text("human_identity").notNull(),choice:text("choice").notNull(),expected_local_version:text("expected_local_version").notNull(),expected_remote_revision:integer("expected_remote_revision").notNull(),expected_remote_fingerprint:text("expected_remote_fingerprint").notNull(),state:text("state").notNull().default("pending"),error_code:text("error_code"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({resolutionRequestIdCheck:check("app_sync_conflict_resolutions_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),resolutionAccountCheck:check("app_sync_conflict_resolutions_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resolutionIdentityCheck:check("app_sync_conflict_resolutions_human_identity_ck",sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),resolutionChoiceCheck:check("app_sync_conflict_resolutions_choice_ck",sql`${t.choice} IN ('keep_local', 'use_cloud', 'keep_both')`),resolutionLocalVersionCheck:check("app_sync_conflict_resolutions_local_version_ck",sql`length(${t.expected_local_version}) BETWEEN 1 AND 256 AND instr(${t.expected_local_version}, '/') = 0 AND instr(${t.expected_local_version}, char(92)) = 0`),resolutionRemoteCheck:check("app_sync_conflict_resolutions_remote_ck",sql`${t.expected_remote_revision} >= 0 AND length(${t.expected_remote_fingerprint}) = 71 AND substr(${t.expected_remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.expected_remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),resolutionStateCheck:check("app_sync_conflict_resolutions_state_ck",sql`${t.state} IN ('pending', 'unknown', 'resolved', 'stale', 'failed')`),resolutionTimeCheck:check("app_sync_conflict_resolutions_time_ck",sql`${t.updated_at} >= ${t.created_at}`),resolutionConflictFk:foreignKey({columns:[t.conflict_id],foreignColumns:[Am.conflict_id]}).onDelete("cascade"),resolutionConflictIdx:index("app_sync_conflict_resolutions_conflict_idx").on(t.conflict_id,t.created_at),resolutionActiveUnique:uniqueIndex("app_sync_conflict_resolutions_one_active_uq").on(t.conflict_id).where(sql`${t.state} IN ('pending', 'unknown')`)})),sqliteTable("app_sync_account_data_purges",{request_id:text("request_id").primaryKey().notNull(),binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),root_fingerprint:text("root_fingerprint").notNull(),human_identity:text("human_identity").notNull(),state:text("state").notNull().default("pending"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({purgeRequestIdCheck:check("app_sync_account_data_purges_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),purgeAccountCheck:check("app_sync_account_data_purges_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),purgeWorkspaceCheck:check("app_sync_account_data_purges_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),purgeRootCheck:check("app_sync_account_data_purges_root_fingerprint_ck",sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),purgeHumanIdentityCheck:check("app_sync_account_data_purges_human_identity_ck",sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),purgeStateCheck:check("app_sync_account_data_purges_state_ck",sql`${t.state} IN ('pending', 'complete')`),purgeTimeCheck:check("app_sync_account_data_purges_time_ck",sql`${t.updated_at} >= ${t.created_at}`),purgeAccountIndex:index("app_sync_account_data_purges_account_idx").on(t.account_key,t.state,t.updated_at)}));});var Xu=x(()=>{h();sqliteTable("route_states",{workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),config_revision:text("config_revision").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),updated_at:text("updated_at").notNull()},t=>({pk_route_state_workspace:primaryKey({columns:[t.workspace_key,t.route_id]})})),sqliteTable("route_sticky_bindings",{workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),thread_id:text("thread_id").notNull(),candidate_id:text("candidate_id").notNull(),updated_at:text("updated_at").notNull()},t=>({uniq_route_sticky_thread:uniqueIndex("uniq_route_sticky_thread").on(t.workspace_key,t.route_id,t.thread_id),idx_route_sticky_candidate:index("idx_route_sticky_candidate").on(t.workspace_key,t.route_id,t.candidate_id)})),sqliteTable("route_decisions",{id:text("id").primaryKey(),workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),task_id:text("task_id").notNull(),config_revision:text("config_revision").notNull(),candidate_id:text("candidate_id").notNull(),provider:text("provider").notNull(),model:text("model").notNull(),reason:text("reason").notNull(),eligible_ids:text("eligible_ids").notNull(),blocked_causes:text("blocked_causes").notNull(),link_errors:text("link_errors").notNull(),created_at:text("created_at").notNull()},t=>({uniq_route_task_decision:uniqueIndex("uniq_route_task_decision").on(t.workspace_key,t.route_id,t.task_id),idx_route_decisions_workspace_created:index("idx_route_decisions_workspace_created").on(t.workspace_key,t.route_id,t.created_at)})),sqliteTable("route_quota_observations",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),model:text("model"),status:text("status",{enum:["ok","blocked"]}).notNull(),source:text("source").notNull(),reset_at:text("reset_at"),observed_at:text("observed_at").notNull()},t=>({uniq_route_quota_observation:uniqueIndex("uniq_route_quota_observation").on(t.provider,t.account_ref,t.model,t.source),idx_route_quota_observations_reset:index("idx_route_quota_observations_reset").on(t.reset_at)}));});var we=x(()=>{h();rs();cr();Zc();tu();no();su();au();du();uu();_u();fu();mu();ku();Tu();Eu();Ru();bu();Au();Nu();vu();Zi();Mu();Hu();Uu();ju();Wu();Gu();zu();Ku();Vu();Ju();Xu();});var Xm,po,fa=x(()=>{h();_e();ye();Ee();ke();we();Xm=50,po=class extends F{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=`${e.dbRoot}/.crewx/crewx.db`);}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(){let e=this.resolveDbPath(),n=L(e);try{return ee(n.db,e),n}catch(r){throw n.close(),r}}recordAccepted(e){if(e.actorKind!=="human"||!e.workspaceId||!e.actorId||!e.agentId)return false;let n;try{n=this.openHandle();let r=e.acceptedAt??new Date().toISOString();return n.db.insert(nt).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[nt.workspace_id,nt.actor_id,nt.agent_id],set:{last_accepted_at:sql`MAX(${nt.last_accepted_at}, excluded.last_accepted_at)`}}).run(),!0}catch(r){return console.error("[AgentSendHistoryRepository] Failed to record accepted agent send",r),false}finally{n?.close();}}findRecentAgents(e,n){let r;try{return r=this.openHandle(),r.db.select({agentId:nt.agent_id,lastAcceptedAt:nt.last_accepted_at}).from(nt).where(and(eq(nt.workspace_id,e),eq(nt.actor_id,n))).orderBy(desc(nt.last_accepted_at),asc(nt.agent_id)).limit(Xm).all()}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to find recent agent sends",o)}finally{r?.close();}}};});function kr(t){return typeof t=="string"&&Lt.includes(t)}function _o(t){if(!t||!t.includes("workflow"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.workflowRunId;if(typeof r=="string"&&r!=="")return r;let o=n.workflow;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let s=o.exec_id;if(typeof s=="string"&&s!=="")return s}return null}var Lt,yr=x(()=>{h();Lt=["workflow_card","workflow_ui_instance","workflow_run"];});var Tr,ka,Tl,ya=x(()=>{h();Tr={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5-5":{input:4,cachedInput:.2,output:20},"claude-opus-5-5-medium":{input:4,cachedInput:.2,output:20},"claude-opus-5":{input:5,cachedInput:.5,output:25},"claude-opus-4-8":{input:5,cachedInput:.5,output:25},"claude-opus-4-7":{input:5,cachedInput:.5,output:25},"claude-opus-4-6":{input:5,cachedInput:.5,output:25},"claude-sonnet-5-5":{input:2,cachedInput:.1,output:10},"claude-sonnet-5-5-medium":{input:2,cachedInput:.1,output:10},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-5-5":{input:.1,cachedInput:.01,output:.5},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-6.1-sol":{input:2,cachedInput:.1,output:10},"gpt-6.1-terra":{input:1,cachedInput:.05,output:5},"gpt-6-sol":{input:2,cachedInput:.2,output:10},"gpt-6-luna":{input:.1,cachedInput:.01,output:.5},"gpt-5.6-sol":{input:4,cachedInput:.4,output:20},"gpt-5.6-terra":{input:2,cachedInput:.2,output:12},"gpt-5.6-luna":{input:.2,cachedInput:.02,output:1.2},"gpt-5.5":{input:5,cachedInput:.5,output:30},"gpt-5.4":{input:2.5,cachedInput:.25,output:15},"gpt-5.4-mini":{input:.75,cachedInput:.075,output:4.5},"gpt-5.3-codex":{input:1.75,cachedInput:.175,output:14},"gpt-5-mini":{input:.4,cachedInput:.1,output:1.6},"gpt-4.1":{input:2,cachedInput:.5,output:8},"gpt-4o":{input:2.5,cachedInput:1.25,output:10},"glm-5.3-flash":{input:.15,cachedInput:.03,output:.5},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"deepseek-v4.1-flash":{input:.3,cachedInput:.006,output:1.2},"qwen3.8-flash":{input:.164,cachedInput:.018,output:.514},"minimax-m3":{input:.3,cachedInput:.06,output:1.2},"kimi-k2.7-code":{input:.95,cachedInput:.19,output:4},"gemini-3.8-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-4-argon":{input:4,cachedInput:.2,output:20},"gemini-3.7-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-3.6-flash":{input:1.5,cachedInput:.15,output:7.5},"grok-4.7":{input:2,cachedInput:.5,output:6},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},ka=new Set(["gpt-5.3-codex-spark","claude-opus-4-6-thinking","gpt-oss-120b","glm-5.3-flash-free","deepseek-v4.1-flash-free"]),Tl=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-haiku-5-5","claude-opus-4-6","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7","claude-opus-4-7[1m]","claude-opus-4-8","claude-opus-4-8[1m]","claude-opus-5","claude-opus-5-5","claude-opus-5-5-medium","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","claude-sonnet-5-5-medium","deepseek-v4.1-flash","deepseek-v4.1-flash-free","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","gemini-3.8-flash","gemini-4-argon","glm-5.1","glm-5.2","glm-5.3-flash","glm-5.3-flash-free","gpt-4.1","gpt-4o","gpt-5-mini","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini","gpt-5.5","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra","gpt-6-luna","gpt-6-sol","gpt-6.1-sol","gpt-6.1-terra","gpt-oss-120b","grok-4.5","grok-4.6","grok-4.7","kimi-k2.7-code","minimax-m3","qwen3.8-flash"]);});function Ta(t){let e=t.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let n=e.lastIndexOf("/");return n>=0&&(e=e.slice(n+1)),e=e.replace(/-\d{8}$/,""),e}function Ek(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),fo;let e=Ta(t),n=wk[e];if(n)return Es[n]??Tr[n]??fo;if(Es[e])return Es[e];if(Tr[e])return Tr[e];if(ka.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),fo;if(Tl.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),fo;let r={...Tr,...Es};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),fo}function Rk(t,e,n,r=0,o){let s=Ek(n),i=Math.min(r,t),c=(t-i)*s.input/1e6,u=i*s.cachedInput/1e6,p=e*s.output/1e6;return c+u+p}function wl(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:Rk(e??0,n??0,o,r??0)}var wk,fo,Es,Rs=x(()=>{h();ya();ya();wk={opus:"claude-opus-4-8",sonnet:"claude-sonnet-4-6",haiku:"claude-haiku-4-5","codex-mini":"gpt-5.3-codex",codex:"gpt-5.3-codex"},fo={input:0,cachedInput:0,output:0},Es={};});function bs(t){if(!t||!t.includes("schedule_id"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.trigger;if(typeof r!="string"||!Sk.includes(r))return null;let o=n.schedule_id;return typeof o=="string"&&o!==""?o:null}var Ss,El,Rl,Sl,wa,Sk,Ea=x(()=>{h();Ss="tasks_run_columns",El="idx_tasks_workflow_run_id",Rl="idx_tasks_ws_schedule_started",Sl="idx_tasks_ws_human_started",wa=[{name:El,sql:`CREATE INDEX IF NOT EXISTS ${El} ON tasks (workflow_run_id) WHERE workflow_run_id IS NOT NULL`},{name:Rl,sql:`CREATE INDEX IF NOT EXISTS ${Rl} ON tasks (workspace_id, started_at) WHERE schedule_id IS NOT NULL`},{name:Sl,sql:`CREATE INDEX IF NOT EXISTS ${Sl} ON tasks (workspace_id, started_at) WHERE actor_kind = 'human'`}],Sk=["cron","cron_manual"];});function Sa(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function bl(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function As(t){return Number.isSafeInteger(t)&&t>0}function vk(t){let e=t.trim();if(!e)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(e);return n?.[1]??n?.[2]??e.split(/\s+/,1)[0]??""}function Ck(t,e,n){let r=n==="win32"?t.toLowerCase():t,o=n==="win32"?e.toLowerCase():e;if(!o.trim())return false;if(o==="agy"){let s=vk(t).split(/[\\/]/).pop()??"",i=n==="win32"?s.toLowerCase():s;return i==="agy"||n==="win32"&&(i==="agy.exe"||i==="agy.cmd")}return r.includes(o)}function Dk(t,e,n){return e.some(r=>Ck(t,r,n))}function xk(t,e){try{let n=spawnSync(t,e,{encoding:"utf8",timeout:Ra,windowsHide:!0});return {status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",error:n.error}}catch(n){return {status:null,stdout:"",stderr:"",error:Sa(n)}}}function Lk(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(u){n({status:null,stdout:"",stderr:"",error:Sa(u)});return}let o="",s="",i=false,a,c=setTimeout(()=>{try{r.kill();}catch{}a({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${Ra}ms`)});},Ra);a=u=>{i||(i=true,clearTimeout(c),n(u));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",u=>{o+=String(u);}),r.stderr?.on("data",u=>{s+=String(u);}),r.once("error",u=>{a({status:null,stdout:o,stderr:s,error:u});}),r.once("close",u=>{a({status:u,stdout:o,stderr:s});});})}async function ba(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Lk(t,e)}function Pk(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Mk(){return new Promise(t=>{setImmediate(t);})}function En(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return bl(n)==="ESRCH"?"not_found":bl(n)==="EPERM"?"alive":"unknown"}}function $k(t,e){let n=En(-t,e),r=En(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function Il(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??Nk),i=Date.now()+o,a,c=o===0,u=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(p=>{a=setTimeout(p,o);});u.then(()=>{c=true;});try{for(await Mk();;){let p=$k(t,e);if(p==="not_found")return p;let l=i-Date.now();if(c||l<=0)return p;await Promise.race([u,Pk(Math.min(s,l))]);}}finally{a!==void 0&&clearTimeout(a);}}async function Al(t,e,n,r,o){let s=await Il(t,e,o.hardConfirmMs??Ok,{...o,sleep:void 0});return s==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:s==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function Nl(t,e,n={}){if(!As(t))return "unknown";let r=n.platform??process.platform,o=r==="win32"?"powershell.exe":"ps",s=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],i;try{i=await ba(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let a=i.stdout.trim();return a?Dk(a,e,r)?"owned":"not_owned":"not_found"}function Bk(t){let e=Hk.exec(t.trim());if(!e)return;let[,n="0",r="0",o="0",s="0"]=e;return ((Number(n)*24+Number(r))*60+Number(o))*60+Number(s)}function Fk(t){let e=t.trim(),n=qk.exec(e);if(n){let[,o,s,i,a,c,u,p,l]=n;return Date.UTC(Number(o),Number(s)-1,Number(i),Number(a),Number(c),Number(u),Math.trunc(Number(p)/1e3))-Number(l)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function Ol(t,e){return e==="win32"?{command:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write($p.CreationDate.ToUniversalTime().ToString('o')) }`]}:{command:"ps",args:["-p",String(t),"-o","pgid=","-o","etime=","-o","stat="]}}function vl(t,e,n){if(t.error)return {status:"unknown"};let r=t.stdout.trim();if(!r)return t.status===0||t.status===1?{status:"not_found"}:{status:"unknown"};if(t.status!==0)return {status:"unknown"};if(e==="win32"){let i=Fk(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let o=Uk.exec(r),s=o?Bk(o[2]):void 0;return !o||s===void 0?{status:"unknown"}:o[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-s*1e3,groupId:Number(o[1])}}function Cl(t,e={}){if(!As(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=Ol(t,n),s=e.runCommand??xk,i;try{i=s(r,o);}catch{return {status:"unknown"}}return vl(i,n,Date.now())}async function Dl(t,e={}){if(!As(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=Ol(t,n),s;try{s=await ba(r,o,e);}catch{return {status:"unknown"}}return vl(s,n,Date.now())}async function ho(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=f=>({status:"failed",pid:t,method:r,error:f});if(!As(t))return o("Invalid process ID");let s=e.kill??process.kill,i=En(t,s);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let f;try{f=await ba("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){f={status:null,stdout:"",stderr:"",error:Sa(m)};}let g=En(t,s);return g==="not_found"?f.status===0&&!f.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(g==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let a,c=e.signal??"SIGKILL";try{s(-t,c);}catch(f){a=f;}if(c==="SIGKILL")return Al(t,s,a,r,e);if(await Il(t,s,e.graceMs??Ik,e)==="not_found")return a?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let p;try{s(-t,"SIGKILL");}catch(f){p=f;}let l=await Al(t,s,p,r,e);return l.status==="terminated"?l:l.status==="not_found"?a?l:{status:"terminated",pid:t,method:r}:o(l.error??"Process termination failed")}var Ra,go,Ik,Nk,Ok,Is,Hk,Uk,qk,Aa=x(()=>{h();Ra=3e3,go="SIGINT",Ik=2e3,Nk=25,Ok=100;Is=3e3,Hk=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,Uk=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,qk=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function $l(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new _("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new _("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Pl(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new _("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new _("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>$l(r,o))}catch(r){throw r instanceof _?new _("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Hl(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new _("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new _("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new _("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Ml(t){return {taskId:t.id,source:Hl(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Vk(t){if(!Number.isInteger(t)||t<0)throw new _("VALIDATION","Task log tail limit must be a non-negative integer")}var Bn,Ns=x(()=>{h();_e();ye();Ee();ke();we();Bn=class extends F{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?it(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new _("NOT_FOUND","Database not found");let r=L(n);if(e)try{ee(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:d.id,log_storage:d.log_storage,last_log_seq:d.last_log_seq,log_revision:d.log_revision,logs:d.logs}).from(d).where(eq(d.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:d.id,log_storage:d.log_storage,last_log_seq:d.last_log_seq,log_revision:d.log_revision,logs:d.logs}).from(d).where(eq(d.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new _("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,i)=>$l(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new _("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let a=this.requireStateRowInTransaction(i,e),c=Hl(a);if(c==="blob"){let f=Pl(e,a.logs);if(i.update(d).set({logs:JSON.stringify([...f,...r]),log_revision:sql`${d.log_revision} + 1`}).where(eq(d.id,e)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:a.log_revision+1,lastSeq:a.last_log_seq}}let u=a.last_log_seq+1,p=a.last_log_seq+r.length;if(i.insert(Kt).values(r.map((f,g)=>({task_id:e,seq:u+g,timestamp:f.timestamp,level:f.level,message:f.message}))).run(),i.update(d).set({last_log_seq:p,log_revision:sql`${d.log_revision} + 1`}).where(eq(d.id,e)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:a.log_revision+1,lastSeq:p}},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?Ml(r):void 0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return Vk(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=Ml(s);if(i.source==="blob"){let p=Pl(e,s.logs).map((l,f)=>({...l,seq:f+1}));return {...i,entries:n===void 0?p:p.slice(Math.max(0,p.length-n))}}let a=o.select({seq:Kt.seq,timestamp:Kt.timestamp,level:Kt.level,message:Kt.message}).from(Kt).where(eq(Kt.task_id,e)).orderBy(n===void 0?asc(Kt.seq):desc(Kt.seq)),u=(n===void 0?a.all():a.limit(n).all()).map(({seq:p,timestamp:l,level:f,message:g})=>({seq:p,timestamp:l,level:f,message:g}));return n!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var Ul=x(()=>{h();});var Jk,J,Rn=x(()=>{h();Jk=new Set(["ACCOUNT_SETTING_REQUIRED","MODEL_RETIRED","SUBSCRIPTION_REQUIRED"]),J=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=Jk.has(this.code)?"config":o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs,this.settingReason=o?.settingReason,this.replacementModel=o?.replacementModel,this.providerReason=o?.providerReason;}providerStr;code;kind;retryAfterMs;settingReason;replacementModel;providerReason;stdout};});var Fn,Ia=x(()=>{h();Rn();Fn=class extends J{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function Os(t){if(typeof t!="string")return;let e=t.trim();if(e)return e=e.replace(/^\s*at\s+[^\r\n]+(?:\r?\n|$)/gim,""),e=e.replace(/(^|[\r\n])\s*(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-auth-token|cookie|set-cookie)\s*:\s*[^\r\n]*/gim,`$1[HTTP HEADER ${Ze}]`),e=Yk(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${Ze}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,Ze),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,Ze),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,Ze),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,Ze),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,Ze),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,Ze),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,Ze),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,Ze),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Ze),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${Ze}${r}${Ze}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${Ze}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,ql),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,ql),e=e.replace(/[\r\n]{3,}/g,`
46
46
 
47
47
  `).trim(),Xk(e,1024)||void 0}function Xk(t,e){let n=new TextEncoder;if(n.encode(t).byteLength<=e)return t;let r="",o=0;for(let s of t){let i=n.encode(s).byteLength;if(o+i>e)break;r+=s,o+=i;}return r}function Yk(t){let e=/\b(?:request|response|http)?\s*body\s*[:=]\s*/gim,n="",r=0,o;for(;(o=e.exec(t))!==null;){if(o.index<r)continue;let s=o.index+o[0].length,i=Qk(t,s),a=i>=0?i:t.indexOf(`
48
48
  `,s)>=0?t.indexOf(`
@@ -82,7 +82,7 @@ ${r.join(`
82
82
  time_updated = excluded.time_updated
83
83
  `);r.transaction(i=>{for(let a of i)o.run(a);})(n);}finally{r.close();}}function hT(t){if(!t)return [];let e=[];for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="-s"||r==="--session"){let o=t[n+1],s=o!==void 0&&!o.startsWith("-");e.push({sessionId:s?o:void 0}),s&&(n+=1);continue}(r.startsWith("--session=")||r.startsWith("-s="))&&e.push({sessionId:r.slice(r.indexOf("=")+1)||void 0});}return e}function mT(t){if(!t)return;let e=[];for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="-s"||r==="--session"){t[n+1]!==void 0&&!t[n+1].startsWith("-")&&(n+=1);continue}r.startsWith("--session=")||r.startsWith("-s=")||e.push(r);}return e}function Us(t){let e=mT(t.additionalArgs);return {...t,...e===void 0?{}:{additionalArgs:e},resumeSessionId:void 0}}function kT(t,e){try{return !!t.prepare("SELECT id FROM session_v2 WHERE id = ?").get(e)}catch(n){if(n instanceof Error&&/no such table: session_v2/i.test(n.message))return false;throw n}}function yT(t,e,n){let r=new t(e,{readonly:true,fileMustExist:true});try{return kT(r,n)}finally{r.close();}}async function za(t,e={}){let n;try{n=await(e.loadSqlite??cT)();}catch{throw new J("OpenCode isolation requires the optional better-sqlite3 dependency. Install it and retry.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}let r=e.crewxHome??Hs(),o=Ao(r),s=Io(r),i=uT(s),a=lT(e.userDataHome),c=_T(n,a);if(c.length>0){if(!Pp(n,i))try{await(e.initializeDatabase??fT)(o);}catch{throw new J("Could not initialize the isolated OpenCode credential database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}if(!Pp(n,i))throw new J("The isolated OpenCode credential database is unavailable.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"});try{gT(n,i,c);}catch{throw new J("Could not copy API-key credentials into the isolated OpenCode database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}let u=hT(t.additionalArgs),p=u.map(f=>f.sessionId),l=u.length>0?p[p.length-1]:t.resumeSessionId;if(!l)return u.length>0?Us(t):t;if(p.some(f=>f!==l)||!existsSync(i))return Us(t);try{return yT(n,i,l)?{...t,resumeSessionId:l}:Us(t)}catch{throw new J("Could not read the isolated OpenCode session database safely.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}var Ka=x(()=>{h();Rn();Wa();Lp();});function zn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function Va(){let t;try{let n=(await import('better-sqlite3')).default,r=join(Io(),"opencode.db");t=new n(r,{readonly:!0,fileMustExist:!0});let o=t.prepare("SELECT value FROM kv WHERE key = ?").get("models-dev:v2:catalog");if(!o||typeof o.value!="string")throw new Error("OpenCode model catalog row is unavailable");let s=JSON.parse(o.value);if(!zn(s))throw new Error("OpenCode model catalog shape is unavailable");let i=typeof s.body=="string"?JSON.parse(s.body):s.body;if(!zn(i))throw new Error("OpenCode model catalog body shape is unavailable");let a=new Map;for(let[c,u]of Object.entries(i)){if(!c||!zn(u)||!zn(u.models))throw new Error("OpenCode model provider shape is unavailable");for(let[p,l]of Object.entries(u.models)){if(!p||!zn(l))throw new Error("OpenCode model shape is unavailable");let f=l.capabilities;if(f===void 0)continue;if(!zn(f))throw new Error("OpenCode model capability shape is unavailable");let g=f.reasoning;if(g===void 0)continue;if(!zn(g))throw new Error("OpenCode reasoning capability shape is unavailable");let m=g.effort;(m===void 0||Array.isArray(m)&&m.every(k=>typeof k=="string"))&&a.set(`${c}/${p}`,Array.isArray(m)?m:[]);}}return a}catch{return console.debug("[opencode] could not read private model effort catalog; omitting effort choices"),new Map}finally{try{t?.close();}catch{}}}var $p=x(()=>{h();Xa();Np();Cp();Wa();Ka();Sn();});function AT(t){return t?bT[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function bt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function IT(){let t;try{t=Io();}catch{return Va().catch(()=>new Map)}let e=Date.now();if(Hp===t&&qs&&qs.expiresAt>e)return qs.result;Hp=t;let n=Va().catch(()=>new Map);return qs={expiresAt:e+ST,result:n},n}async function NT(t){let e=await za(t),n=t.additionalArgs??[],r=bt(n,"--model")||bt(n,"-m");if(!t.model||!t.effort||r)return e;let o=(await IT()).get(t.model);return !o||o.includes(t.effort)?e:(console.debug("[opencode] requested effort is not listed for this model; using OpenCode default"),{...e,effort:void 0})}function jp(t){let e=[],n=0,r=false,o=false,s=0;for(let a=0;a<t.length;a++){let c=t[a];if(o){o=false;continue}if(c==="\\"&&r){o=true;continue}if(c==='"'){r=!r;continue}if(!r){if(c==="{")n++;else if(c==="}"&&(n--,n===0)){let u=t.slice(s,a+1).trim();u&&e.push(u),s=a+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function Se(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Wp(t){let e=Se(t.part)?t.part:void 0;return t.type==="reasoning"||e?.type==="reasoning"}function OT(t){let e=Se(t.part)?t.part:void 0;return (typeof e?.text=="string"?e.text:typeof t.text=="string"?t.text:void 0)?.trim()||void 0}function vT(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let i=JSON.parse(o);Se(i)?e.push(i):n=!0;continue}catch{}let s=jp(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of s)try{let a=JSON.parse(i);Se(a)?e.push(a):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Za(t){let e=Se(t.error)?t.error:void 0,n=e&&Se(e.data)?e.data:void 0,r=Gp(e),o=St(e?.name),s=St(n?.message)??St(e?.message)??Ya(r)??St(t.message)??St(t.errorMessage)??St(t.error),i=St(t.ref),a=o&&s&&o!==s?`${o}: ${s}`:o??s??Fp;return (i?`${a} (ref: ${i})`:a).slice(0,ET)}function Up(t){let e=Se(t.error)?t.error:void 0,n=typeof e?.type=="string"?e.type:void 0,r=typeof e?.status=="number"?e.status:Number(e?.status),o=Za(t),s=Gp(e),i=s&&Se(s.error)?s.error:void 0,a=typeof i?.type=="string"?i.type:void 0,c=[o,Ya(s)].filter(Boolean).join(`
84
84
  `);if(r===402||CT(c))return new J(`OpenCode subscription is required: ${o}`,ft,{code:"SUBSCRIPTION_REQUIRED",kind:"config",providerReason:So(o)});if(r===403&&(a==="RegionError"||a==="FreeTierError"))return new J(`OpenCode account settings are required: ${o}`,ft,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:"access",providerReason:So(o)});if(n==="provider.auth"||r===401||r===403)return new J(`OpenCode authentication is required: ${o}`,ft,{code:"AUTH_REQUIRED",kind:"config"});if(r===410||a==="ModelDeprecated")return new J(`OpenCode model has been retired: ${o}`,ft,{code:"MODEL_RETIRED",kind:"config",replacementModel:DT(s,e,t),providerReason:So(o)});if(n==="provider.free-limit"||r===429){let u=xT(e);return new J(`OpenCode rate limit reached: ${o}`,ft,{code:"RATE_LIMITED",kind:"transient",...u===void 0?{}:{retryAfterMs:u}})}if(n==="provider.no-route")return new J(`OpenCode model or variant unavailable: ${o}`,ft,{code:"MODEL_UNAVAILABLE",kind:"config"});if(n==="provider.invalid-request"&&r===400){let u=[o,Ya(s)].filter(g=>g!==void 0),p=u.find(g=>/requires global regions/i.test(g)),l=u.find(g=>/trains on request data/i.test(g)),f=p?"region":l?"training_consent":void 0;if(f)return new J(`OpenCode account settings are required: ${o}`,ft,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:f,providerReason:So(p??l)})}return new J(`OpenCode error: ${o}`,ft,{code:"PROVIDER_CRASHED",kind:"transient"})}function Gp(t){let n=(t&&Se(t.response)?t.response:void 0)?.body;if(Se(n))return n;if(typeof n=="string")try{let r=JSON.parse(n);return Se(r)?r:void 0}catch{return}}function Ya(t){let e=t&&Se(t.error)?t.error:void 0;return St(e?.message)??St(t?.message)}function CT(t){return /insufficient\s+(?:balance|account funds)|credit\s+limit\s+exceeded|payment\s+required|account invoice is overdue|billing_error|please add or update your payment method|(?:GLM Coding Plan|enterprise) package has expired|your current subscription plan does not yet include access to/i.test(t)}function DT(t,e,n){let r=t&&Se(t.metadata)?t.metadata:void 0,o=typeof r?.replacement=="string"?r.replacement.trim():void 0;if(!o)return;let s=[r?.model,e?.model,n.model,n.modelID].find(c=>typeof c=="string"&&c.trim().length>0)?.trim(),i=s&&s.includes("/")?s.slice(0,s.indexOf("/")):"opencode-go",a=o.includes("/")?o:`${i}/${o}`;return /^[A-Za-z0-9._/-]{1,128}$/.test(a)?a:void 0}function xT(t){let e=t?.retryAfterMs;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;let r=(t&&Se(t.response)?t.response:void 0)?.body,o=typeof r=="string"?LT(r):Se(r)?r:void 0;if(o){let s=Qa(o);if(s)return qp(s.value,s.key==="retryafterms")}if(typeof r=="string"){let s=r.match(/retry[-_]after(?:\s*[:=]\s*|\s+)["']?([^"'\s,;}]+)/i);if(s?.[1])return qp(s[1],false)}}function LT(t){try{let e=JSON.parse(t);return Se(e)?e:void 0}catch{return}}function Qa(t){if(Array.isArray(t)){for(let e of t){let n=Qa(e);if(n)return n}return}if(Se(t)){for(let[e,n]of Object.entries(t)){let r=e.toLowerCase().replace(/[-_]/g,"");if(r==="retryafterms"||r==="retryafter")return {value:n,key:r}}for(let e of Object.values(t)){let n=Qa(e);if(n)return n}}}function qp(t,e){if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return e?t:Math.round(t*1e3);if(typeof t!="string"||!t.trim())return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return e?n:Math.round(n*1e3);if(e)return;let r=Date.parse(t);return Number.isFinite(r)?Math.max(0,r-Date.now()):void 0}function Bp(t){let e=vT(t),n=[],r=null,o=0,s=[],i=[],a,c=false;for(let u of e.events){if(Wp(u))continue;let p=typeof u.type=="string"?u.type:void 0;if(p){if(p==="text"){let l=Se(u.part)?u.part:void 0,f=typeof l?.text=="string"?l.text:void 0;f?.trim()&&n.push(f.trim());continue}if(p==="result"){typeof u.result=="string"&&(r=u.result);continue}if(p==="tool_use"){o++;continue}if(p==="error"){s.push(u),i.push(Za(u));continue}if(p==="step_finish"){c=true;let l=Se(u.part)?u.part:void 0;a=typeof l?.reason=="string"?l.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorEvents:s,errorMessages:i,terminalReason:a,hasTerminal:c}}function zp(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function PT(){return new J("OpenCode returned no assistant output.",ft,{code:"EMPTY_OUTPUT",kind:"transient"})}function MT(){return new J("OpenCode emitted malformed JSON output.",ft,{code:"PROVIDER_CRASHED",kind:"transient"})}function $T(t,e){switch(zp(t)){case "length":return new J("OpenCode stopped because the context window was exceeded.",ft,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new J("OpenCode stopped because the content filter blocked the response.",ft,{code:"UNKNOWN",kind:"permanent"});case "error":return new J(`${Fp} while generating a response.`,ft,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var wT,ft,Fp,ET,RT,ST,Hp,qs,bT,ed,td=x(()=>{h();Rn();Ip();Ro();br();Wn();$p();Ka();wT=new Set(["step_start","step_finish"]),ft="cli/opencode",Fp="OpenCode provider error",ET=240,RT="Follow the instructions provided on standard input.",ST=3e5,bT={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};ed={command:"opencode",prepare:NT,meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];bt(o,"--format")||o.push("--format","json"),bt(o,"--thinking")||o.push("--thinking"),!bt(o,"--standalone")&&!bt(o,"--server")&&o.push("--standalone"),e.resumeSessionId&&!bt(o,"-s")&&!bt(o,"--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=AT(e.mode);bt(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!bt(o,"--auto")&&o.push("--auto");let a=bt(o,"--model")||bt(o,"-m");if(e.model&&!a){let c=e.effort?`${e.model}#${e.effort}`:e.model;o.push("--model",c);}else e.effort&&!e.model&&!a&&console.debug("[opencode] ignoring effort because no model is configured");return o.push(RT),{args:o,stdinMessage:t,env:Ao()}},extractText(t){let e=Bp(t),n=e.errorEvents[0];if(n)throw Up(n);let r=$T(e.terminalReason??"");if(r)throw r;let o=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(o!==void 0)return o;if(e.resultText?.trim())return e.resultText;if(e.malformed)throw MT();let s=zp(e.terminalReason);if(e.hasTerminal&&s==="tool-calls"&&e.toolUseCount>0)return "";throw PT()},interpretExit(t,e,n=""){if(t===0)return null;let o=Bp(n).errorEvents[0];return o?Up(o):null},parseResultMeta(t){let e=Ir(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e,n){let r=e??new Date().toISOString(),o=[],s=new Map,i;try{JSON.parse(t),i=[t];}catch{i=jp(t),i.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let a of i){let c;try{c=JSON.parse(a);}catch{continue}let u=$t(c,r),p=c.type;if(Wp(c)){let l=OT(c);if(!l)continue;let f=Se(c.part)?c.part:void 0,g=typeof f?.id=="string"?f.id:typeof c.id=="string"?c.id:void 0,m=l;if(g){let k=`opencode.reasoning:${g}`,T=n?.state.get(k),b=typeof T=="string"?T:s.get(g);if(typeof b=="string"&&(b===l||b.startsWith(l))||typeof b=="string"&&l.startsWith(b)&&(m=l.slice(b.length).trim(),!m))continue;s.set(g,l),n?.state.set(k,l);}o.push({timestamp:u,type:"thinking",content:m});continue}if(p){if(p==="text"){let f=c.part?.text;f&&o.push({timestamp:u,type:"text",content:f});continue}if(p==="tool_use"){let l=c.part;if(!l)continue;let f=String(l.tool||""),g=String(l.callID||l.id||""),m=l.state,k=String(m?.status||""),T=m?.input,b=Mt(T);if(o.push({timestamp:u,type:"tool_use",toolName:f,toolUseId:g,toolInput:b}),k==="completed"&&m?.output!==void 0){let w=m.output,M=typeof w=="string"?w:JSON.stringify(w);o.push({timestamp:u,type:"tool_result",toolUseId:g,resultPreview:M,isError:false});}else k==="error"&&o.push({timestamp:u,type:"tool_result",toolUseId:g,resultPreview:String(m?.error||"tool error"),isError:true});continue}if(p==="error"){let l=Za(c);o.push({timestamp:u,type:"error",content:l,errorMessage:l});continue}}}return o},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?wT.has(r):!1}catch{return false}}};});var Kp=x(()=>{h();});function Bs(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function FT(t,e){let n=[];for(let r=0;r<t.length;r+=1){let o=t[r],s=[...e].find(i=>o===i||o.startsWith(`${i}=`));s?o===s&&r+1<t.length&&(r+=1):n.push(o);}return n}function jT(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],o=r.indexOf("="),s=o>0?r.slice(0,o):r;if(!qT.has(s)){e.push(r);continue}r===s&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function At(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function WT(t,e){if(!(t?UT.has(t)||_n(nd).some(s=>s.id===t):false)||!t)return e;let r=Ar(nd,t),o=$a(nd)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}function fn(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function sd(t){return t.kind==="step_update"?typeof t.step.conversation_id=="string"?t.step.conversation_id:void 0:typeof t.envelope.conversation_id=="string"?t.envelope.conversation_id:void 0}function id(t){return t.step.step_index}function Re(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&Os(e)?.slice(0,500).trim()||void 0}function GT(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&BT.has(n))return n;let r=`${n} ${e??""}`.toLowerCase();return /quota|resource_exhausted|usage[ _-]?limit|credits?.{0,20}exhaust/.test(r)?"QUOTA_EXHAUSTED":/rate[ _-]?limit|throttl/.test(r)?"RATE_LIMITED":/auth|sign[ _-]?in|log(?:ged)?[ _-]?in|unauthori[sz]ed|credential/.test(r)?"AUTH_REQUIRED":[/unknown (?:flag|option)/,/flag provided but not defined/,/unrecognized (?:flag|option)/,/invalid value for (?:flag|option)/,/invalid (?:flag|option)/].some(s=>s.test(r))?"INVALID_PROVIDER_FORMAT":/invalid.{0,24}model|model.{0,24}(unknown|unavailable|not found|not recognized)|config/.test(r)?"MODEL_UNAVAILABLE":"UNKNOWN"}function zT(t){return t==="AUTH_REQUIRED"||t==="TIMEOUT_IDLE"||t==="TIMEOUT_TOTAL"||t==="TIMEOUT_RESUME"||t==="PROVIDER_CRASHED"?"permanent":t==="MODEL_UNAVAILABLE"||t==="INVALID_PROVIDER_FORMAT"||t==="PROVIDER_NOT_FOUND"?"config":"transient"}function Xp(t){let e=At(t)?t:void 0,n=e&&At(e.error)?e.error:void 0,r=e?Re(e.code)??Re(e.error_code)??Re(n?.code)??Re(n?.error_code):void 0,o=typeof t=="string"?Re(t):e?Re(e.message)??Re(e.error)??Re(e.reason)??Re(n?.message)??Re(n?.error)??Re(n?.reason):void 0,s=GT(r,o),i=e?fn(e.retry_after_ms)??fn(e.retryAfterMs)??fn(n?.retry_after_ms)??fn(n?.retryAfterMs):void 0;return {code:s,kind:zT(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function js(t){let e=Xp(t);return new J(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function ad(t){return new J(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function KT(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=od))throw new J(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${od} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function rd(){return new J("Antigravity CLI returned empty output with exit code 0. agy may have hidden an auth/quota/model error in its log file; inspect ~/.gemini/antigravity-cli/log for details.","cli/antigravity",{code:"EMPTY_OUTPUT",kind:"transient"})}function Ws(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function Gs(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n&&(n.kind==="result"||n.kind==="legacy_result"||n.kind==="agy_error"))return {event:n,index:e}}}function VT(t){let e=Gs(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||Ws(e.event)?.status!=="SUCCESS"||Fs(t))return false;let r=new Map;for(let o of t){if(o.kind!=="step_update"||o.step.step_type!=="agent_response")continue;let s=sd(o),i=id(o);!s||!Number.isSafeInteger(i)||r.set(JSON.stringify([s,i]),o.step);}if(r.size===0)return false;for(let o of r.values())if(o.state!=="DONE"||!At(o.usage)||fn(o.usage.input_tokens)===void 0||fn(o.usage.output_tokens)===void 0)return false;return true}function JT(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function XT(t,e){return At(t)&&At(e)?{...e,...t}:At(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&At(e)?{...e,message:t}:t??e}function YT(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let s of e){let i=At(s)?s:void 0,a=typeof s=="string"?Re(s):Re(i?.display_name)??Re(i?.action);a&&!n.includes(a)&&n.length<5&&n.push(a.slice(0,80));}let r=Math.max(0,e.length-n.length),o=n.length>0?` (${n.join(", ")}${r>0?`, +${r} more`:""})`:"";return new J(`Permission denied: Antigravity blocked ${e.length} requested action${e.length===1?"":"s"}${o}.`,"cli/antigravity",{code:"UNKNOWN",kind:"permanent"})}function Fs(t){let e=Gs(t);if(!e)return;if(e.event.kind==="agy_error")return js(e.event.error);let n=Ws(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return YT(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return ad("Antigravity returned a result with an unsupported status.");let r=n.error,o=XT(r==null||r===""?n:r,JT(t,e.index));return js(o)}function Yp(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function QT(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function ZT(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function Qp(t){let e=Yp(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function ew(t){let e=At(t)?t:void 0,n=e&&At(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,o=(Re(e?.type)??Re(e?.code)??Re(e?.error_type)??Re(n?.type)??Re(n?.code)??Re(n?.error_type)??Re(r)??"TOOL_ERROR").slice(0,60),s=Xp(t).message.slice(0,250);return Qp({type:o,message:s})??"Antigravity reported a tool error."}function Vp(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function Jp(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var nd,UT,qT,od,BT,dd,cd=x(()=>{h();Rn();Kp();Na();To();Sn();Eo();Cs();nd="antigravity",UT=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),qT=new Set(["--conversation","--resume","--continue"]),od=18e4,BT=new Set(["QUOTA_EXHAUSTED","RATE_LIMITED","EMPTY_OUTPUT","AUTH_REQUIRED","MODEL_UNAVAILABLE","TIMEOUT_IDLE","TIMEOUT_TOTAL","TIMEOUT_RESUME","PROVIDER_NOT_FOUND","INVALID_PROVIDER_FORMAT","PROVIDER_CRASHED","UNKNOWN"]);dd={command:"agy",maxInitialInputBytes:od,meta:{displayName:"Antigravity",models:Zl(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=ko(t);if(e?.kind!=="init")return null;let n=e.envelope.conversation_id;return typeof n=="string"&&n.trim().length>0?n.trim():null},buildArgs(t,e,n){KT(t);let{model:r,effort:o}=bn(e.model),s=Pa(r),i=s.model,a=e.effort??o??s.effort,c=WT(i,a),u=e.additionalArgs??[],p=jT(FT(u,new Set(["--input-format","--output-format"]))),l=i&&!Bs(u,"--model")?["--model",i]:[],f=Bs(u,"--effort")?[]:pp(c),g=Bs(u,"--mode")||Bs(u,"--dangerously-skip-permissions")?[]:lp(e.mode),m=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...l,...f,...g,...m,...p],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
85
- `,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=jn(t),n=Gs(e)?.event,r=Fs(e);if(r)throw r;let o=n?Ws(n):void 0;if(o){if(o.status!=="SUCCESS")throw ad("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw ad("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw rd();return o.response}if(e.length>0)throw rd();let s=t.trim();if(!s)throw rd();return s},extractPartialText(t){let e=jn(t),n=Gs(e)?.event;if(!n||n.kind==="agy_error")return;let r=Ws(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=jn(n??""),o=Fs(r);return o||(t!==0&&e.trim()?js(e):null)},parseResultMeta(t){let e=jn(t),n=0,r=0,o=0,s=0,i=new Set;for(let c of e){if(c.kind!=="step_update"||c.step.state!=="DONE"||!At(c.step.usage))continue;let u=sd(c),p=id(c);if(!u||!Number.isSafeInteger(p))continue;let l=JSON.stringify([u,p]);if(i.has(l))continue;let f=c.step.usage,g=fn(f.input_tokens),m=fn(f.output_tokens);g===void 0||m===void 0||(i.add(l),n+=g,r+=m,o+=fn(f.cache_read_tokens)??0,s+=1);}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete:VT(e)},model:null}},parseEvent(t,e,n){let r=ko(t);if(!r)return [];let o=e??new Date().toISOString();if(r.kind==="agy_error")return [Jp(o,js(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let g=Fs([r]);return g?[Jp(o,g)]:[]}if(r.kind!=="step_update")return [];let{step:s}=r,i=sd(r)??"unknown",a=id(r),c=`${i}:${a}`;if((s.state==="DONE"||s.state==="ERROR")&&Vp(n,`antigravity:terminal:${c}`))return [];if(s.step_type==="agent_response")return typeof s.text_delta=="string"&&s.text_delta.length>0?[{timestamp:o,type:"text",content:s.text_delta}]:[];if(s.step_type!=="tool")return [];let u=At(s.tool_info)?s.tool_info:void 0,p=ZT(s,u);if(!p)return [];let l=QT(s);if(s.state==="ACTIVE"){if(Vp(n,`antigravity:active:${c}`))return [];let g=Yp(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:p,toolUseId:l,...g===void 0?{}:{toolInput:g}}]}let f=s.state==="ERROR"?ew(u?.error):Qp(u?.output);return [{timestamp:o,type:"tool_result",toolName:p,toolUseId:l,...f===void 0?{}:{resultPreview:f},...s.state==="ERROR"?{isError:true}:{}}]}};});var Zp=x(()=>{h();Rr();br();Sr();Wn();});function Or(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vr(t){return Or(t)?t:void 0}function ot(t){return typeof t=="string"?t:void 0}function Vn(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function cw(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let a=t[i];if(n===-1){(a==="{"||a==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(a==="\\"&&o){s=true;continue}if(a==='"'){o=!o;continue}o||(a==="{"||a==="["?r+=1:(a==="}"||a==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function No(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return Or(n)?[n]:[]}catch{return cw(e).flatMap(n=>{try{let r=JSON.parse(n);return Or(r)?[r]:[]}catch{return []}})}}function i_(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function Kn(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(Kn).filter(n=>n!==void 0);return e.length>0?e.join(`
85
+ `,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=jn(t),n=Gs(e)?.event,r=Fs(e);if(r)throw r;let o=n?Ws(n):void 0;if(o){if(o.status!=="SUCCESS")throw ad("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw ad("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw rd();return o.response}if(e.length>0)throw rd();let s=t.trim();if(!s)throw rd();return s},extractPartialText(t){let e=jn(t),n=Gs(e)?.event;if(!n||n.kind==="agy_error")return;let r=Ws(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=jn(n??""),o=Fs(r);return o||(t!==0&&e.trim()?js(e):null)},parseResultMeta(t){let e=jn(t),n=0,r=0,o=0,s=0,i=new Set;for(let c of e){if(c.kind!=="step_update"||c.step.state!=="DONE"||!At(c.step.usage))continue;let u=sd(c),p=id(c);if(!u||!Number.isSafeInteger(p))continue;let l=JSON.stringify([u,p]);if(i.has(l))continue;let f=c.step.usage,g=fn(f.input_tokens),m=fn(f.output_tokens);if(g===void 0||m===void 0)continue;i.add(l);let k=fn(f.cache_read_tokens)??0;n+=g+k,r+=m,o+=k,s+=1;}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete:VT(e)},model:null}},parseEvent(t,e,n){let r=ko(t);if(!r)return [];let o=e??new Date().toISOString();if(r.kind==="agy_error")return [Jp(o,js(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let g=Fs([r]);return g?[Jp(o,g)]:[]}if(r.kind!=="step_update")return [];let{step:s}=r,i=sd(r)??"unknown",a=id(r),c=`${i}:${a}`;if((s.state==="DONE"||s.state==="ERROR")&&Vp(n,`antigravity:terminal:${c}`))return [];if(s.step_type==="agent_response")return typeof s.text_delta=="string"&&s.text_delta.length>0?[{timestamp:o,type:"text",content:s.text_delta}]:[];if(s.step_type!=="tool")return [];let u=At(s.tool_info)?s.tool_info:void 0,p=ZT(s,u);if(!p)return [];let l=QT(s);if(s.state==="ACTIVE"){if(Vp(n,`antigravity:active:${c}`))return [];let g=Yp(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:p,toolUseId:l,...g===void 0?{}:{toolInput:g}}]}let f=s.state==="ERROR"?ew(u?.error):Qp(u?.output);return [{timestamp:o,type:"tool_result",toolName:p,toolUseId:l,...f===void 0?{}:{resultPreview:f},...s.state==="ERROR"?{isError:true}:{}}]}};});var Zp=x(()=>{h();Rr();br();Sr();Wn();});function Or(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vr(t){return Or(t)?t:void 0}function ot(t){return typeof t=="string"?t:void 0}function Vn(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function cw(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let a=t[i];if(n===-1){(a==="{"||a==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(a==="\\"&&o){s=true;continue}if(a==='"'){o=!o;continue}o||(a==="{"||a==="["?r+=1:(a==="}"||a==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function No(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return Or(n)?[n]:[]}catch{return cw(e).flatMap(n=>{try{let r=JSON.parse(n);return Or(r)?[r]:[]}catch{return []}})}}function i_(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function Kn(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(Kn).filter(n=>n!==void 0);return e.length>0?e.join(`
86
86
  `):void 0}if(Or(t)){if(typeof t.text=="string")return t.text;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error;if(t.type==="text"&&typeof t.data=="string")return t.data;for(let e of ["content","FileContent","rawOutput"]){let n=Kn(t[e]);if(n!==void 0)return n}}}function uw(t){let e=i=>Array.isArray(i)&&i.every(a=>Number.isInteger(a)&&a>=0&&a<=255),n=i=>typeof i=="string"&&i.trim().length>0?i:void 0,r=i=>new TextDecoder("utf-8",{fatal:false}).decode(Uint8Array.from(i)),o=i=>{let a=JSON.stringify(i,(c,u)=>e(u)?`<bytes:${u.length}>`:u);return a===void 0?String(i):a},s=t.rawOutput;if(s!=null){let i=vr(s);if(!i)return n(Kn(s))??o(s);let a;if(e(i.output)&&i.output.length>0&&(a=n(r(i.output))),!a&&e(i.stdout)&&i.stdout.length>0&&(a=n(r(i.stdout))),!a){let p=vr(i.Result);a=n(i.output)??n(p?.output)??n(Kn(s));}let c=e(i.stderr)&&i.stderr.length>0?r(i.stderr):void 0;if(c!==void 0)if(a){let p=a.endsWith(`
87
87
  `)||a.endsWith("\r")?"":`
88
88
  `;a=`${a}${p}${c}`;}else a=n(c);if(a)return a;let u=n(i.summary)??n(Kn(t.content))??n(i.output_for_prompt);return u!==void 0?u:o(s)}if(t.content!==null&&t.content!==void 0)return Kn(t.content)??o(t.content);if(t.result!==null&&t.result!==void 0)return Kn(t.result)??o(t.result)}function a_(t){let e=vr(t.error),n=[t.message,t.errorMessage,e?.message,e?.detail,typeof t.error=="string"?t.error:void 0].find(r=>typeof r=="string"&&r.trim().length>0);return n?d_(n):"Grok CLI reported an error."}function d_(t){return (t.replace(dw,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function o_(t){return aw.test(t)}function lw(t){let e=vr(t.modelUsage);return e?Object.keys(e)[0]??null:null}function pw(t){let e=vr(t.usage);if(!e)return null;let n=Vn(e.cache_read_input_tokens);return {inputTokens:Vn(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Vn(e.output_tokens),costUsd:Vn(t.total_cost_usd)}}function _w(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`