@crewx/sdk 0.9.0-rc.206 → 0.9.0-rc.208
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-sync/continuation.d.ts +67 -0
- package/dist/app-sync/coordinator.d.ts +92 -0
- package/dist/app-sync/create-ledger.d.ts +27 -0
- package/dist/app-sync/index.d.ts +9 -0
- package/dist/app-sync/index.js +390 -0
- package/dist/app-sync/scope.d.ts +35 -0
- package/dist/app-sync/session-fence.d.ts +26 -0
- package/dist/app-sync/sqlite-store.d.ts +237 -0
- package/dist/app-sync/types.d.ts +855 -0
- package/dist/esm/app-sync/index.js +390 -0
- package/dist/esm/index.js +319 -306
- package/dist/esm/plugins/index.js +150 -137
- package/dist/esm/publish/index.js +2 -2
- package/dist/esm/repository/index.js +210 -197
- package/dist/esm/skills/index.js +2 -2
- package/dist/index.js +310 -297
- package/dist/migrations/0050_rapid_black_cat.sql +89 -0
- package/dist/migrations/0051_lying_sinister_six.sql +1 -0
- package/dist/migrations/0052_lying_gambit.sql +33 -0
- package/dist/migrations/0053_smart_shriek.sql +172 -0
- package/dist/migrations/0054_lying_surge.sql +63 -0
- package/dist/migrations/0055_curious_talkback.sql +92 -0
- package/dist/migrations/0056_stale_menace.sql +14 -0
- package/dist/migrations/meta/0050_snapshot.json +5717 -0
- package/dist/migrations/meta/0051_snapshot.json +5725 -0
- package/dist/migrations/meta/0052_snapshot.json +5930 -0
- package/dist/migrations/meta/0053_snapshot.json +6780 -0
- package/dist/migrations/meta/0054_snapshot.json +6784 -0
- package/dist/migrations/meta/0055_snapshot.json +6896 -0
- package/dist/migrations/meta/0056_snapshot.json +6971 -0
- package/dist/migrations/meta/_journal.json +49 -0
- package/dist/plugins/index.js +150 -137
- package/dist/provider/bridge.d.ts +3 -2
- package/dist/provider/cli/adapter.types.d.ts +8 -5
- package/dist/publish/index.js +2 -2
- package/dist/repository/index.js +206 -193
- package/dist/schema/app-sync.d.ts +2533 -0
- package/dist/schema/doc-create-dispatches.d.ts +101 -0
- package/dist/schema/doc-sync-links.d.ts +75 -0
- package/dist/schema/index.d.ts +2 -0
- package/dist/skills/index.js +2 -2
- package/package.json +8 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as Se from'path';import Se__default,{join,dirname,resolve}from'path';import {fileURLToPath}from'url';import*as Qc from'fs';import {existsSync,mkdirSync,writeFileSync,appendFileSync,lstatSync,readFileSync,statSync,realpathSync}from'fs';import*as Na from'os';import Na__default,{homedir,tmpdir}from'os';import {createHash,randomBytes,randomUUID}from'crypto';import {sqliteTable,text,integer,index,check,primaryKey,real,uniqueIndex,unique,foreignKey}from'drizzle-orm/sqlite-core';import {sql,and,eq,inArray,or as or$1,isNull,ne,desc,lt,asc,like,gte,isNotNull,notLike,getTableColumns}from'drizzle-orm';import {spawnSync,spawn,execFile}from'child_process';import'string_decoder';import {mkdtemp,open,rm as rm$1}from'fs/promises';var Dl=Object.defineProperty;var gn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var Pl=(t,e)=>{for(var n in e)Dl(t,n,{get:e[n],enumerable:true});};var $l,Hl,R,g=x(()=>{$l=()=>fileURLToPath(import.meta.url),Hl=()=>Se__default.dirname($l()),R=Hl();});var f,Ct=x(()=>{g();f=class extends Error{code;cause;constructor(e,n,r){super(n),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};});function Ia(t){if(t===":memory:")return t;let e=resolve(t),n=e,r=[];for(;!existsSync(n);){let s=dirname(n);if(s===n)return e;r.unshift(n.slice(s.length+1)),n=s;}let o=realpathSync(n);for(let s of r)o=join(o,s);return resolve(o)}function Vl(t,e){let n=Ia(t),r=Ia(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function Kt(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&Xl.some(e=>Vl(t,join(Na__default.homedir(),".crewx",e))))throw new Error(`${Jl}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var Jl,Xl,Ce,xt=x(()=>{g();Jl="[crewx] Refusing to open the real CrewX database from a test process";Xl=["crewx.db","logs.db"];Ce=class{resolveDbPath(){if(process.env.CREWX_TRACES_DB!==void 0)throw new Error(`CREWX_TRACES_DB is removed. Use CREWX_DB instead. (got: ${process.env.CREWX_TRACES_DB})`);let e=process.env.CREWX_DB||join(Na__default.homedir(),".crewx","crewx.db");return Kt(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};});function q(t,e={}){let n=Kt(t),r=gn("better-sqlite3"),{drizzle:o}=gn("drizzle-orm/better-sqlite3"),s=e.readOnly?new r(n,{readonly:true,fileMustExist:true}):new r(n);return e.readOnly||(s.exec("PRAGMA journal_mode = WAL"),s.exec(`PRAGMA journal_size_limit = ${Ql}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),sqlite:s,runRaw:(i,c=[])=>s.prepare(i).run(...c),close:()=>s.close()}}var Ql,zt=x(()=>{g();xt();Ql=32*1024*1024;});function mn(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function ep(t,e){if(e>0||!mn(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,s]of Object.entries(Zl))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function np(t,e,n){if(!mn(t,"__drizzle_migrations")||!mn(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(Se__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let c=tp[i.tag];if(!c)continue;let d=Se__default.join(e,`${i.tag}.sql`);if(!existsSync(d))continue;let u=readFileSync(d,"utf-8"),l=createHash("sha256").update(u).digest("hex");if(o.has(l))continue;let p=t.all("PRAGMA table_info(tasks)"),_=new Set(p.map(h=>h.name));for(let[h,m]of Object.entries(c))_.has(h)||(t.run(`ALTER TABLE tasks ADD COLUMN ${h} ${m}`),_.add(h));}}function Ca(t){let e=t.trim().replace(/;+\s*$/,"").trim(),n=e.match(/^ALTER\s+TABLE\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ADD\s+(?:COLUMN\s+)?[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(n)return {kind:"add-column",table:n[1],column:n[2]};let r=e.match(/^CREATE\s+(?:UNIQUE\s+)?INDEX(?:\s+IF\s+NOT\s+EXISTS)?\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ON\s+/i);if(r)return {kind:"create-index",name:r[1]};let o=e.match(/^DROP\s+INDEX\s+IF\s+EXISTS\s+[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(o)return {kind:"drop-index",name:o[1]}}function xa(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function rp(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(s=>s.name===n)}function op(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function Wr(t,e){return e.kind==="add-column"?rp(t,e.table,e.column):op(t,e.name)}function ba(t,e,n){let r=t;for(let o of xa(e)){let s=Ca(o);s?.kind==="add-column"&&Wr(r,s)||s?.kind==="create-index"&&Wr(r,s)||s?.kind==="drop-index"&&!Wr(r,s)||r.run(n.raw(o));}}function sp(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(Se__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let c=Se__default.join(e,`${i.tag}.sql`);if(!existsSync(c))continue;let d=readFileSync(c,"utf-8"),u=createHash("sha256").update(d).digest("hex");if(o.has(u))continue;let p=xa(d).map(Ca);if(p.some(h=>!h))continue;let _=p;_.some(h=>h.kind==="add-column")&&_.some(h=>Wr(t,h))&&(t.transaction(h=>{ba(h,d,n),h.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${i.when})`);},{behavior:"immediate"}),o.add(u),console.error(`[crewx] Reconciled additive migration ${i.tag} from existing schema objects.`));}}function ip(t,e){let{sql:n}=gn("drizzle-orm"),r=JSON.parse(readFileSync(Se__default.join(e,"meta/_journal.json"),"utf-8")),s=["0025_task_heartbeat","0025_thread_app_instance_ledger","0026_mcp_action_source","0027_ui_instance_active_unique"].map(i=>{let c=r.entries.find(u=>u.tag===i);if(!c)throw new Error(`Missing release/App compatibility migration: ${i}`);let d=readFileSync(Se__default.join(e,`${i}.sql`),"utf-8");return {entry:c,content:d,hash:createHash("sha256").update(d).digest("hex")}});t.transaction(i=>{let c=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(d=>d.hash));if(c.has(s[0].hash))for(let d of s.slice(1))c.has(d.hash)||(ba(i,d.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${d.hash}, ${d.entry.when})`),c.add(d.hash),console.error(`[crewx] Replayed release/App migration ${d.entry.tag} safely.`));},{behavior:"immediate"});}function up(t,e,n,r){let s=JSON.parse(readFileSync(Se__default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===ap);if(!s)return;let i=Se__default.join(e,`${s.tag}.sql`);if(!existsSync(i))return;let c=createHash("sha256").update(readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c))return;if(!mn(t,"tasks"))return {hash:c,affectedRows:0};let d=t.all("PRAGMA table_info(tasks)"),u=new Set(d.map(p=>p.name));if(!u.has("stop_requested_at")||!u.has("stop_requested_epoch"))return {hash:c,affectedRows:0};let l=t.get(n`
|
|
2
2
|
SELECT count(*) AS count
|
|
3
3
|
FROM tasks
|
|
4
4
|
WHERE status IN ('success', 'failed')
|
|
5
5
|
AND (stop_requested_at IS NOT NULL OR stop_requested_epoch IS NOT NULL)
|
|
6
|
-
`);return {hash:
|
|
6
|
+
`);return {hash:c,affectedRows:l?.count??0}}function lp(t,e,n,r){let s=JSON.parse(readFileSync(Se__default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===dp);if(!s)return;let i=Se__default.join(e,`${s.tag}.sql`);if(!existsSync(i))return;let c=createHash("sha256").update(readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c))return;if(!mn(t,"threads"))return {hash:c,markedPointers:0};if(!t.all("PRAGMA table_info(threads)").some(p=>p.name==="created_by_task_id"))return {hash:c,markedPointers:0};let u=mn(t,va)?`AND NOT EXISTS (
|
|
7
7
|
SELECT 1
|
|
8
|
-
FROM ${
|
|
8
|
+
FROM ${va} AS marked
|
|
9
9
|
WHERE marked.thread_id = current.id
|
|
10
10
|
AND marked.created_by_task_id = current.created_by_task_id
|
|
11
11
|
)`:"",l=t.get(`SELECT count(*) AS count
|
|
@@ -15,44 +15,57 @@ import*as ke from'path';import ke__default,{join,dirname,resolve}from'path';impo
|
|
|
15
15
|
SELECT 1
|
|
16
16
|
FROM sqlite_master
|
|
17
17
|
WHERE type = 'trigger'
|
|
18
|
-
AND name = '${
|
|
18
|
+
AND name = '${cp}'
|
|
19
19
|
)
|
|
20
|
-
${
|
|
20
|
+
${u}`);return {hash:c,markedPointers:l?.count??0}}function pp(t){let{migrate:e}=gn("drizzle-orm/better-sqlite3/migrator"),{sql:n}=gn("drizzle-orm"),r=[Se__default.join(R,"../migrations"),Se__default.join(R,"migrations"),Se__default.join(R,"../../../../drizzle/migrations"),Se__default.join(process.cwd(),"drizzle/migrations")],o=r.find(p=>existsSync(Se__default.join(p,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
21
21
|
${r.join(`
|
|
22
|
-
`)}`);let o=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Hl(t,i),o?.cnt&&(Gl(t,s),Wl(t,s,n),ql(t,s,n));let u=Jl(t,s,n,!!o?.cnt),d=Vl(t,s,n,!!o?.cnt);e(t,{migrationsFolder:s});let l=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let p=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${p} (${l} migration${l>1?"s":""} applied).`);}u&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===u.hash)&&console.error(`[crewx] Task stop-marker cleanup (${u.affectedRows} success/failed row(s) affected).`),d&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===d.hash)&&console.error(`[crewx] Thread creator pointer migration (${d.markedPointers} pointer(s) marked unverified).`);}function $e(t,e){ga.has(e)||(Xl(t),ga.add(e));}var ga,$l,Ul,jl,Kl,zl,_a,qt=v(()=>{_();ga=new Set,$l={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT",metadata:"TEXT"};Ul={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"},"0024_storage_metadata":{prompt:"TEXT",rendered_prompt:"TEXT",result:"TEXT",input_tokens:"INTEGER DEFAULT 0",output_tokens:"INTEGER DEFAULT 0",cost_usd:"REAL DEFAULT 0"},"0044_clammy_bruce_banner":{metadata:"TEXT"}};jl="0027_task_stop_scope_cleanup",Kl="0033_thread_creator_boundary_guard",zl="trg_threads_creator_late_fill_guard",_a="thread_creator_unverified";});var re,Cr=v(()=>{_();re=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),starred:integer("starred").notNull().default(0)});});var a,Wk,tp,se,un=v(()=>{_();a=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),actor_kind:text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:text("actor_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),pid_started_at:text("pid_started_at"),heartbeat_at:text("heartbeat_at"),stop_requested_at:text("stop_requested_at"),stop_requested_epoch:integer("stop_requested_epoch"),rendered_prompt:text("rendered_prompt"),security_key:text("security_key"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),cwd:text("cwd"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0),rating:text("rating",{enum:["up","down"]}),rated_at:text("rated_at"),workflow_run_id:text("workflow_run_id"),schedule_id:text("schedule_id")},t=>({log_storage_check:check("tasks_log_storage_ck",sql`${t.log_storage} IN ('blob', 'events')`),rating_check:check("tasks_rating_ck",sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:index("idx_tasks_status").on(t.status),idx_tasks_started_at:index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(sql`${t.rating} IS NOT NULL`)})),{security_key:Wk,...tp}=getTableColumns(a),se=tp;});var ht,Ea=v(()=>{_();un();ht=sqliteTable("task_provider_inputs",{task_id:text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),run_epoch:integer("run_epoch").notNull(),input:text("input").notNull(),key_wrap_skipped:integer("key_wrap_skipped").notNull().default(0),recorded_at:text("recorded_at").notNull()},t=>({pk:primaryKey({columns:[t.task_id,t.run_epoch]})}));});var dt,Sa=v(()=>{_();un();dt=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},t=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var dp,up,T,qn=v(()=>{_();Cr();dp="json_extract(metadata, '$.threadTitle.state')",up="json_extract(metadata, '$.threadTitle.priority')",T=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>re.id,{onDelete:"set null"}),created_by_kind:text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:text("created_by_id"),created_by_task_id:text("created_by_task_id"),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(t.workspace_id,sql.raw(dp)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(up))}));});var Oa=v(()=>{_();sqliteTable("thread_creator_unverified",{thread_id:text("thread_id").notNull(),created_by_task_id:text("created_by_task_id").notNull()},t=>({pk:primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var gp,va=v(()=>{_();un();gp=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>gp.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},t=>({idx_spans_task_id:index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var Na=v(()=>{_();un();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},t=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(t.timestamp)}));});var Ca=v(()=>{_();qn();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:unique().on(t.thread_id,t.seq)}));});var Pa=v(()=>{_();sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},t=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(t.partition_key)}));});var La=v(()=>{_();sqliteTable("request_log_daily",{day:text("day").notNull(),scope:text("scope").notNull(),ok:integer("ok").notNull(),client:integer("client").notNull(),server:integer("server").notNull(),p50_ms:integer("p50_ms"),p95_ms:integer("p95_ms"),computed_at:text("computed_at").notNull()},t=>({pk:primaryKey({columns:[t.day,t.scope]})}));});var Ha=v(()=>{_();sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var Ua=v(()=>{_();sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},t=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var Fa=v(()=>{_();sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},t=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(t.workspace_id,sql`${t.created_at} DESC`)})),sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},t=>({pk:primaryKey({columns:[t.notification_id,t.user_id]})}));});var Wa=v(()=>{_();sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var Ga=v(()=>{_();sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),app_id:text("app_id"),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),opened_by_json:text("opened_by_json"),agent_open_request_json:text("agent_open_request_json"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({idCheck:check("ui_instances_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${t.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:check("ui_instances_app_id_ck",sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${t.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:check("ui_instances_opened_by_json_ck",sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:check("ui_instances_created_at_ck",sql`${t.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(sql`${t.status} = 'active'`)}));});var Ka=v(()=>{_();sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),definition_id:text("definition_id"),definition_version:integer("definition_version"),definition_hash:text("definition_hash"),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},t=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${t.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${t.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${t.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
22
|
+
`)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ep(t,i),s?.cnt&&(ip(t,o),sp(t,o,n),np(t,o,n));let c=up(t,o,n,!!s?.cnt),d=lp(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let l=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let p=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${p} (${l} migration${l>1?"s":""} applied).`);}c&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c.hash)&&console.error(`[crewx] Task stop-marker cleanup (${c.affectedRows} success/failed row(s) affected).`),d&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===d.hash)&&console.error(`[crewx] Thread creator pointer migration (${d.markedPointers} pointer(s) marked unverified).`);}function We(t,e){Oa.has(e)||(pp(t),Oa.add(e));}var Oa,Zl,tp,ap,dp,cp,va,Jt=x(()=>{g();Oa=new Set,Zl={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT",metadata:"TEXT"};tp={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"},"0024_storage_metadata":{prompt:"TEXT",rendered_prompt:"TEXT",result:"TEXT",input_tokens:"INTEGER DEFAULT 0",output_tokens:"INTEGER DEFAULT 0",cost_usd:"REAL DEFAULT 0"},"0044_clammy_bruce_banner":{metadata:"TEXT"}};ap="0027_task_stop_scope_cleanup",dp="0033_thread_creator_boundary_guard",cp="trg_threads_creator_late_fill_guard",va="thread_creator_unverified";});var de,Gr=x(()=>{g();de=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),starred:integer("starred").notNull().default(0)});});var a,_y,mp,ce,kn=x(()=>{g();a=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),actor_kind:text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:text("actor_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),pid_started_at:text("pid_started_at"),heartbeat_at:text("heartbeat_at"),stop_requested_at:text("stop_requested_at"),stop_requested_epoch:integer("stop_requested_epoch"),rendered_prompt:text("rendered_prompt"),security_key:text("security_key"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),cwd:text("cwd"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0),rating:text("rating",{enum:["up","down"]}),rated_at:text("rated_at"),workflow_run_id:text("workflow_run_id"),schedule_id:text("schedule_id")},t=>({log_storage_check:check("tasks_log_storage_ck",sql`${t.log_storage} IN ('blob', 'events')`),rating_check:check("tasks_rating_ck",sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:index("idx_tasks_status").on(t.status),idx_tasks_started_at:index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(sql`${t.rating} IS NOT NULL`)})),{security_key:_y,...mp}=getTableColumns(a),ce=mp;});var Et,Ma=x(()=>{g();kn();Et=sqliteTable("task_provider_inputs",{task_id:text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),run_epoch:integer("run_epoch").notNull(),input:text("input").notNull(),key_wrap_skipped:integer("key_wrap_skipped").notNull().default(0),recorded_at:text("recorded_at").notNull()},t=>({pk:primaryKey({columns:[t.task_id,t.run_epoch]})}));});var _t,Ha=x(()=>{g();kn();_t=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},t=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var Sp,Ip,y,Xn=x(()=>{g();Gr();Sp="json_extract(metadata, '$.threadTitle.state')",Ip="json_extract(metadata, '$.threadTitle.priority')",y=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>de.id,{onDelete:"set null"}),created_by_kind:text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:text("created_by_id"),created_by_task_id:text("created_by_task_id"),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(t.workspace_id,sql.raw(Sp)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(Ip))}));});var Fa=x(()=>{g();sqliteTable("thread_creator_unverified",{thread_id:text("thread_id").notNull(),created_by_task_id:text("created_by_task_id").notNull()},t=>({pk:primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var Cp,Wa=x(()=>{g();kn();Cp=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Cp.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},t=>({idx_spans_task_id:index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var Ga=x(()=>{g();kn();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},t=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(t.timestamp)}));});var Ka=x(()=>{g();Xn();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:unique().on(t.thread_id,t.seq)}));});var Ja=x(()=>{g();sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},t=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(t.partition_key)}));});var Va=x(()=>{g();sqliteTable("request_log_daily",{day:text("day").notNull(),scope:text("scope").notNull(),ok:integer("ok").notNull(),client:integer("client").notNull(),server:integer("server").notNull(),p50_ms:integer("p50_ms"),p95_ms:integer("p95_ms"),computed_at:text("computed_at").notNull()},t=>({pk:primaryKey({columns:[t.day,t.scope]})}));});var Qa=x(()=>{g();sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var Za=x(()=>{g();sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},t=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var td=x(()=>{g();sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},t=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(t.workspace_id,sql`${t.created_at} DESC`)})),sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},t=>({pk:primaryKey({columns:[t.notification_id,t.user_id]})}));});var rd=x(()=>{g();sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var od=x(()=>{g();sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),app_id:text("app_id"),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),opened_by_json:text("opened_by_json"),agent_open_request_json:text("agent_open_request_json"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({idCheck:check("ui_instances_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${t.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:check("ui_instances_app_id_ck",sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${t.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:check("ui_instances_opened_by_json_ck",sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:check("ui_instances_created_at_ck",sql`${t.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(sql`${t.status} = 'active'`)}));});var id=x(()=>{g();sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),definition_id:text("definition_id"),definition_version:integer("definition_version"),definition_hash:text("definition_hash"),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},t=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${t.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${t.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${t.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
23
23
|
(${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
|
|
24
24
|
OR
|
|
25
25
|
(${t.status} = 'settled' AND ${t.after_revision} IS NOT NULL AND ${t.outcome} IS NOT NULL AND ${t.settled_at} IS NOT NULL)
|
|
26
|
-
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));});var
|
|
26
|
+
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));});var ad=x(()=>{g();sqliteTable("ui_instance_repins",{instance_id:text("instance_id").notNull(),from_version:integer("from_version").notNull(),from_hash:text("from_hash").notNull(),to_version:integer("to_version").notNull(),to_hash:text("to_hash").notNull(),from_revision:integer("from_revision").notNull(),to_revision:integer("to_revision"),status:text("status").notNull(),code:text("code"),attempts:integer("attempts").notNull().default(1),first_at:integer("first_at").notNull(),last_at:integer("last_at").notNull()},t=>({pk:primaryKey({columns:[t.instance_id,t.to_hash],name:"ui_instance_repins_pk"}),instanceIdCheck:check("ui_instance_repins_instance_id_ck",sql`length(${t.instance_id}) BETWEEN 5 AND 128 AND ${t.instance_id} GLOB 'uic_*'`),fromVersionCheck:check("ui_instance_repins_from_version_ck",sql`${t.from_version} >= 1`),toVersionCheck:check("ui_instance_repins_to_version_ck",sql`${t.to_version} >= 1`),fromHashCheck:check("ui_instance_repins_from_hash_ck",sql`length(${t.from_hash}) = 64 AND ${t.from_hash} NOT GLOB '*[^0-9a-f]*'`),toHashCheck:check("ui_instance_repins_to_hash_ck",sql`length(${t.to_hash}) = 64 AND ${t.to_hash} NOT GLOB '*[^0-9a-f]*'`),fromRevisionCheck:check("ui_instance_repins_from_revision_ck",sql`${t.from_revision} >= 0`),toRevisionCheck:check("ui_instance_repins_to_revision_ck",sql`${t.to_revision} IS NULL OR ${t.to_revision} >= 0`),statusCheck:check("ui_instance_repins_status_ck",sql`${t.status} IN ('applied', 'deferred', 'failed')`),attemptsCheck:check("ui_instance_repins_attempts_ck",sql`${t.attempts} >= 1`),datesCheck:check("ui_instance_repins_dates_ck",sql`${t.first_at} >= 0 AND ${t.last_at} >= ${t.first_at}`),resultCheck:check("ui_instance_repins_result_ck",sql`(
|
|
27
27
|
(${t.status} = 'applied' AND ${t.code} IS NULL
|
|
28
28
|
AND ${t.to_revision} = ${t.from_revision} + 1)
|
|
29
29
|
OR
|
|
30
30
|
(${t.status} IN ('deferred', 'failed') AND ${t.code} IS NOT NULL
|
|
31
31
|
AND ${t.to_revision} IS NULL)
|
|
32
|
-
)`)}));});var Va=v(()=>{_();sqliteTable("ui_definition_archive",{definition_hash:text("definition_hash").primaryKey().notNull(),definition_json:text("definition_json").notNull(),created_at:integer("created_at").notNull()},t=>({definitionHashCheck:check("ui_definition_archive_definition_hash_ck",sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:check("ui_definition_archive_definition_json_ck",sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:check("ui_definition_archive_created_at_ck",sql`${t.created_at} >= 0`)}));});var Ya,Qa=v(()=>{_();Ya=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},t=>({idCheck:check("projects_id_ck",sql`${t.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${t.stage_index} >= 1`)})),sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>Ya.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({idCheck:check("project_criteria_id_ck",sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>Ya.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},t=>({idCheck:check("project_events_id_ck",sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var to,no,D,ro=v(()=>{_();to=["THREAD_STATE","THREAD_PRIORITY"],no=["gray","blue","violet","green","amber","orange","red","pink"],D=sqliteTable("common_codes",{code_group:text("code_group").notNull(),code:text("code").notNull(),code_name:text("code_name"),color:text("color").notNull().default("gray"),sort_order:integer("sort_order").notNull(),workspace_id:text("workspace_id"),is_builtin:integer("is_builtin").notNull().default(0),is_archived:integer("is_archived").notNull().default(0),metadata:text("metadata"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({pk:primaryKey({columns:[t.code_group,t.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${t.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var Za,ed,td,nd,rd,j,B,U,sd=v(()=>{_();qn();Za=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],ed=["user","agent","system"],td=["auto","manual"],nd=["decision","judgment","issue","result","pivot"],rd=["queued","running","completed","failed"],j=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},t=>({typeCheck:check("thread_events_type_ck",sql`${t.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:check("thread_events_actor_type_ck",sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:check("thread_events_payload_json_ck",sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),B=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),request_id:text("request_id").notNull(),status:text("status").notNull(),detector_version:text("detector_version").notNull(),requested_at:text("requested_at").notNull(),started_at:text("started_at"),completed_at:text("completed_at"),error_code:text("error_code"),previous_auto_count:integer("previous_auto_count"),new_auto_count:integer("new_auto_count")},t=>({statusCheck:check("thread_highlight_runs_status_ck",sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:check("thread_highlight_runs_counts_ck",sql`(${t.previous_auto_count} IS NULL OR ${t.previous_auto_count} >= 0) AND (${t.new_auto_count} IS NULL OR ${t.new_auto_count} >= 0)`),threadRequestUnique:uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),U=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},t=>({sourceCheck:check("thread_highlights_source_ck",sql`${t.source} IN ('auto', 'manual')`),kindCheck:check("thread_highlights_kind_ck",sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:check("thread_highlights_status_ck",sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:check("thread_highlights_active_text_ck",sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:check("thread_highlights_covers_ck",sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:check("thread_highlights_auto_key_ck",sql`${t.source} = 'manual' OR (${t.source} = 'auto' AND ${t.source_task_id} IS NOT NULL AND ${t.detector_version} IS NOT NULL AND ${t.content_fingerprint} IS NOT NULL AND length(${t.source_task_id}) > 0 AND length(${t.detector_version}) > 0 AND length(${t.content_fingerprint}) > 0)`),threadStatusCreatedIndex:index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(sql`${t.source} = 'auto'`)}));});var id=v(()=>{_();sqliteTable("storage_metadata",{source_kind:text("source_kind").notNull(),source_id:text("source_id").notNull(),utc_ts:text("utc_ts"),bytes:integer("bytes").notNull()},t=>({pk:primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteTable("storage_metadata_state",{unit:text("unit").primaryKey().notNull(),cursor_rowid:integer("cursor_rowid").notNull().default(0),end_rowid:integer("end_rowid"),complete:integer("complete").notNull().default(0),updated_at:text("updated_at").notNull()});});var Ce,ad=v(()=>{_();Ce=sqliteTable("agent_send_history",{workspace_id:text("workspace_id").notNull(),actor_id:text("actor_id").notNull(),agent_id:text("agent_id").notNull(),last_accepted_at:text("last_accepted_at").notNull()},t=>({pk:primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var cd,ld=v(()=>{_();qn();Cr();sqliteTable("sidebar_states",{workspace_id:text("workspace_id").primaryKey().references(()=>re.id,{onDelete:"cascade"}),revision:integer("revision").notNull().default(0),rail_collapsed:integer("rail_collapsed").notNull().default(0),seeded_at:text("seeded_at").notNull()},t=>({railCollapsedCheck:check("sidebar_states_rail_collapsed_ck",sql`${t.rail_collapsed} IN (0, 1)`)})),cd=sqliteTable("sidebar_groups",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull().references(()=>re.id,{onDelete:"cascade"}),name:text("name").notNull(),color:text("color").notNull(),collapsed:integer("collapsed").notNull().default(0),position:integer("position").notNull()},t=>({colorCheck:check("sidebar_groups_color_ck",sql`${t.color} IN ('cyan', 'orange', 'purple', 'blue')`),collapsedCheck:check("sidebar_groups_collapsed_ck",sql`${t.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:index("idx_sidebar_groups_workspace_position").on(t.workspace_id,t.position)})),sqliteTable("sidebar_tabs",{workspace_id:text("workspace_id").notNull().references(()=>re.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),group_id:text("group_id").references(()=>cd.id,{onDelete:"set null"}),position:integer("position").notNull()},t=>({pk:primaryKey({columns:[t.workspace_id,t.thread_id]})})),sqliteTable("sidebar_closed_tabs",{id:integer("id").primaryKey({autoIncrement:true}),workspace_id:text("workspace_id").notNull().references(()=>re.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),group_id:text("group_id").references(()=>cd.id,{onDelete:"set null"}),position:integer("position").notNull(),closed_at:text("closed_at").notNull()},t=>({idxSidebarClosedTabsWorkspaceId:index("idx_sidebar_closed_tabs_workspace_id").on(t.workspace_id,t.id)})),sqliteTable("thread_reads",{workspace_id:text("workspace_id").notNull().references(()=>re.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),read_through_at:text("read_through_at").notNull()},t=>({pk:primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var pd=v(()=>{_();sqliteTable("schedule_runs",{id:text("id").primaryKey(),schedule_id:text("schedule_id").notNull(),workspace_id:text("workspace_id").notNull(),mode:text("mode").notNull(),trigger:text("trigger").notNull(),occurrence_key:text("occurrence_key"),task_id:text("task_id"),app_id:text("app_id"),schedule_name:text("schedule_name"),builtin_id:text("builtin_id"),command:text("command"),high_frequency:integer("high_frequency").notNull().default(0),status:text("status").notNull(),error_code:text("error_code"),exit_code:integer("exit_code"),signal:text("signal"),started_at:text("started_at").notNull(),finished_at:text("finished_at"),duration_ms:integer("duration_ms"),pid:integer("pid"),host_pid:integer("host_pid"),output_tail:text("output_tail"),output_bytes:integer("output_bytes"),output_truncated:integer("output_truncated").notNull().default(0)},t=>({idx_schedule_runs_workspace_started:index("idx_schedule_runs_workspace_started").on(t.workspace_id,sql`${t.started_at} DESC`),idx_schedule_runs_schedule_started:index("idx_schedule_runs_schedule_started").on(t.schedule_id,sql`${t.started_at} DESC`),idx_schedule_runs_task_id:index("idx_schedule_runs_task_id").on(t.task_id),idx_schedule_runs_running:index("idx_schedule_runs_running").on(t.workspace_id,t.started_at).where(sql`${t.status} = 'running'`)}));});var fd=v(()=>{_();sqliteTable("run_column_backfill",{name:text("name").primaryKey(),cursor:integer("cursor"),anchor_id:text("anchor_id"),completed_at:text("completed_at")});});var gd=v(()=>{_();sqliteTable("doc_sync_connect_requests",{request_id:text("request_id").primaryKey().notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),app_id:text("app_id").notNull(),ref:text("ref").notNull(),sent_hash:text("sent_hash").notNull(),created_at:integer("created_at").notNull()},t=>({requestIdCheck:check("doc_sync_connect_requests_request_id_ck",sql`length(${t.request_id}) = 36`),accountKeyCheck:check("doc_sync_connect_requests_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("doc_sync_connect_requests_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:check("doc_sync_connect_requests_app_id_ck",sql`length(${t.app_id}) BETWEEN 1 AND 128`),refCheck:check("doc_sync_connect_requests_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),sentHashCheck:check("doc_sync_connect_requests_sent_hash_ck",sql`length(${t.sent_hash}) = 71 AND substr(${t.sent_hash}, 1, 7) = 'sha256:' AND substr(${t.sent_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),createdAtCheck:check("doc_sync_connect_requests_created_at_ck",sql`${t.created_at} >= 0`),connectUnique:uniqueIndex("doc_sync_connect_requests_connect_uq").on(t.account_key,t.workspace_id,t.app_id,t.ref)}));});var hd=v(()=>{_();sqliteTable("doc_sync_links",{doc_id:text("doc_id").primaryKey().notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),app_id:text("app_id").notNull(),root_segments:text("root_segments").notNull(),ref:text("ref").notNull(),cloud_ref:text("cloud_ref").notNull(),origin:text("origin").notNull().default("own"),sync_state:text("sync_state").notNull().default("ok"),end_reason:text("end_reason"),file_state:text("file_state").notNull().default("present"),synced_revision:integer("synced_revision").notNull(),synced_hash:text("synced_hash").notNull(),synced_at:integer("synced_at").notNull(),file_dev_ino:text("file_dev_ino"),conflict_revision:integer("conflict_revision"),conflict_hash:text("conflict_hash"),conflict_at:integer("conflict_at"),remote_revision:integer("remote_revision"),remote_checked_at:integer("remote_checked_at"),published_revision:integer("published_revision"),bundle_sha256:text("bundle_sha256"),missing_since:integer("missing_since"),connected_at:integer("connected_at").notNull(),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({docIdCheck:check("doc_sync_links_doc_id_ck",sql`length(${t.doc_id}) BETWEEN 1 AND 128`),accountKeyCheck:check("doc_sync_links_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("doc_sync_links_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:check("doc_sync_links_app_id_ck",sql`length(${t.app_id}) BETWEEN 1 AND 128`),rootSegmentsCheck:check("doc_sync_links_root_segments_ck",sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),refCheck:check("doc_sync_links_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),cloudRefCheck:check("doc_sync_links_cloud_ref_ck",sql`length(${t.cloud_ref}) BETWEEN 1 AND 256`),originCheck:check("doc_sync_links_origin_ck",sql`${t.origin} IN ('own', 'received')`),syncStateCheck:check("doc_sync_links_sync_state_ck",sql`${t.sync_state} IN ('ok', 'conflict', 'ended')`),endReasonCheck:check("doc_sync_links_end_reason_ck",sql`${t.end_reason} IS NULL OR ${t.end_reason} IN ('disconnected', 'cloud_deleted')`),endedMatchesReasonCheck:check("doc_sync_links_ended_reason_ck",sql`(${t.sync_state} = 'ended') = (${t.end_reason} IS NOT NULL)`),fileStateCheck:check("doc_sync_links_file_state_ck",sql`${t.file_state} IN ('present', 'missing', 'root_unavailable')`),syncedRevisionCheck:check("doc_sync_links_synced_revision_ck",sql`${t.synced_revision} >= 0`),syncedHashCheck:check("doc_sync_links_synced_hash_ck",sql`length(${t.synced_hash}) = 71 AND substr(${t.synced_hash}, 1, 7) = 'sha256:' AND substr(${t.synced_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),connectedAtCheck:check("doc_sync_links_connected_at_ck",sql`${t.connected_at} >= 0`),createdAtCheck:check("doc_sync_links_created_at_ck",sql`${t.created_at} >= 0`),updatedAtCheck:check("doc_sync_links_updated_at_ck",sql`${t.updated_at} >= ${t.created_at}`),liveRefUnique:uniqueIndex("doc_sync_links_live_ref_uq").on(t.workspace_id,t.app_id,t.ref).where(sql`${t.sync_state} <> 'ended'`),accountStateIdx:index("doc_sync_links_account_state_idx").on(t.account_key,t.sync_state),workspaceAppIdx:index("doc_sync_links_workspace_app_idx").on(t.workspace_id,t.app_id)}));});var md=v(()=>{_();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 Vt=v(()=>{_();Cr();un();Ea();Sa();qn();Oa();va();Na();Ca();Pa();La();Ha();Ua();Fa();Wa();Ga();Ka();za();Va();Qa();ro();sd();id();ad();ld();pd();fd();gd();hd();md();});function Kn(t){return typeof t=="string"&&Ot.includes(t)}function kd(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 s=n.workflow;if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let o=s.exec_id;if(typeof o=="string"&&o!=="")return o}return null}var Ot,Gr=v(()=>{_();Ot=["workflow_card","workflow_ui_instance","workflow_run"];});var pn,po,Td,fo=v(()=>{_();pn={"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}},po=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"]),Td=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 go(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 df(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),zn;let e=go(t),n=af[e];if(n)return jr[n]??pn[n]??zn;if(jr[e])return jr[e];if(pn[e])return pn[e];if(po.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),zn;if(Td.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),zn;let r={...pn,...jr};for(let s of Object.keys(r))if(e.includes(s))return r[s];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),zn}function uf(t,e,n,r=0,s){let o=df(n),i=Math.min(r,t),d=(t-i)*o.input/1e6,c=i*o.cachedInput/1e6,l=e*o.output/1e6;return d+c+l}function yd(t,e,n,r,s,o){return t&&t>0?t:!e&&!n?0:uf(e??0,n??0,s,r??0)}var af,zn,jr,Kr=v(()=>{_();fo();fo();af={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"},zn={input:0,cachedInput:0,output:0},jr={};});function Sd(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"||!cf.includes(r))return null;let s=n.schedule_id;return typeof s=="string"&&s!==""?s:null}var cf,Id=v(()=>{_();cf=["cron","cron_manual"];});function ho(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function Ad(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function zr(t){return Number.isSafeInteger(t)&&t>0}function hf(t){let e=t.trim();if(!e)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(e);return n?.[1]??n?.[2]??e.split(/\s+/,1)[0]??""}function mf(t,e,n){let r=n==="win32"?t.toLowerCase():t,s=n==="win32"?e.toLowerCase():e;if(!s.trim())return false;if(s==="agy"){let o=hf(t).split(/[\\/]/).pop()??"",i=n==="win32"?o.toLowerCase():o;return i==="agy"||n==="win32"&&(i==="agy.exe"||i==="agy.cmd")}return r.includes(s)}function kf(t,e,n){return e.some(r=>mf(t,r,n))}function Tf(t,e){try{let n=spawnSync(t,e,{encoding:"utf8",timeout:_o,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:ho(n)}}}function yf(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:ho(c)});return}let s="",o="",i=false,u,d=setTimeout(()=>{try{r.kill();}catch{}u({status:null,stdout:s,stderr:o,error:new Error(`Command timed out after ${_o}ms`)});},_o);u=c=>{i||(i=true,clearTimeout(d),n(c));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",c=>{s+=String(c);}),r.stderr?.on("data",c=>{o+=String(c);}),r.once("error",c=>{u({status:null,stdout:s,stderr:o,error:c});}),r.once("close",c=>{u({status:c,stdout:s,stderr:o});});})}async function mo(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):yf(t,e)}function wf(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Ef(){return new Promise(t=>{setImmediate(t);})}function bt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return Ad(n)==="ESRCH"?"not_found":Ad(n)==="EPERM"?"alive":"unknown"}}function Rf(t,e){let n=bt(-t,e),r=bt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function bd(t,e,n,r){let s=Math.max(0,n),o=Math.max(1,r.pollIntervalMs??gf),i=Date.now()+s,u,d=s===0,c=r.sleep?Promise.resolve().then(()=>r.sleep(s)).then(()=>{},()=>{}):new Promise(l=>{u=setTimeout(l,s);});c.then(()=>{d=true;});try{for(await Ef();;){let l=Rf(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([c,wf(Math.min(o,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function Od(t,e,n,r,s){let o=await bd(t,e,s.hardConfirmMs??_f,{...s,sleep:void 0});return o==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:o==="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 vd(t,e,n={}){if(!zr(t))return "unknown";let r=n.platform??process.platform,s=r==="win32"?"powershell.exe":"ps",o=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 mo(s,o,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let u=i.stdout.trim();return u?kf(u,e,r)?"owned":"not_owned":"not_found"}function Of(t){let e=Sf.exec(t.trim());if(!e)return;let[,n="0",r="0",s="0",o="0"]=e;return ((Number(n)*24+Number(r))*60+Number(s))*60+Number(o)}function bf(t){let e=t.trim(),n=Af.exec(e);if(n){let[,s,o,i,u,d,c,l,p]=n;return Date.UTC(Number(s),Number(o)-1,Number(i),Number(u),Number(d),Number(c),Math.trunc(Number(l)/1e3))-Number(p)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function Nd(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 xd(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=bf(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let s=If.exec(r),o=s?Of(s[2]):void 0;return !s||o===void 0?{status:"unknown"}:s[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-o*1e3,groupId:Number(s[1])}}function Cd(t,e={}){if(!zr(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=Nd(t,n),o=e.runCommand??Tf,i;try{i=o(r,s);}catch{return {status:"unknown"}}return xd(i,n,Date.now())}async function Dd(t,e={}){if(!zr(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=Nd(t,n),o;try{o=await mo(r,s,e);}catch{return {status:"unknown"}}return xd(o,n,Date.now())}async function Nt(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",s=f=>({status:"failed",pid:t,method:r,error:f});if(!zr(t))return s("Invalid process ID");let o=e.kill??process.kill,i=bt(t,o);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return s("Unable to determine whether the process is alive");if(n==="win32"){let f;try{f=await mo("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){f={status:null,stdout:"",stderr:"",error:ho(m)};}let h=bt(t,o);return h==="not_found"?f.status===0&&!f.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:s(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let u,d=e.signal??"SIGKILL";try{o(-t,d);}catch(f){u=f;}if(d==="SIGKILL")return Od(t,o,u,r,e);if(await bd(t,o,e.graceMs??ff,e)==="not_found")return u?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{o(-t,"SIGKILL");}catch(f){l=f;}let p=await Od(t,o,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?u?p:{status:"terminated",pid:t,method:r}:s(p.error??"Process termination failed")}var _o,vt,ff,gf,_f,Jr,Sf,If,Af,Vr=v(()=>{_();_o=3e3,vt="SIGINT",ff=2e3,gf=25,_f=100;Jr=3e3,Sf=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,If=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,Af=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function Hd(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new g("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new g("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Md(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new g("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new g("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,s)=>Hd(r,s))}catch(r){throw r instanceof g?new g("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Ud(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new g("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new g("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new g("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function $d(t){return {taskId:t.id,source:Ud(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Pf(t){if(!Number.isInteger(t)||t<0)throw new g("VALIDATION","Task log tail limit must be a non-negative integer")}var Xr,qd=v(()=>{_();St();Ut();qt();Rt();Vt();Xr=class extends Ie{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?Ht(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=dirname(n);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(n))throw new g("NOT_FOUND","Database not found");let r=$(n);if(e)try{$e(r.db,n);}catch(s){throw r.close(),s}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 g("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((o,i)=>Hd(o,i));if(r.length===0){let o=this.getLogState(e);if(!o)throw new g("NOT_FOUND",`Task not found: ${e}`);return o}let s=this.openHandle(true);try{return s.db.transaction(i=>{let u=this.requireStateRowInTransaction(i,e),d=Ud(u);if(d==="blob"){let f=Md(e,u.logs);if(i.update(a).set({logs:JSON.stringify([...f,...r]),log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new g("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:u.last_log_seq}}let c=u.last_log_seq+1,l=u.last_log_seq+r.length;if(i.insert(dt).values(r.map((f,h)=>({task_id:e,seq:c+h,timestamp:f.timestamp,level:f.level,message:f.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 g("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to append task log",o)}finally{s.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?$d(r):void 0}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return Pf(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(s=>{let o=this.findStateRowInTransaction(s,e);if(!o)return;let i=$d(o);if(i.source==="blob"){let l=Md(e,o.logs).map((p,f)=>({...p,seq:f+1}));return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let u=s.select({seq:dt.seq,timestamp:dt.timestamp,level:dt.level,message:dt.message}).from(dt).where(eq(dt.task_id,e)).orderBy(n===void 0?asc(dt.seq):desc(dt.seq)),c=(n===void 0?u.all():u.limit(n).all()).map(({seq:l,timestamp:p,level:f,message:h})=>({seq:l,timestamp:p,level:f,message:h}));return n!==void 0&&c.reverse(),{...i,entries:c}},{behavior:"deferred"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read task logs",s)}finally{r.close();}}};});var Uf,Yr,Bd=v(()=>{_();St();Ut();qt();Rt();Vt();Uf=50,Yr=class extends Ie{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=$(e);try{return $e(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(Ce).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[Ce.workspace_id,Ce.actor_id,Ce.agent_id],set:{last_accepted_at:sql`MAX(${Ce.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:Ce.agent_id,lastAcceptedAt:Ce.last_accepted_at}).from(Ce).where(and(eq(Ce.workspace_id,e),eq(Ce.actor_id,n))).orderBy(desc(Ce.last_accepted_at),asc(Ce.agent_id)).limit(Uf).all()}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to find recent agent sends",s)}finally{r?.close();}}};});var Wd=v(()=>{_();});var qf,q,xt=v(()=>{_();qf=new Set(["ACCOUNT_SETTING_REQUIRED","MODEL_RETIRED","SUBSCRIPTION_REQUIRED"]),q=class extends Error{constructor(n,r,s){super(n);this.providerStr=r;this.name="ProviderError",this.code=s?.code??"UNKNOWN",this.kind=qf.has(this.code)?"config":s?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=s?.retryAfterMs,this.settingReason=s?.settingReason,this.replacementModel=s?.replacementModel,this.providerReason=s?.providerReason;}providerStr;code;kind;retryAfterMs;settingReason;replacementModel;providerReason;stdout};});var Xt,ko=v(()=>{_();xt();Xt=class extends q{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function Qr(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 ${Re}]`),e=Bf(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${Re}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,Re),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,Re),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,Re),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,Re),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,Re),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,Re),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,Re),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,Re),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Re),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${Re}${r}${Re}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${Re}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,Gd),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,Gd),e=e.replace(/[\r\n]{3,}/g,`
|
|
32
|
+
)`)}));});var cd=x(()=>{g();sqliteTable("ui_definition_archive",{definition_hash:text("definition_hash").primaryKey().notNull(),definition_json:text("definition_json").notNull(),created_at:integer("created_at").notNull()},t=>({definitionHashCheck:check("ui_definition_archive_definition_hash_ck",sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:check("ui_definition_archive_definition_json_ck",sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:check("ui_definition_archive_created_at_ck",sql`${t.created_at} >= 0`)}));});var ld,pd=x(()=>{g();ld=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},t=>({idCheck:check("projects_id_ck",sql`${t.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${t.stage_index} >= 1`)})),sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>ld.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({idCheck:check("project_criteria_id_ck",sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>ld.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},t=>({idCheck:check("project_events_id_ck",sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var gs,hs,M,ms=x(()=>{g();gs=["THREAD_STATE","THREAD_PRIORITY"],hs=["gray","blue","violet","green","amber","orange","red","pink"],M=sqliteTable("common_codes",{code_group:text("code_group").notNull(),code:text("code").notNull(),code_name:text("code_name"),color:text("color").notNull().default("gray"),sort_order:integer("sort_order").notNull(),workspace_id:text("workspace_id"),is_builtin:integer("is_builtin").notNull().default(0),is_archived:integer("is_archived").notNull().default(0),metadata:text("metadata"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({pk:primaryKey({columns:[t.code_group,t.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${t.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var _d,fd,gd,hd,md,X,K,B,kd=x(()=>{g();Xn();_d=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],fd=["user","agent","system"],gd=["auto","manual"],hd=["decision","judgment","issue","result","pivot"],md=["queued","running","completed","failed"],X=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},t=>({typeCheck:check("thread_events_type_ck",sql`${t.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:check("thread_events_actor_type_ck",sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:check("thread_events_payload_json_ck",sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),K=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),request_id:text("request_id").notNull(),status:text("status").notNull(),detector_version:text("detector_version").notNull(),requested_at:text("requested_at").notNull(),started_at:text("started_at"),completed_at:text("completed_at"),error_code:text("error_code"),previous_auto_count:integer("previous_auto_count"),new_auto_count:integer("new_auto_count")},t=>({statusCheck:check("thread_highlight_runs_status_ck",sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:check("thread_highlight_runs_counts_ck",sql`(${t.previous_auto_count} IS NULL OR ${t.previous_auto_count} >= 0) AND (${t.new_auto_count} IS NULL OR ${t.new_auto_count} >= 0)`),threadRequestUnique:uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),B=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},t=>({sourceCheck:check("thread_highlights_source_ck",sql`${t.source} IN ('auto', 'manual')`),kindCheck:check("thread_highlights_kind_ck",sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:check("thread_highlights_status_ck",sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:check("thread_highlights_active_text_ck",sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:check("thread_highlights_covers_ck",sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:check("thread_highlights_auto_key_ck",sql`${t.source} = 'manual' OR (${t.source} = 'auto' AND ${t.source_task_id} IS NOT NULL AND ${t.detector_version} IS NOT NULL AND ${t.content_fingerprint} IS NOT NULL AND length(${t.source_task_id}) > 0 AND length(${t.detector_version}) > 0 AND length(${t.content_fingerprint}) > 0)`),threadStatusCreatedIndex:index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(sql`${t.source} = 'auto'`)}));});var Td=x(()=>{g();sqliteTable("storage_metadata",{source_kind:text("source_kind").notNull(),source_id:text("source_id").notNull(),utc_ts:text("utc_ts"),bytes:integer("bytes").notNull()},t=>({pk:primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteTable("storage_metadata_state",{unit:text("unit").primaryKey().notNull(),cursor_rowid:integer("cursor_rowid").notNull().default(0),end_rowid:integer("end_rowid"),complete:integer("complete").notNull().default(0),updated_at:text("updated_at").notNull()});});var He,wd=x(()=>{g();He=sqliteTable("agent_send_history",{workspace_id:text("workspace_id").notNull(),actor_id:text("actor_id").notNull(),agent_id:text("agent_id").notNull(),last_accepted_at:text("last_accepted_at").notNull()},t=>({pk:primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var Sd,Id=x(()=>{g();Xn();Gr();sqliteTable("sidebar_states",{workspace_id:text("workspace_id").primaryKey().references(()=>de.id,{onDelete:"cascade"}),revision:integer("revision").notNull().default(0),rail_collapsed:integer("rail_collapsed").notNull().default(0),seeded_at:text("seeded_at").notNull()},t=>({railCollapsedCheck:check("sidebar_states_rail_collapsed_ck",sql`${t.rail_collapsed} IN (0, 1)`)})),Sd=sqliteTable("sidebar_groups",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull().references(()=>de.id,{onDelete:"cascade"}),name:text("name").notNull(),color:text("color").notNull(),collapsed:integer("collapsed").notNull().default(0),position:integer("position").notNull()},t=>({colorCheck:check("sidebar_groups_color_ck",sql`${t.color} IN ('cyan', 'orange', 'purple', 'blue')`),collapsedCheck:check("sidebar_groups_collapsed_ck",sql`${t.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:index("idx_sidebar_groups_workspace_position").on(t.workspace_id,t.position)})),sqliteTable("sidebar_tabs",{workspace_id:text("workspace_id").notNull().references(()=>de.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),group_id:text("group_id").references(()=>Sd.id,{onDelete:"set null"}),position:integer("position").notNull()},t=>({pk:primaryKey({columns:[t.workspace_id,t.thread_id]})})),sqliteTable("sidebar_closed_tabs",{id:integer("id").primaryKey({autoIncrement:true}),workspace_id:text("workspace_id").notNull().references(()=>de.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),group_id:text("group_id").references(()=>Sd.id,{onDelete:"set null"}),position:integer("position").notNull(),closed_at:text("closed_at").notNull()},t=>({idxSidebarClosedTabsWorkspaceId:index("idx_sidebar_closed_tabs_workspace_id").on(t.workspace_id,t.id)})),sqliteTable("thread_reads",{workspace_id:text("workspace_id").notNull().references(()=>de.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),read_through_at:text("read_through_at").notNull()},t=>({pk:primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var Ad=x(()=>{g();sqliteTable("schedule_runs",{id:text("id").primaryKey(),schedule_id:text("schedule_id").notNull(),workspace_id:text("workspace_id").notNull(),mode:text("mode").notNull(),trigger:text("trigger").notNull(),occurrence_key:text("occurrence_key"),task_id:text("task_id"),app_id:text("app_id"),schedule_name:text("schedule_name"),builtin_id:text("builtin_id"),command:text("command"),high_frequency:integer("high_frequency").notNull().default(0),status:text("status").notNull(),error_code:text("error_code"),exit_code:integer("exit_code"),signal:text("signal"),started_at:text("started_at").notNull(),finished_at:text("finished_at"),duration_ms:integer("duration_ms"),pid:integer("pid"),host_pid:integer("host_pid"),output_tail:text("output_tail"),output_bytes:integer("output_bytes"),output_truncated:integer("output_truncated").notNull().default(0)},t=>({idx_schedule_runs_workspace_started:index("idx_schedule_runs_workspace_started").on(t.workspace_id,sql`${t.started_at} DESC`),idx_schedule_runs_schedule_started:index("idx_schedule_runs_schedule_started").on(t.schedule_id,sql`${t.started_at} DESC`),idx_schedule_runs_task_id:index("idx_schedule_runs_task_id").on(t.task_id),idx_schedule_runs_running:index("idx_schedule_runs_running").on(t.workspace_id,t.started_at).where(sql`${t.status} = 'running'`)}));});var Nd=x(()=>{g();sqliteTable("run_column_backfill",{name:text("name").primaryKey(),cursor:integer("cursor"),anchor_id:text("anchor_id"),completed_at:text("completed_at")});});var Od=x(()=>{g();sqliteTable("doc_sync_connect_requests",{request_id:text("request_id").primaryKey().notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),app_id:text("app_id").notNull(),ref:text("ref").notNull(),sent_hash:text("sent_hash").notNull(),created_at:integer("created_at").notNull()},t=>({requestIdCheck:check("doc_sync_connect_requests_request_id_ck",sql`length(${t.request_id}) = 36`),accountKeyCheck:check("doc_sync_connect_requests_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("doc_sync_connect_requests_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:check("doc_sync_connect_requests_app_id_ck",sql`length(${t.app_id}) BETWEEN 1 AND 128`),refCheck:check("doc_sync_connect_requests_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),sentHashCheck:check("doc_sync_connect_requests_sent_hash_ck",sql`length(${t.sent_hash}) = 71 AND substr(${t.sent_hash}, 1, 7) = 'sha256:' AND substr(${t.sent_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),createdAtCheck:check("doc_sync_connect_requests_created_at_ck",sql`${t.created_at} >= 0`),connectUnique:uniqueIndex("doc_sync_connect_requests_connect_uq").on(t.account_key,t.workspace_id,t.app_id,t.ref)}));});var vd=x(()=>{g();sqliteTable("doc_sync_links",{doc_id:text("doc_id").primaryKey().notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),app_id:text("app_id").notNull(),root_segments:text("root_segments").notNull(),ref:text("ref").notNull(),cloud_ref:text("cloud_ref").notNull(),connection_kind:text("connection_kind").$type().notNull().default("document"),app_grant_id:text("app_grant_id"),app_grant_generation:integer("app_grant_generation"),app_scope_version:text("app_scope_version"),origin:text("origin").notNull().default("own"),sync_state:text("sync_state").notNull().default("ok"),end_reason:text("end_reason"),file_state:text("file_state").notNull().default("present"),synced_revision:integer("synced_revision").notNull(),synced_hash:text("synced_hash").notNull(),synced_at:integer("synced_at").notNull(),file_dev_ino:text("file_dev_ino"),conflict_revision:integer("conflict_revision"),conflict_hash:text("conflict_hash"),conflict_at:integer("conflict_at"),remote_revision:integer("remote_revision"),remote_checked_at:integer("remote_checked_at"),published_revision:integer("published_revision"),bundle_sha256:text("bundle_sha256"),missing_since:integer("missing_since"),connected_at:integer("connected_at").notNull(),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({docIdCheck:check("doc_sync_links_doc_id_ck",sql`length(${t.doc_id}) BETWEEN 1 AND 128`),accountKeyCheck:check("doc_sync_links_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("doc_sync_links_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:check("doc_sync_links_app_id_ck",sql`length(${t.app_id}) BETWEEN 1 AND 128`),rootSegmentsCheck:check("doc_sync_links_root_segments_ck",sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),refCheck:check("doc_sync_links_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),cloudRefCheck:check("doc_sync_links_cloud_ref_ck",sql`length(${t.cloud_ref}) BETWEEN 1 AND 256`),originCheck:check("doc_sync_links_origin_ck",sql`${t.origin} IN ('own', 'received')`),syncStateCheck:check("doc_sync_links_sync_state_ck",sql`${t.sync_state} IN ('ok', 'conflict', 'ended')`),endReasonCheck:check("doc_sync_links_end_reason_ck",sql`${t.end_reason} IS NULL OR ${t.end_reason} IN ('disconnected', 'cloud_deleted')`),endedMatchesReasonCheck:check("doc_sync_links_ended_reason_ck",sql`(${t.sync_state} = 'ended') = (${t.end_reason} IS NOT NULL)`),fileStateCheck:check("doc_sync_links_file_state_ck",sql`${t.file_state} IN ('present', 'missing', 'root_unavailable')`),syncedRevisionCheck:check("doc_sync_links_synced_revision_ck",sql`${t.synced_revision} >= 0`),syncedHashCheck:check("doc_sync_links_synced_hash_ck",sql`length(${t.synced_hash}) = 71 AND substr(${t.synced_hash}, 1, 7) = 'sha256:' AND substr(${t.synced_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),connectedAtCheck:check("doc_sync_links_connected_at_ck",sql`${t.connected_at} >= 0`),createdAtCheck:check("doc_sync_links_created_at_ck",sql`${t.created_at} >= 0`),updatedAtCheck:check("doc_sync_links_updated_at_ck",sql`${t.updated_at} >= ${t.created_at}`),liveRefUnique:uniqueIndex("doc_sync_links_live_ref_uq").on(t.workspace_id,t.app_id,t.ref).where(sql`${t.sync_state} <> 'ended'`),accountStateIdx:index("doc_sync_links_account_state_idx").on(t.account_key,t.sync_state),workspaceAppIdx:index("doc_sync_links_workspace_app_idx").on(t.workspace_id,t.app_id),connectionKindAccountIdx:index("doc_sync_links_connection_account_idx").on(t.account_key,t.connection_kind,t.app_id)}));});var Cd=x(()=>{g();sqliteTable("doc_create_dispatches",{dispatch_id:text("dispatch_id").primaryKey().notNull(),request_id:text("request_id").notNull(),account_key:text("account_key").notNull(),source:text("source").$type().notNull(),dispatched_at:integer("dispatched_at").notNull()},t=>({dispatchIdCheck:check("doc_create_dispatches_id_ck",sql`length(${t.dispatch_id}) BETWEEN 1 AND 128`),requestIdCheck:check("doc_create_dispatches_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),accountKeyCheck:check("doc_create_dispatches_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),sourceCheck:check("doc_create_dispatches_source_ck",sql`${t.source} IN ('human', 'app_create', 'app_reattach')`),timestampCheck:check("doc_create_dispatches_time_ck",sql`${t.dispatched_at} >= 0`),accountDispatchedIndex:index("doc_create_dispatches_account_time_idx").on(t.account_key,t.dispatched_at)}));});var wn,R_,xd=x(()=>{g();wn=sqliteTable("app_sync_bindings",{binding_id:text("binding_id").primaryKey().notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),app_id:text("app_id").notNull(),root_segments:text("root_segments").notNull(),grant_id:text("grant_id"),grant_generation:integer("grant_generation"),scope_version:text("scope_version"),status:text("status").notNull().default("local_only"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({bindingIdCheck:check("app_sync_bindings_binding_id_ck",sql`length(${t.binding_id}) BETWEEN 1 AND 128`),accountKeyCheck:check("app_sync_bindings_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("app_sync_bindings_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:check("app_sync_bindings_app_id_ck",sql`${t.app_id} = 'workout-log'`),rootSegmentsCheck:check("app_sync_bindings_root_segments_ck",sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),grantGenerationCheck:check("app_sync_bindings_generation_ck",sql`${t.grant_generation} IS NULL OR ${t.grant_generation} >= 1`),statusCheck:check("app_sync_bindings_status_ck",sql`${t.status} IN ('local_only', 'consent_required', 'checking', 'syncing', 'synced', 'partial', 'offline', 'revoked', 'unavailable', 'stopping')`),timestampsCheck:check("app_sync_bindings_timestamps_ck",sql`${t.updated_at} >= ${t.created_at}`),ownerAppUnique:uniqueIndex("app_sync_bindings_owner_app_uq").on(t.account_key,t.app_id)})),sqliteTable("app_sync_creation_jobs",{job_id:text("job_id").primaryKey().notNull(),binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),grant_id:text("grant_id").notNull(),grant_generation:integer("grant_generation").notNull(),ref:text("ref").notNull(),request_id:text("request_id").notNull(),fingerprint:text("fingerprint").notNull(),operation_kind:text("operation_kind").$type().notNull().default("create"),document_id:text("document_id"),status:text("status").notNull().default("waiting"),attempts:integer("attempts").notNull().default(0),next_attempt_at:integer("next_attempt_at").notNull().default(0),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({jobIdCheck:check("app_sync_creation_jobs_job_id_ck",sql`length(${t.job_id}) BETWEEN 1 AND 128`),accountKeyCheck:check("app_sync_creation_jobs_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),generationCheck:check("app_sync_creation_jobs_generation_ck",sql`${t.grant_generation} >= 1`),refCheck:check("app_sync_creation_jobs_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),documentIdCheck:check("app_sync_creation_jobs_document_id_ck",sql`${t.document_id} IS NULL OR length(${t.document_id}) BETWEEN 1 AND 128`),operationKindCheck:check("app_sync_creation_jobs_operation_kind_ck",sql`${t.operation_kind} IN ('create', 'reattach')`),reattachDocumentCheck:check("app_sync_creation_jobs_reattach_document_ck",sql`${t.operation_kind} != 'reattach' OR ${t.document_id} IS NOT NULL`),fingerprintCheck:check("app_sync_creation_jobs_fingerprint_ck",sql`length(${t.fingerprint}) = 71 AND substr(${t.fingerprint}, 1, 7) = 'sha256:' AND substr(${t.fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),statusCheck:check("app_sync_creation_jobs_status_ck",sql`${t.status} IN ('waiting', 'processing', 'completed', 'failed', 'conflict', 'blocked', 'invalidated', 'deleted')`),attemptsCheck:check("app_sync_creation_jobs_attempts_ck",sql`${t.attempts} >= 0`),timestampsCheck:check("app_sync_creation_jobs_timestamps_ck",sql`${t.updated_at} >= ${t.created_at}`),bindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[wn.binding_id]}).onDelete("cascade"),requestIdUnique:uniqueIndex("app_sync_creation_jobs_request_id_uq").on(t.request_id),activeFingerprintUnique:uniqueIndex("app_sync_creation_jobs_active_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.fingerprint,t.operation_kind).where(sql`${t.status} IN ('waiting', 'processing')`),runnableIndex:index("app_sync_creation_jobs_runnable_idx").on(t.binding_id,t.status,t.next_attempt_at),accountIndex:index("app_sync_creation_jobs_account_idx").on(t.account_key,t.status)})),sqliteTable("app_sync_results",{binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),ref:text("ref").notNull(),grant_id:text("grant_id").notNull(),grant_generation:integer("grant_generation").notNull(),source_fingerprint:text("source_fingerprint"),synced_fingerprint:text("synced_fingerprint"),document_id:text("document_id"),status:text("status").notNull(),error_code:text("error_code"),next_attempt_at:integer("next_attempt_at").notNull().default(0),attempts:integer("attempts").notNull().default(0),updated_at:integer("updated_at").notNull()},t=>({resultAccountCheck:check("app_sync_results_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resultRefCheck:check("app_sync_results_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),resultGenerationCheck:check("app_sync_results_generation_ck",sql`${t.grant_generation} >= 1`),resultStatusCheck:check("app_sync_results_status_ck",sql`${t.status} IN ('waiting', 'processing', 'synced', 'failed', 'conflict', 'blocked', 'excluded', 'deleted')`),resultAttemptsCheck:check("app_sync_results_attempts_ck",sql`${t.attempts} >= 0`),resultBindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[wn.binding_id]}).onDelete("cascade"),resultIdentityUnique:uniqueIndex("app_sync_results_binding_ref_uq").on(t.binding_id,t.ref),resultAccountIndex:index("app_sync_results_account_status_idx").on(t.account_key,t.status)})),sqliteTable("app_sync_control_requests",{request_id:text("request_id").primaryKey().notNull(),binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),app_id:text("app_id").notNull(),workspace_id:text("workspace_id").notNull(),root_fingerprint:text("root_fingerprint").notNull(),kind:text("kind").notNull(),state:text("state").notNull().default("pending"),grant_id:text("grant_id"),generation:integer("generation"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull(),resolved_at:integer("resolved_at"),resolution:text("resolution"),resolution_id:text("resolution_id")},t=>({requestIdCheck:check("app_sync_control_requests_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),requestAccountCheck:check("app_sync_control_requests_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),requestAppCheck:check("app_sync_control_requests_app_id_ck",sql`${t.app_id} = 'workout-log'`),requestWorkspaceCheck:check("app_sync_control_requests_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),rootFingerprintCheck:check("app_sync_control_requests_root_fingerprint_ck",sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),requestKindCheck:check("app_sync_control_requests_kind_ck",sql`${t.kind} IN ('connect', 'revoke')`),requestStateCheck:check("app_sync_control_requests_state_ck",sql`${t.state} IN ('pending', 'unknown', 'confirmed', 'failed')`),revokeGrantCheck:check("app_sync_control_requests_revoke_grant_ck",sql`${t.kind} != 'revoke' OR (${t.grant_id} IS NOT NULL AND ${t.generation} >= 1)`),requestResolutionCheck:check("app_sync_control_requests_resolution_ck",sql`(${t.state} IN ('pending', 'unknown') AND ${t.resolved_at} IS NULL AND ${t.resolution} IS NULL AND ${t.resolution_id} IS NULL) OR (${t.state} IN ('confirmed', 'failed') AND ${t.resolved_at} IS NOT NULL AND ${t.resolution} IN ('remote', 'human') AND length(${t.resolution_id}) BETWEEN 1 AND 128)`),generationCheck:check("app_sync_control_requests_generation_ck",sql`${t.generation} IS NULL OR ${t.generation} >= 1`),timestampsCheck:check("app_sync_control_requests_timestamps_ck",sql`${t.updated_at} >= ${t.created_at}`),bindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[wn.binding_id]}).onDelete("cascade"),unresolvedPerBinding:uniqueIndex("app_sync_control_requests_one_pending_uq").on(t.binding_id).where(sql`${t.state} IN ('pending', 'unknown')`),accountLookup:index("app_sync_control_requests_account_idx").on(t.account_key,t.app_id,t.state)})),sqliteTable("app_sync_deleted_refs",{account_key:text("account_key").notNull(),app_id:text("app_id").notNull(),ref_sha256:text("ref_sha256").notNull(),created_at:integer("created_at").notNull()},t=>({deletedAccountCheck:check("app_sync_deleted_refs_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),deletedAppCheck:check("app_sync_deleted_refs_app_id_ck",sql`${t.app_id} = 'workout-log'`),deletedHashCheck:check("app_sync_deleted_refs_hash_ck",sql`length(${t.ref_sha256}) = 64 AND ${t.ref_sha256} NOT GLOB '*[^0-9a-f]*'`),deletedIdentityUnique:uniqueIndex("app_sync_deleted_refs_identity_uq").on(t.account_key,t.app_id,t.ref_sha256)})),sqliteTable("app_sync_discovery_checkpoints",{binding_id:text("binding_id").primaryKey().notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),root_fingerprint:text("root_fingerprint").notNull(),grant_id:text("grant_id").notNull(),grant_generation:integer("grant_generation").notNull(),scope_version:text("scope_version").notNull(),last_cycle_started_at:integer("last_cycle_started_at"),cycle_started_at:integer("cycle_started_at"),docs_cursor:text("docs_cursor"),docs_complete:integer("docs_complete").notNull().default(0),deleted_cursor:text("deleted_cursor"),deleted_complete:integer("deleted_complete").notNull().default(0),updated_at:integer("updated_at").notNull()},t=>({checkpointAccountCheck:check("app_sync_discovery_checkpoints_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),checkpointRootCheck:check("app_sync_discovery_checkpoints_root_fingerprint_ck",sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),checkpointGenerationCheck:check("app_sync_discovery_checkpoints_generation_ck",sql`${t.grant_generation} >= 1`),checkpointScopeCheck:check("app_sync_discovery_checkpoints_scope_ck",sql`${t.scope_version} = 'workout-log.records.v1'`),checkpointDocsCompleteCheck:check("app_sync_discovery_checkpoints_docs_complete_ck",sql`${t.docs_complete} IN (0, 1)`),checkpointDeletedCompleteCheck:check("app_sync_discovery_checkpoints_deleted_complete_ck",sql`${t.deleted_complete} IN (0, 1)`),checkpointTimeCheck:check("app_sync_discovery_checkpoints_time_ck",sql`${t.updated_at} >= 0 AND (${t.last_cycle_started_at} IS NULL OR ${t.last_cycle_started_at} >= 0) AND (${t.cycle_started_at} IS NULL OR ${t.cycle_started_at} >= 0)`),checkpointBindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[wn.binding_id]}).onDelete("cascade"),checkpointAccountIndex:index("app_sync_discovery_checkpoints_account_idx").on(t.account_key,t.grant_id,t.grant_generation)})),sqliteTable("app_sync_pending_discoveries",{binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),grant_id:text("grant_id").notNull(),grant_generation:integer("grant_generation").notNull(),ref:text("ref").notNull(),doc_id:text("doc_id").notNull(),listed_revision:integer("listed_revision").notNull(),listed_fingerprint:text("listed_fingerprint").notNull(),app_grant_generation:integer("app_grant_generation").notNull(),needs_reattach:integer("needs_reattach").notNull().default(0),needs_reconcile:integer("needs_reconcile").notNull().default(0),status:text("status").notNull().default("waiting"),error_code:text("error_code"),attempts:integer("attempts").notNull().default(0),updated_at:integer("updated_at").notNull()},t=>({pendingAccountCheck:check("app_sync_pending_discoveries_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),pendingRefCheck:check("app_sync_pending_discoveries_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),pendingDocCheck:check("app_sync_pending_discoveries_doc_id_ck",sql`length(${t.doc_id}) BETWEEN 1 AND 128`),pendingRevisionCheck:check("app_sync_pending_discoveries_revision_ck",sql`${t.listed_revision} >= 0`),pendingFingerprintCheck:check("app_sync_pending_discoveries_fingerprint_ck",sql`length(${t.listed_fingerprint}) = 71 AND substr(${t.listed_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.listed_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),pendingGenerationCheck:check("app_sync_pending_discoveries_generation_ck",sql`${t.grant_generation} >= 1 AND ${t.app_grant_generation} >= 1`),pendingFlagsCheck:check("app_sync_pending_discoveries_flags_ck",sql`${t.needs_reattach} IN (0, 1) AND ${t.needs_reconcile} IN (0, 1)`),pendingStatusCheck:check("app_sync_pending_discoveries_status_ck",sql`${t.status} IN ('waiting', 'processing', 'failed', 'invalidated')`),pendingAttemptsCheck:check("app_sync_pending_discoveries_attempts_ck",sql`${t.attempts} >= 0 AND ${t.updated_at} >= 0`),pendingBindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[wn.binding_id]}).onDelete("cascade"),pendingIdentityUnique:uniqueIndex("app_sync_pending_discoveries_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref),pendingRunnableIdx:index("app_sync_pending_discoveries_runnable_idx").on(t.binding_id,t.grant_id,t.grant_generation,t.status,t.ref)})),R_=sqliteTable("app_sync_conflicts",{conflict_id:text("conflict_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(),grant_id:text("grant_id").notNull(),grant_generation:integer("grant_generation").notNull(),scope_version:text("scope_version").notNull(),ref:text("ref").notNull(),doc_id:text("doc_id").notNull(),local_version:text("local_version").notNull(),local_fingerprint:text("local_fingerprint").notNull(),baseline_revision:integer("baseline_revision"),baseline_fingerprint:text("baseline_fingerprint"),remote_revision:integer("remote_revision").notNull(),remote_fingerprint:text("remote_fingerprint").notNull(),needs_reattach:integer("needs_reattach").notNull().default(0),vault_handle:text("vault_handle"),preservation_status:text("preservation_status").notNull().default("pending"),state:text("state").notNull().default("open"),superseded_by:text("superseded_by"),resolution_request_id:text("resolution_request_id"),resolution_choice:text("resolution_choice"),cleanup_pending:integer("cleanup_pending").notNull().default(0),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({conflictIdCheck:check("app_sync_conflicts_id_ck",sql`length(${t.conflict_id}) BETWEEN 1 AND 128`),conflictAccountCheck:check("app_sync_conflicts_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),conflictRootCheck:check("app_sync_conflicts_root_fingerprint_ck",sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),conflictGenerationCheck:check("app_sync_conflicts_generation_ck",sql`${t.grant_generation} >= 1`),conflictScopeCheck:check("app_sync_conflicts_scope_ck",sql`${t.scope_version} = 'workout-log.records.v1'`),conflictRefCheck:check("app_sync_conflicts_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),conflictDocCheck:check("app_sync_conflicts_doc_id_ck",sql`length(${t.doc_id}) BETWEEN 1 AND 128`),conflictLocalVersionCheck:check("app_sync_conflicts_local_version_ck",sql`length(${t.local_version}) BETWEEN 1 AND 256 AND instr(${t.local_version}, '/') = 0 AND instr(${t.local_version}, char(92)) = 0`),conflictLocalFingerprintCheck:check("app_sync_conflicts_local_fingerprint_ck",sql`length(${t.local_fingerprint}) = 71 AND substr(${t.local_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.local_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),conflictBaselineCheck:check("app_sync_conflicts_baseline_ck",sql`(${t.baseline_revision} IS NULL) = (${t.baseline_fingerprint} IS NULL) AND (${t.baseline_revision} IS NULL OR (${t.baseline_revision} >= 0 AND length(${t.baseline_fingerprint}) = 71 AND substr(${t.baseline_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.baseline_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'))`),conflictRemoteCheck:check("app_sync_conflicts_remote_ck",sql`${t.remote_revision} >= 0 AND length(${t.remote_fingerprint}) = 71 AND substr(${t.remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),conflictFlagsCheck:check("app_sync_conflicts_flags_ck",sql`${t.needs_reattach} IN (0, 1) AND ${t.cleanup_pending} IN (0, 1)`),conflictHandleCheck:check("app_sync_conflicts_handle_ck",sql`${t.vault_handle} IS NULL OR (length(${t.vault_handle}) BETWEEN 1 AND 256 AND instr(${t.vault_handle}, '/') = 0 AND instr(${t.vault_handle}, char(92)) = 0)`),conflictPreservationCheck:check("app_sync_conflicts_preservation_ck",sql`${t.preservation_status} IN ('pending', 'ready', 'failed')`),conflictStateCheck:check("app_sync_conflicts_state_ck",sql`${t.state} IN ('open', 'resolving', 'superseded', 'resolved', 'kept_both', 'purging')`),conflictArchiveLifecycleCheck:check("app_sync_conflicts_archive_lifecycle_ck",sql`(
|
|
33
|
+
(${t.preservation_status} IN ('pending', 'failed') AND ${t.vault_handle} IS NULL
|
|
34
|
+
AND ${t.state} IN ('open', 'purging') AND ${t.cleanup_pending} = 0
|
|
35
|
+
AND (${t.state} = 'purging' OR ${t.superseded_by} IS NULL))
|
|
36
|
+
OR (${t.preservation_status} = 'ready' AND (
|
|
37
|
+
(${t.state} IN ('open', 'resolving', 'superseded') AND ${t.vault_handle} IS NOT NULL AND ${t.cleanup_pending} = 0)
|
|
38
|
+
OR (${t.state} = 'kept_both' AND ${t.resolution_request_id} IS NOT NULL
|
|
39
|
+
AND ${t.vault_handle} IS NOT NULL AND ${t.cleanup_pending} = 0)
|
|
40
|
+
OR (${t.state} = 'purging' AND ${t.cleanup_pending} = 0)
|
|
41
|
+
OR (${t.state} = 'resolved' AND ${t.resolution_request_id} IS NOT NULL
|
|
42
|
+
AND ((${t.cleanup_pending} = 1 AND ${t.vault_handle} IS NOT NULL)
|
|
43
|
+
OR (${t.cleanup_pending} = 0 AND ${t.vault_handle} IS NULL)))
|
|
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:[R_.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 N_(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),sr;let e=Os(t),n=A_[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 O_(t,e,n,r=0,o){let s=N_(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:O_(e??0,n??0,o,r??0)}var A_,sr,oo,so=x(()=>{g();Ns();Ns();A_={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"||!v_.includes(r))return null;let o=n.schedule_id;return typeof o=="string"&&o!==""?o:null}var v_,qd=x(()=>{g();v_=["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 L_(t){let e=t.trim();if(!e)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(e);return n?.[1]??n?.[2]??e.split(/\s+/,1)[0]??""}function M_(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=L_(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 $_(t,e,n){return e.some(r=>M_(t,r,n))}function H_(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 U_(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):U_(t,e)}function q_(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function F_(){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 B_(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??D_),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 F_();;){let l=B_(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([u,q_(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??P_,{...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?$_(c,e,r)?"owned":"not_owned":"not_found"}function K_(t){let e=W_.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 z_(t){let e=t.trim(),n=j_.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=z_(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let o=G_.exec(r),s=o?K_(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??H_,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??b_,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,b_,D_,P_,ao,W_,G_,j_,co=x(()=>{g();vs=3e3,Mt="SIGINT",b_=2e3,D_=25,P_=100;ao=3e3,W_=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,G_=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,j_=/^(\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 Z_(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 Z_(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 of,lo,rc=x(()=>{g();xt();zt();Jt();Ct();on();of=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(of).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 sf,G,Ht=x(()=>{g();sf=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=sf.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=df(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,`
|
|
33
46
|
|
|
34
|
-
`).trim(),
|
|
35
|
-
`,
|
|
36
|
-
`,
|
|
37
|
-
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>
|
|
38
|
-
`&&
|
|
47
|
+
`).trim(),af(e,1024)||void 0}function af(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 df(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=cf(t,s),c=i>=0?i:t.indexOf(`
|
|
48
|
+
`,s)>=0?t.indexOf(`
|
|
49
|
+
`,s):t.length;n+=t.slice(r,o.index),n+=`[HTTP BODY ${Oe}]`,r=c;}return n+t.slice(r)}function cf(t,e){let n=t[e];if(n==='"'||n==="'")return uf(t,e,n);if(n!=="{"&&n!=="[")return -1;let r=[],o,s=false;for(let i=e;i<t.length;i+=1){let c=t[i];if(o){s?s=false:c==="\\"?s=true:c===o&&(o=void 0);continue}if(c==='"'||c==="'"){o=c;continue}if(c==="{"||c==="["){r.push(c);continue}if(c!=="}"&&c!=="]")continue;let d=r.pop();if(c==="}"&&d!=="{"||c==="]"&&d!=="[")return -1;if(r.length===0)return i+1}return -1}function uf(t,e,n){let r=false;for(let o=e+1;o<t.length;o+=1){let s=t[o];if(r)r=false;else if(s==="\\")r=true;else if(s===n)return o+1}return -1}var Oe,sc,Ds=x(()=>{g();Oe="[REDACTED]",sc="[PATH]";});function Ls(t){if(!_o(t)||t.type!=="item.started"||!ac(t)||!ic(t))return false;let e=t.item;return !_o(e)||!ac(e)||!ic(e)||!Ps(e.id)?false:e.type==="web_search"?e.query===""&&_o(e.action)&&e.action.type==="other":e.type==="file_change"?e.status!=="in_progress"||!Array.isArray(e.changes)||e.changes.length===0?false:e.changes.every(n=>_o(n)&&Ps(n.path)&&Ps(n.kind)):false}function _o(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function dc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Ps(t){return typeof t=="string"&&t.trim().length>0}function ic(t){return !dc(t,"status")||t.status==="in_progress"}function ac(t){for(let e of ["error","errors","isError","is_error"])if(dc(t,e))return false;return true}var Ms=x(()=>{g();});function Rn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Sn(t){return typeof t=="string"&&t.trim().length>0}function $s(t){return typeof t=="string"?t.trim().length>0:Rn(t)?Sn(t.code)||Sn(t.message)||Sn(t.error)||Sn(t.reason):false}function ar(t){let e;try{e=JSON.parse(t);}catch{return}if(Rn(e))switch(e.event){case "init":return Rn(e.init)?{kind:"init",envelope:e,init:e.init}:void 0;case "step_update":{if(!Rn(e.step_update))return;let n=e.step_update;return !Sn(n.conversation_id)||!Number.isSafeInteger(n.step_index)||n.state!=="ACTIVE"&&n.state!=="DONE"&&!(n.state==="ERROR"&&n.step_type==="tool")||!Sn(n.step_type)?void 0:{kind:"step_update",envelope:e,step:n}}case "result":return Rn(e.result)?{kind:"result",envelope:e,result:e.result}:void 0;case "AGY_ERROR":{let n=$s(e)?e:e.error;return $s(n)?{kind:"agy_error",envelope:e,error:n}:void 0}default:return (e.status==="SUCCESS"||e.status==="ERROR")&&typeof e.response=="string"&&(typeof e.conversation_id=="string"||$s(e.error)||Rn(e.usage))?{kind:"legacy_result",envelope:e,result:e}:void 0}}function cc(t){return ar(t)!==void 0}function dr(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.trim())continue;let r=ar(n);r&&e.push(r);}return e}var Hs=x(()=>{g();});function lf(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let o=typeof r.type=="string"?r.type:"",s=e?yf[e]:void 0;return s?s(r,o):o?Object.values(lc).some(i=>i(r,o)):false}function kt(t,e){let n=t.split(`
|
|
50
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>lf(r,e))}function be(t){return typeof t=="object"&&t!==null}function uc(t,e){if(e==="assistant"||e==="user"){let n=t.message;return be(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||be(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?be(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function pf(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:uc(t,e)}function _f(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||be(t.error);if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return be(n)&&typeof n.type=="string"}return false}function ff(t,e){if(e==="step_start"||e==="step_finish")return typeof t.stepID=="string"||typeof t.sessionID=="string"||be(t.part);if(e==="text"||e==="tool_use")return be(t.part);if(e==="error"){let n=t.error;return be(n)&&typeof n.type=="string"&&typeof n.message=="string"}return e==="result"?typeof t.result=="string":false}function gf(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||be(t.part)||e==="result"&&typeof t.result=="string")}function hf(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?be(t.data):e==="result"?typeof t.result=="string":false}function mf(t,e){return e==="message"?typeof t.role=="string":e==="tool_use"?typeof t.tool_name=="string"||typeof t.tool_id=="string":e==="tool_result"?typeof t.tool_id=="string"||typeof t.status=="string":false}function kf(t,e){return e==="available_commands"?be(t.tools)||be(t.commands):e==="usage"?be(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||be(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var lc,yf,In=x(()=>{g();Ms();Hs();lc={claude:uc,codex:_f,opencode:ff,copilot:hf,gemini:mf},yf={...lc,claude:pf,opencode:gf,grok:kf,antigravity:t=>cc(JSON.stringify(t))};});function yt(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function Tt(t,e,n){let r=e.match(/@(\S+)/);return {timestamp:t,type:"agent_call",targetAgent:r?.[1]?.replace(/["']/g,""),toolInput:e,...typeof n=="string"&&n.length>0?{toolUseId:n}:{}}}var An=x(()=>{g();});function Ef(t){let e=Rf(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>If(s.value)),r=Sf(e);return {result:n.length===1&&n[0].index===r?Af(n[0].line.value):null,resultPreview:vf(e,n),hasReservedLine:n.length>0}}function et(t,e){let n=Ef(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function Rf(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
51
|
+
`&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
|
|
39
52
|
`?`\r
|
|
40
|
-
`:s;e.push({value:t.slice(n,r),separator:o}),r+=o.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function sg(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function og(t){return t.trimStart().startsWith(eg)}function ig(t){let e=t.trim();if(!e.startsWith(Yd)||!e.endsWith("]]"))return null;let n=e.slice(Yd.length,-2);if(!n)return null;try{return ag(JSON.parse(n))}catch{return null}}function ag(t){return dg(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function dg(t){if(!cg(t)||Object.keys(t).some(r=>!tg.has(r))||t.schema!==1||typeof t.isError!="boolean")return false;let e=Object.prototype.hasOwnProperty.call(t,"taskId"),n=Object.prototype.hasOwnProperty.call(t,"agentId");return e!==n?false:e?Qd(t.taskId)&&Qd(t.agentId):t.isError===true}function ug(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,s)=>n.has(s)?"":r.value+r.separator).join("")}function Qd(t){return typeof t=="string"&&t.trim().length>0}function cg(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Yd,eg,tg,mn=v(()=>{_();Yd="[[crewx:delegation-result ",eg="[[crewx:delegation-result",tg=new Set(["schema","taskId","agentId","isError"]);});function Ve(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return JSON.stringify(t??{});let e=t;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var kn=v(()=>{_();});var Zd,es,Io,ts=v(()=>{_();Zd=["none","minimal","low","medium","high","xhigh","max","ultra"],es={claude:["low","medium","high","xhigh","max"],codex:["none","minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]},Io={claude:{models:[{id:"claude-fable-5-1",name:"Claude Fable 5.1",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-5-5",name:"Claude Opus 5.5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-5-5",name:"Claude Sonnet 5.5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-5-5",name:"Claude Haiku 5.5",contextWindowTokens:1e6,tier:"speed"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5-1":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-6.1-terra",name:"GPT-6.1 Terra",contextWindowTokens:5e5,tier:"balanced"},{id:"gpt-6-sol",name:"GPT-6 Sol",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-6-luna",name:"GPT-6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-6-astra":{effort:["low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-6.1-sol":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-6.1-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"max"},"gpt-6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"max"},"gpt-6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"gpt-5.6-sol":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["low","medium","high","xhigh"],defaultEffort:"high"}},providerOptions:[]},opencode:{models:[],suggestedModels:[{id:"opencode-go/glm-5.3-flash",name:"GLM-5.3 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/qwen3.8-flash",name:"Qwen3.8 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/minimax-m3",name:"MiniMax M3",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"opencode-go/kimi-k2.7-code",name:"Kimi K2.7 Code",contextWindowTokens:262144,tier:"balanced",recommended:true}],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{},providerOptions:[]},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{},providerOptions:[]},antigravity:{models:[{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",tier:"balanced"},{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-5-5-medium",name:"Claude Sonnet 5.5",tier:"balanced"},{id:"claude-opus-5-5-medium",name:"Claude Opus 5.5",tier:"flagship"},{id:"gemini-4-argon",name:"Gemini 4 Argon",tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Antigravity's default permission handling. No extra permission flags are passed."},{id:"plan",name:"Plan",description:"Passes --mode plan. This turns on /plan; it is not a Claude-style permission mode."},{id:"acceptEdits",name:"Accept Edits",description:"Passes --mode accept-edits."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Passes --dangerously-skip-permissions so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"gemini-3.8-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.7-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.6-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.5-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.1-pro":{effort:["low","high"],defaultEffort:"high"},"claude-sonnet-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"claude-opus-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-4-argon":{effort:["low","medium","high"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:[]},"claude-opus-4-6-thinking":{effort:[]},"gpt-oss-120b":{effort:["medium"],defaultEffort:"medium"}},providerOptions:[]},grok:{models:[{id:"grok-4.7",name:"Grok 4.7",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship"},{id:"grok-4.5",name:"Grok 4.5",contextWindowTokens:5e5,tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Grok's default permission handling."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without changing the selected sandbox profile."},{id:"auto",name:"Auto",description:"Uses Grok automatic permission handling."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permission before tool execution."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Grok permission checks for tool execution."},{id:"plan",name:"Plan",description:"Keeps Grok in planning mode without applying changes."}],effort:["low","medium","high"],modelOverrides:{"grok-4.7":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.6":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.5":{effort:["low","medium","high"],defaultEffort:"high"}},providerOptions:[{key:"alwaysApprove",type:"boolean"},{key:"sandbox",type:"enum",values:["workspace","read-only","off"]}]}},Object.fromEntries(Object.entries(Io).map(([t,e])=>[t,e.models]));});function Ao(t){return pg[t]??t}function gg(t){return fg.get(t)??t}function Oo(t){if(!t)return {};let e=hg.get(t);return e?{...e}:{model:t}}function bo(t,e){return t==="antigravity"||t==="cli/antigravity"?Oo(e):e===void 0?{}:{model:gg(e)}}var lg,pg,fg,_g,hg,Yn=v(()=>{_();lg=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}],pg={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};fg=new Map(lg.map(({baseModelId:t,catalogModelId:e})=>[t,e]));_g=[{legacyId:"Gemini 3.7 Flash (High)",model:"gemini-3.7-flash",effort:"high"},{legacyId:"Gemini 3.7 Flash (Medium)",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"Gemini 3.7 Flash (Low)",model:"gemini-3.7-flash",effort:"low"},{legacyId:"Gemini 3.6 Flash (High)",model:"gemini-3.6-flash",effort:"high"},{legacyId:"Gemini 3.6 Flash (Medium)",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"Gemini 3.6 Flash (Low)",model:"gemini-3.6-flash",effort:"low"},{legacyId:"Gemini 3.5 Flash (Medium)",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"Gemini 3.5 Flash (High)",model:"gemini-3.5-flash",effort:"high"},{legacyId:"Gemini 3.5 Flash (Low)",model:"gemini-3.5-flash",effort:"low"},{legacyId:"Gemini 3.1 Pro (Low)",model:"gemini-3.1-pro",effort:"low"},{legacyId:"Gemini 3.1 Pro (High)",model:"gemini-3.1-pro",effort:"high"},{legacyId:"Claude Sonnet 4.6 (Thinking)",model:"claude-sonnet-4-6"},{legacyId:"Claude Opus 4.6 (Thinking)",model:"claude-opus-4-6-thinking"},{legacyId:"GPT-OSS 120B (Medium)",model:"gpt-oss-120b",effort:"medium"},{legacyId:"gemini-3.7-flash-high",model:"gemini-3.7-flash",effort:"high"},{legacyId:"gemini-3.7-flash-medium",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"gemini-3.7-flash-low",model:"gemini-3.7-flash",effort:"low"},{legacyId:"gemini-3.6-flash-high",model:"gemini-3.6-flash",effort:"high"},{legacyId:"gemini-3.6-flash-medium",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"gemini-3.6-flash-low",model:"gemini-3.6-flash",effort:"low"},{legacyId:"gemini-3.5-flash-high",model:"gemini-3.5-flash",effort:"high"},{legacyId:"gemini-3.5-flash-medium",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"gemini-3.5-flash-low",model:"gemini-3.5-flash",effort:"low"},{legacyId:"gemini-3.1-pro-high",model:"gemini-3.1-pro",effort:"high"},{legacyId:"gemini-3.1-pro-low",model:"gemini-3.1-pro",effort:"low"},{legacyId:"gpt-oss-120b-medium",model:"gpt-oss-120b",effort:"medium"}],hg=new Map(_g.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function kg(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function kt(t){return Qn(t).models}function Qn(t){let e=mg[t],n=Io[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??kg()}function Tn(t,e){let n=Qn(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=bo(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function vo(t){return Qn(t).modelOverrides}function eu(){return kt("claude")}function tu(){return kt("codex")}function nu(){return kt("copilot")}function ru(){return kt("antigravity")}var mg,Ct=v(()=>{_();ts();Kr();Yn();mg={};});function su(t){return yg[t]??t}var yg,ou=v(()=>{_();Ct();Yn();yg={auto:"default"};});function ns(t,e){return (es[t]??[]).includes(e)}function Dt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return wg.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function iu(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["--sandbox","read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function au(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["-c","sandbox_mode=read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function du(t){return !t||!ns("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function uu(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=su(t);return e.has(n)?["--permission-mode",n]:[]}function cu(t){return t?ns("claude",t)?["--effort",t]:[]:[]}function lu(t){return t==="default"?[]:t&&Eg.has(t)?["--permission-mode",t]:[]}function pu(t){return t===true?["--always-approve"]:[]}function fu(t,e=n=>console.warn(n)){return t===void 0?[]:t==="workspace"||t==="read-only"||t==="off"?["--sandbox",t]:(e(`[grok] Invalid sandbox value ${JSON.stringify(t)}; using workspace.`),["--sandbox","workspace"])}function gu(t){return t?ns("grok",t)?["--effort",t]:[]:[]}function _u(t){if(!t)return [];switch(Ao(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function hu(t){return t?ns("antigravity",t)?["--effort",t]:[]:[]}var wg,Eg,Zn=v(()=>{_();ou();Yn();ts();wg=new Set(Zd);Eg=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function Rg(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),s="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,o="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=s!==void 0?s:o??0;return {inputTokens:s!==void 0?e+s:e,outputTokens:n,cachedInputTokens:i}}function Sg(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),s=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,u="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=i!==void 0?i:u??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:s,cachedInputTokens:d}}function Ig(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),s=Number(n.output??0)+Number(n.reasoning??0),o=n.cache,i=o?Number(o.read??0):0;return {inputTokens:r+i,outputTokens:s,cachedInputTokens:i}}function mu(t){let e=new Map,n;for(let o of t.split(`
|
|
41
|
-
`))if(
|
|
42
|
-
`))if(r.trim())try{let
|
|
43
|
-
`).filter(
|
|
44
|
-
`).filter(n=>n.trim());for(let n of e.reverse())try{let r=JSON.parse(n);if(typeof r=="object"&&r!==null&&r.type==="result")return r}catch{}}function
|
|
45
|
-
`)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=
|
|
53
|
+
`:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function Sf(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function If(t){return t.trimStart().startsWith(Tf)}function Af(t){let e=t.trim();if(!e.startsWith(pc)||!e.endsWith("]]"))return null;let n=e.slice(pc.length,-2);if(!n)return null;try{return Nf(JSON.parse(n))}catch{return null}}function Nf(t){return Of(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Of(t){if(!Cf(t)||Object.keys(t).some(r=>!wf.has(r))||t.schema!==1||typeof t.isError!="boolean")return false;let e=Object.prototype.hasOwnProperty.call(t,"taskId"),n=Object.prototype.hasOwnProperty.call(t,"agentId");return e!==n?false:e?_c(t.taskId)&&_c(t.agentId):t.isError===true}function vf(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function _c(t){return typeof t=="string"&&t.trim().length>0}function Cf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var pc,Tf,wf,Nn=x(()=>{g();pc="[[crewx:delegation-result ",Tf="[[crewx:delegation-result",wf=new Set(["schema","taskId","agentId","isError"]);});function tt(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return JSON.stringify(t??{});let e=t;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var On=x(()=>{g();});var fc,fo,Us,go=x(()=>{g();fc=["none","minimal","low","medium","high","xhigh","max","ultra"],fo={claude:["low","medium","high","xhigh","max"],codex:["none","minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]},Us={claude:{models:[{id:"claude-fable-5-1",name:"Claude Fable 5.1",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-5-5",name:"Claude Opus 5.5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-5-5",name:"Claude Sonnet 5.5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-5-5",name:"Claude Haiku 5.5",contextWindowTokens:1e6,tier:"speed"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5-1":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-6.1-terra",name:"GPT-6.1 Terra",contextWindowTokens:5e5,tier:"balanced"},{id:"gpt-6-sol",name:"GPT-6 Sol",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-6-luna",name:"GPT-6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-6-astra":{effort:["low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-6.1-sol":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-6.1-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"max"},"gpt-6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"max"},"gpt-6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"gpt-5.6-sol":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["low","medium","high","xhigh"],defaultEffort:"high"}},providerOptions:[]},opencode:{models:[],suggestedModels:[{id:"opencode-go/glm-5.3-flash",name:"GLM-5.3 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/qwen3.8-flash",name:"Qwen3.8 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/minimax-m3",name:"MiniMax M3",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"opencode-go/kimi-k2.7-code",name:"Kimi K2.7 Code",contextWindowTokens:262144,tier:"balanced",recommended:true}],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{},providerOptions:[]},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{},providerOptions:[]},antigravity:{models:[{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",tier:"balanced"},{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-5-5-medium",name:"Claude Sonnet 5.5",tier:"balanced"},{id:"claude-opus-5-5-medium",name:"Claude Opus 5.5",tier:"flagship"},{id:"gemini-4-argon",name:"Gemini 4 Argon",tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Antigravity's default permission handling. No extra permission flags are passed."},{id:"plan",name:"Plan",description:"Passes --mode plan. This turns on /plan; it is not a Claude-style permission mode."},{id:"acceptEdits",name:"Accept Edits",description:"Passes --mode accept-edits."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Passes --dangerously-skip-permissions so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"gemini-3.8-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.7-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.6-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.5-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.1-pro":{effort:["low","high"],defaultEffort:"high"},"claude-sonnet-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"claude-opus-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-4-argon":{effort:["low","medium","high"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:[]},"claude-opus-4-6-thinking":{effort:[]},"gpt-oss-120b":{effort:["medium"],defaultEffort:"medium"}},providerOptions:[]},grok:{models:[{id:"grok-4.7",name:"Grok 4.7",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship"},{id:"grok-4.5",name:"Grok 4.5",contextWindowTokens:5e5,tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Grok's default permission handling."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without changing the selected sandbox profile."},{id:"auto",name:"Auto",description:"Uses Grok automatic permission handling."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permission before tool execution."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Grok permission checks for tool execution."},{id:"plan",name:"Plan",description:"Keeps Grok in planning mode without applying changes."}],effort:["low","medium","high"],modelOverrides:{"grok-4.7":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.6":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.5":{effort:["low","medium","high"],defaultEffort:"high"}},providerOptions:[{key:"alwaysApprove",type:"boolean"},{key:"sandbox",type:"enum",values:["workspace","read-only","off"]}]}},Object.fromEntries(Object.entries(Us).map(([t,e])=>[t,e.models]));});function qs(t){return bf[t]??t}function Pf(t){return Df.get(t)??t}function Fs(t){if(!t)return {};let e=Mf.get(t);return e?{...e}:{model:t}}function Bs(t,e){return t==="antigravity"||t==="cli/antigravity"?Fs(e):e===void 0?{}:{model:Pf(e)}}var xf,bf,Df,Lf,Mf,cr=x(()=>{g();xf=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}],bf={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Df=new Map(xf.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Lf=[{legacyId:"Gemini 3.7 Flash (High)",model:"gemini-3.7-flash",effort:"high"},{legacyId:"Gemini 3.7 Flash (Medium)",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"Gemini 3.7 Flash (Low)",model:"gemini-3.7-flash",effort:"low"},{legacyId:"Gemini 3.6 Flash (High)",model:"gemini-3.6-flash",effort:"high"},{legacyId:"Gemini 3.6 Flash (Medium)",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"Gemini 3.6 Flash (Low)",model:"gemini-3.6-flash",effort:"low"},{legacyId:"Gemini 3.5 Flash (Medium)",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"Gemini 3.5 Flash (High)",model:"gemini-3.5-flash",effort:"high"},{legacyId:"Gemini 3.5 Flash (Low)",model:"gemini-3.5-flash",effort:"low"},{legacyId:"Gemini 3.1 Pro (Low)",model:"gemini-3.1-pro",effort:"low"},{legacyId:"Gemini 3.1 Pro (High)",model:"gemini-3.1-pro",effort:"high"},{legacyId:"Claude Sonnet 4.6 (Thinking)",model:"claude-sonnet-4-6"},{legacyId:"Claude Opus 4.6 (Thinking)",model:"claude-opus-4-6-thinking"},{legacyId:"GPT-OSS 120B (Medium)",model:"gpt-oss-120b",effort:"medium"},{legacyId:"gemini-3.7-flash-high",model:"gemini-3.7-flash",effort:"high"},{legacyId:"gemini-3.7-flash-medium",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"gemini-3.7-flash-low",model:"gemini-3.7-flash",effort:"low"},{legacyId:"gemini-3.6-flash-high",model:"gemini-3.6-flash",effort:"high"},{legacyId:"gemini-3.6-flash-medium",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"gemini-3.6-flash-low",model:"gemini-3.6-flash",effort:"low"},{legacyId:"gemini-3.5-flash-high",model:"gemini-3.5-flash",effort:"high"},{legacyId:"gemini-3.5-flash-medium",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"gemini-3.5-flash-low",model:"gemini-3.5-flash",effort:"low"},{legacyId:"gemini-3.1-pro-high",model:"gemini-3.1-pro",effort:"high"},{legacyId:"gemini-3.1-pro-low",model:"gemini-3.1-pro",effort:"low"},{legacyId:"gpt-oss-120b-medium",model:"gpt-oss-120b",effort:"medium"}],Mf=new Map(Lf.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Hf(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function At(t){return ur(t).models}function ur(t){let e=$f[t],n=Us[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??Hf()}function vn(t,e){let n=ur(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Bs(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Ws(t){return ur(t).modelOverrides}function gc(){return At("claude")}function hc(){return At("codex")}function mc(){return At("copilot")}function kc(){return At("antigravity")}var $f,Ut=x(()=>{g();go();so();cr();$f={};});function yc(t){return qf[t]??t}var qf,Tc=x(()=>{g();Ut();cr();qf={auto:"default"};});function ho(t,e){return (fo[t]??[]).includes(e)}function qt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Ff.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function wc(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["--sandbox","read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function Ec(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["-c","sandbox_mode=read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function Rc(t){return !t||!ho("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Sc(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=yc(t);return e.has(n)?["--permission-mode",n]:[]}function Ic(t){return t?ho("claude",t)?["--effort",t]:[]:[]}function Ac(t){return t==="default"?[]:t&&Bf.has(t)?["--permission-mode",t]:[]}function Nc(t){return t===true?["--always-approve"]:[]}function Oc(t,e=n=>console.warn(n)){return t===void 0?[]:t==="workspace"||t==="read-only"||t==="off"?["--sandbox",t]:(e(`[grok] Invalid sandbox value ${JSON.stringify(t)}; using workspace.`),["--sandbox","workspace"])}function vc(t){return t?ho("grok",t)?["--effort",t]:[]:[]}function Cc(t){if(!t)return [];switch(qs(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function xc(t){return t?ho("antigravity",t)?["--effort",t]:[]:[]}var Ff,Bf,lr=x(()=>{g();Tc();cr();go();Ff=new Set(fc);Bf=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function Wf(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),o="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,s="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:i}}function Gf(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,c="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=i!==void 0?i:c??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:d}}function jf(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0)+Number(n.reasoning??0),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function bc(t){let e=new Map,n;for(let s of t.split(`
|
|
54
|
+
`))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let c=i.message,d=c?.id,u=c?.usage;if(typeof d!="string"||!u)continue;let l=Number(u.input_tokens??0),p=Number(u.cache_read_input_tokens??0);e.set(d,{inputTokens:l+p,cachedInputTokens:p});let _=c?.model;typeof _=="string"&&_&&(n=_);}catch{}if(e.size===0)return;let r=0,o=0;for(let s of e.values())r+=s.inputTokens,o+=s.cachedInputTokens;return {inputTokens:r,cachedInputTokens:o,model:n}}function Cn(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
|
|
55
|
+
`))if(r.trim())try{let o=JSON.parse(r),s=jf(o);if(s){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=s.inputTokens,n.outputTokens+=s.outputTokens,n.cachedInputTokens+=s.cachedInputTokens;continue}let i=Wf(o)??Gf(o);i&&(e=i);}catch{}return n||(e??void 0)}var pr=x(()=>{g();});function nt(t,e){if(typeof t!="object"||t===null||Array.isArray(t))return e;let n=t.timestamp;return typeof n!="string"||!Number.isFinite(Date.parse(n))?e:new Date(n).toISOString()}var an=x(()=>{g();});var mo,Dc=x(()=>{g();mo=Object.freeze({CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"});});function Pc(t){let e=t.split(`
|
|
56
|
+
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Lc(t){let e=t.split(`
|
|
57
|
+
`).filter(n=>n.trim());for(let n of e.reverse())try{let r=JSON.parse(n);if(typeof r=="object"&&r!==null&&r.type==="result")return r}catch{}}function xn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function qc(t){let e=xn(t.rate_limit_info);if(t.type==="rate_limit_event"&&e?.status==="rejected")return `Claude rate limit: ${typeof e.rateLimitType=="string"?e.rateLimitType:"unknown"} (status: rejected)`;if(t.error==="rate_limit"){let n=Yf(t);return n?`Claude rate limit: ${n}`:"Claude rate limit"}if(t.type==="result"&&t.is_error===true){let n=typeof t.result=="string"?t.result:"";if(Qf(n))return `Claude rate limit: ${n}`}}function Jf(t){for(let e of t.split(`
|
|
58
|
+
`)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=xn(JSON.parse(n));if(r?.type==="result"&&r.is_error===!0&&typeof r.result=="string"&&r.result.startsWith("Not logged in"))return r.result}catch{}}}}function Vf(t){let e=xn(t);if(e?.type!=="rate_limit_event")return;let n=xn(xn(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=Mc(n.five_hour),o=Mc(n.seven_day);if(!(!r&&!o))return {...r?{five_hour:r}:{},...o?{seven_day:o}:{}}}function Mc(t){let e=xn(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function $c(t){if(t?.is_error===true)return po(t.result)}function Xf(t){let e=qc(t);if(e)return e;if(t.type!=="result"||t.is_error!==true)return;let n=typeof t.result=="string"?t.result:"";if(n.trim())return n;let r=typeof t.subtype=="string"?t.subtype:"unknown",o=typeof t.terminal_reason=="string"?t.terminal_reason:"unknown";return `Claude ended without an answer (subtype=${r}, terminal_reason=${o})`}function Yf(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
46
59
|
|
|
47
|
-
`):""}function
|
|
48
|
-
`):i=JSON.stringify(
|
|
49
|
-
`);for(let r of e)if(r.trim())try{let
|
|
50
|
-
`).filter(
|
|
51
|
-
`).map(
|
|
52
|
-
`),
|
|
60
|
+
`):""}function Qf(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function Uc(t){return t.replace(/\s+/g," ").trim()}function Zf(t,e){let n=t?.description;if(typeof n!="string")return;let r=Uc(n);if(!r||r===Uc(e))return;if(r.length<=Hc)return r;let o=r.slice(0,Hc-1);return /[\uD800-\uDBFF]$/.test(o)&&(o=o.slice(0,-1)),`${o}\u2026`}function eg(t,e){let n=e.type;if(n==="text"){let r=String(e.text||"");return r?{timestamp:t,type:"text",content:r}:null}if(n==="thinking"){let r=typeof e.thinking=="string"?e.thinking.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="tool_use"){let r=String(e.name||""),o=e.id,s=e.input,i=tt(s);if(r==="Bash"&&yt(i))return Tt(t,i,o);let c=Zf(s,i);return {timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:i,...c?{toolTitle:c}:{}}}if(n==="tool_result"){let r=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(c=>c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
|
|
61
|
+
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...et(i,r)}}return null}var Kf,zf,ko,Hc,Gs=x(()=>{g();bs();Ht();Ds();In();An();Nn();On();lr();Ut();pr();an();Dc();Kf=new Set(["tool_progress"]),zf="cli/claude";ko={command:"claude",meta:{displayName:"Claude",models:gc(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=qt(e.model),s=e.effort??o,i=Sc(e.mode),c=Ic(s),d=r?["--model",r]:[],u=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let p=[...e.additionalArgs];return p.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...u,...i,...c,...d,...p],stdinMessage:t,env:mo}:{args:["--output-format","stream-json","--verbose",...u,...i,...c,...d,...p],stdinMessage:t,env:mo}}return {args:["-p","--output-format","stream-json","--verbose",...u,...i,...c,...d],stdinMessage:t,env:mo}},extractText(t){let e=Lc(t);if(e?.is_error===true){let o=ko.extractFailure(JSON.stringify(e));if(o)throw o;let s=typeof e.subtype=="string"?e.subtype:"unknown",i=typeof e.terminal_reason=="string"?e.terminal_reason:"unknown";throw new G($c(e)??`Claude ended without an answer (subtype=${s}, terminal_reason=${i})`,zf,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=Pc(t);if(n)return n;let r=t.trim();return kt(r,"claude")?"":r},extractPartialText(t){return Pc(t)},extractFailure(t){try{let e=JSON.parse(t),n=qc(e);if(n)return new sn(n)}catch{}return null},interpretExit(t,e,n){let r=Jf(n??"");if(r)return new G(`Claude is not logged in (exit ${t}): ${r}. Sign in to this account with the official "claude auth login".`,"cli/claude",{code:"AUTH_REQUIRED",kind:"config"});let o=$c(Lc(n??""));return o?new G(o,"cli/claude"):null},observeRateLimit(t){try{let e=JSON.parse(t);return Vf(e)}catch{return}},parseResultMeta(t){let e=t.split(`
|
|
62
|
+
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,i=s?{inputTokens:Number(s.input_tokens??0)+Number(s.cache_read_input_tokens??0),outputTokens:Number(s.output_tokens??0),cachedInputTokens:Number(s.cache_read_input_tokens??0),costUsd:Number(o.total_cost_usd??0)}:null,c=o.modelUsage,d=c?Object.keys(c)[0]??null:null;return {usage:i,model:d}}}catch{}let n=bc(t);return n?{usage:{inputTokens:n.inputTokens,outputTokens:0,cachedInputTokens:n.cachedInputTokens,costUsd:0},model:n.model??null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];let o=nt(n,e??new Date().toISOString()),s=Xf(n);if(s)return [{timestamp:o,type:"error",content:s,errorMessage:s}];let i=n.output_file,c=n.summary;if(r==="system"&&n.subtype==="task_notification"&&n.status==="completed"&&typeof i=="string"&&i.trim().length>0&&typeof c=="string"&&c.trim().length>0)return [{timestamp:o,type:"text",content:c}];if(r!=="assistant"&&r!=="user")return [];let u=n.message?.content;if(!Array.isArray(u))return [];let l=[];for(let p of u){let _=eg(o,p);_&&l.push(_);}return l},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Kf.has(r):!1}catch{return false}}};Hc=200;});function Fc(t){let e=t.split(`
|
|
63
|
+
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var tg,js,Ks=x(()=>{g();In();pr();An();On();Nn();Ut();go();an();tg=new Set(["interactive","plan","autopilot"]);js={command:"copilot",meta:{displayName:"Copilot",models:mc()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&tg.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(fo.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=Fc(t);if(e)return e;let n=t.trim();return kt(n,"copilot")?"":n},extractPartialText(t){return Fc(t)},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){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];if(!r.startsWith("tool.execution")&&!r.startsWith("assistant.")&&r!=="user.message")return [];let o=n.data;if(!o)return [];let s=nt(n,e??new Date().toISOString()),i=o.toolCallId;if(r==="tool.execution_start"){let c=String(o.toolName||""),d=o.arguments,u=tt(d);return (c==="bash"||c==="Bash")&&yt(u)?[Tt(s,u,i)]:[{timestamp:s,type:"tool_use",toolName:c,toolInput:u,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let c=o.error;if(c)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...et(String(c.message||""),true)}];let d=o.result,u=String(d?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...et(u,false)}]}if(r==="assistant.message"){let c=String(o.content||"");return c?[{timestamp:s,type:"text",content:c}]:[]}return []}};});function og(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 sg(t){return t[0]==="exec"?t.slice(1):t}function Bc(t){let e=t.split(`
|
|
64
|
+
`).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Ft(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Gc(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Ft(t.error)}function jc(t){let e=Ft(t.error)?t.error:void 0,n=[t.message,t.errorMessage,e?.message,e?.detail,typeof t.error=="string"?t.error:void 0];for(let r of n)if(typeof r=="string"&&r.trim())return r;return t.type==="turn.failed"?"Codex turn failed.":"Codex CLI reported an error."}function ig(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(Ft(n)&&Gc(n))return jc(n)}}function Wc(t,e,n,r){if(!n||t.type!=="command_execution"&&t.type!=="mcp_tool_call"||typeof t.id!="string"||!t.id.trim()||t.type==="mcp_tool_call"&&e==="item.started"&&(typeof t.server!="string"||typeof t.tool!="string"))return;let o=n.state.get("codex.pending");o||(o=new Map,n.state.set("codex.pending",o));let s=JSON.stringify([t.type,t.id]);if(e==="item.started"){let d=`codex:${JSON.stringify(t.id)}#${n.rowIndex}:${r}`,u=o.get(s)??[];return u.push(d),o.set(s,u),d}let i=o.get(s),c=i?.pop();return i?.length||o.delete(s),c}function ag(t,e,n){let r=e.type;if(r==="command_execution"){let o=String(e.command||"");return yt(o)?[Tt(t,o,n)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:o,...n?{toolUseId:n}:{}}]}return r==="mcp_tool_call"?typeof e.server!="string"||typeof e.tool!="string"?[]:[{timestamp:t,type:"tool_use",toolName:`${e.server}/${e.tool}`,toolInput:tt(e.arguments),...n?{toolUseId:n}:{}}]:[]}function dg(t,e,n){let r=e.type;if(r==="message"||r==="text"){let o=e.content;if(Array.isArray(o))for(let s of o){let i=cg(t,s);if(i)return i}if(typeof e.text=="string")return {timestamp:t,type:"text",content:e.text}}if(r==="agent_message"&&typeof e.text=="string")return {timestamp:t,type:"text",content:e.text};if(r==="reasoning"){let o=typeof e.text=="string"?e.text.trim():"";return o?{timestamp:t,type:"thinking",content:o}:null}if(r==="command_execution"){let o=String(e.aggregated_output||e.output||""),s=!!e.is_error;return {timestamp:t,type:"tool_result",...et(o,s),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let o=Ft(e.result)?e.result:void 0,i=(Array.isArray(o?.content)?o.content:[]).filter(d=>Ft(d)&&d.type==="text"&&typeof d.text=="string").map(d=>d.text).join(`
|
|
65
|
+
`),c=typeof e.error=="string"?e.error:Ft(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||c,isError:e.status==="failed"||e.status==="error"||e.is_error===true||e.error!=null,...n?{toolUseId:n}:{}}}if(r==="tool_use"){let o=String(e.name||e.tool_name||""),s=e.input,i=tt(s);return o==="Bash"&&yt(i)?Tt(t,i):{timestamp:t,type:"tool_use",toolName:o,toolInput:i}}if(r==="tool_result"){let o=!!e.is_error,s=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...et(s,o)}}if(r==="web_search"){let o=e.action,s;if(o?.type==="search"){let i=o.queries;s=String(o.query||"")||(i?.length?i.join(", "):"")||String(e.query||"");}else s=e.query?"open: "+String(e.query):"";return !s&&!(Ft(o)&&o.type==="other"&&e.query==="")?null:{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:s}}if(r==="file_change"){let o=e.changes;if(!Array.isArray(o)||o.length===0)return null;let s=o.map(c=>String(c.path||"")).filter(Boolean);if(s.length===0)return null;let i=s.length===1?s[0]:`${s.slice(0,2).join(", ")}${s.length>2?` (+${s.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:i}}return null}function cg(t,e){let n=e.type;if(n==="text")return {timestamp:t,type:"text",content:String(e.text||"")};if(n==="tool_use"){let r=String(e.name||""),o=e.input,s=tt(o);return r==="Bash"&&yt(s)?Tt(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var ng,rg,zs,Js=x(()=>{g();Ht();In();pr();An();On();Ms();Nn();lr();Ut();an();ng=new Set(["turn.started","turn.completed","item.updated"]),rg="cli/codex";zs={command:"codex",meta:{displayName:"Codex",models:hc(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=qt(e.model),s=e.effort??o,i=e.resumeSessionId?Ec(e.mode):wc(e.mode),c=Rc(s),d=r?["-m",r]:[],u=sg(e.additionalArgs??[]),p=u.includes("--json")||u.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...p,...i,...c,...d,...u,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...p,...i,...c,...d,...u],stdinMessage:t}},extractText(t){let e=ig(t);if(e)throw new G(e,rg);let n=Bc(t);if(n)return n;let r=t.trim();return kt(r,"codex")?"":r},extractPartialText(t){return Bc(t)},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;try{JSON.parse(t),s=[t];}catch{s=og(t),s.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,c]of s.entries()){let d;try{d=JSON.parse(c);}catch{continue}if(!Ft(d))continue;let u=d.type;if(!u)continue;let l=nt(d,r);if(Gc(d)){let _=jc(d);o.push({timestamp:l,type:"error",content:_,errorMessage:_});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||Ls(d))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let p=d.item;if(p){if(u==="item.started"){o.push(...ag(l,p,Wc(p,u,n,i)));continue}if(u==="item.completed"){let _=dg(l,p,Wc(p,u,n,i));_&&o.push(_);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?ng.has(r):!1}catch{return false}}};});function ze(t,e=240){if(typeof t!="string")return;let n=t.split(/\r?\n/).map(r=>r.trim()).find(r=>r&&!/^at\s+/.test(r));if(n)return n.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").replace(/(^|[\s"'(=])((?:[A-Za-z]:[\\/]|\/)(?:[^\s"'`()\[\]{}]+[\\/])*[^\s"'`()\[\]{}]+)/g,"$1[path]").slice(0,e).trim()}function _r(t){let e=ze(t);if(e)return ze(e.replace(/^Upstream request failed:\s*/i,""),200)}var Kc=x(()=>{g();});var zc=x(()=>{g();});function lg(t){let e=t.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!e)return null;let n=Number(e[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function pg(){return new Promise(t=>{let e=false,n,r=o=>{e||(e=true,n&&clearTimeout(n),t(o));};n=setTimeout(()=>r(null),Jc),n.unref();try{execFile("chcp.com",[],{encoding:"ascii",timeout:Jc,windowsHide:!0},(s,i)=>{if(s){r(null);return}r(lg(String(i)));}).once("error",()=>r(null));}catch{r(null);}})}function _g(){return process.platform!=="win32"?Promise.resolve(null):(yo||(yo=pg(),yo.then(t=>{},()=>{})),yo)}function fg(){process.platform==="win32"&&_g();}var Jc,yo,Xc=x(()=>{g();Jc=1e3;fg();});function hg(t,e){let n={};for(let[r,o]of Object.entries(t))o!==void 0&&(e.includes(r)||(n[r]=o));return n}function Vs(t){return hg(t,gg)}var gg,Xs=x(()=>{g();gg=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];});function To(){if(process.env.CREWX_HOME){let t=Se.resolve(process.env.CREWX_HOME);try{return Qc.realpathSync(t)}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return t;throw e}}return process.platform!=="win32"&&process.env.XDG_CONFIG_HOME?Se.join(process.env.XDG_CONFIG_HOME,"crewx"):Se.join(Na.homedir(),".crewx")}var Zc=x(()=>{g();});function gr(t=To()){let e=join(t,"opencode-xdg");return {XDG_DATA_HOME:join(e,"data"),XDG_STATE_HOME:join(e,"state")}}function hr(t=To()){return join(gr(t).XDG_DATA_HOME,"opencode")}async function Tg(){return (await import('better-sqlite3')).default}function wg(t){return join(t,"opencode.db")}function Eg(t){let e=t??process.env.XDG_DATA_HOME??join(homedir(),".local","share");return join(resolve(e),"opencode","opencode.db")}function tu(t,e){return !!t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)}function Rg(t){let e;try{e=typeof t=="string"?JSON.parse(t):t;}catch{return false}if(!e||typeof e!="object"||Array.isArray(e))return false;let n=e;return n.type==="key"&&typeof n.key=="string"&&!("refresh"in n)&&!("refresh_token"in n)&&!("expires"in n)&&!("expires_at"in n)&&!("expires_in"in n)}function Sg(t,e){if(!existsSync(e))return [];let n;try{return n=new t(e,{readonly:!0,fileMustExist:!0}),tu(n,"credential")?n.prepare(`
|
|
53
66
|
SELECT id, integration_id, label, value, connector_id, method_id, active, time_created, time_updated
|
|
54
67
|
FROM credential
|
|
55
|
-
`).all().filter(
|
|
68
|
+
`).all().filter(o=>o.integration_id!==null&&Rg(o.value)):[]}catch{return []}finally{n?.close();}}function eu(t,e){if(!existsSync(e))return false;let n;try{return n=new t(e,{readonly:!0,fileMustExist:!0}),tu(n,"credential")}catch{return false}finally{n?.close();}}function Ig(t){return new Promise((e,n)=>{execFile("opencode",["auth","list","--standalone"],{timeout:15e3,maxBuffer:1024*1024,encoding:"utf8",env:{...Vs(process.env),...t}},r=>{r?n(r):e();});})}function Ag(t,e,n){let r=new t(e,{fileMustExist:true});try{let o=r.prepare(`
|
|
56
69
|
INSERT INTO credential (
|
|
57
70
|
id, integration_id, label, value, connector_id, method_id, active, time_created, time_updated
|
|
58
71
|
) VALUES (
|
|
@@ -67,17 +80,17 @@ ${r.join(`
|
|
|
67
80
|
active = excluded.active,
|
|
68
81
|
time_created = excluded.time_created,
|
|
69
82
|
time_updated = excluded.time_updated
|
|
70
|
-
`);r.transaction(i=>{for(let
|
|
71
|
-
`);if(r===402||w_(d))return new q(`OpenCode subscription is required: ${s}`,De,{code:"SUBSCRIPTION_REQUIRED",kind:"config",providerReason:tr(s)});if(r===403&&(u==="RegionError"||u==="FreeTierError"))return new q(`OpenCode account settings are required: ${s}`,De,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:"access",providerReason:tr(s)});if(n==="provider.auth"||r===401||r===403)return new q(`OpenCode authentication is required: ${s}`,De,{code:"AUTH_REQUIRED",kind:"config"});if(r===410||u==="ModelDeprecated")return new q(`OpenCode model has been retired: ${s}`,De,{code:"MODEL_RETIRED",kind:"config",replacementModel:E_(o,e,t),providerReason:tr(s)});if(n==="provider.free-limit"||r===429){let c=R_(e);return new q(`OpenCode rate limit reached: ${s}`,De,{code:"RATE_LIMITED",kind:"transient",...c===void 0?{}:{retryAfterMs:c}})}if(n==="provider.no-route")return new q(`OpenCode model or variant unavailable: ${s}`,De,{code:"MODEL_UNAVAILABLE",kind:"config"});if(n==="provider.invalid-request"&&r===400){let c=[s,Wo(o)].filter(h=>h!==void 0),l=c.find(h=>/requires global regions/i.test(h)),p=c.find(h=>/trains on request data/i.test(h)),f=l?"region":p?"training_consent":void 0;if(f)return new q(`OpenCode account settings are required: ${s}`,De,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:f,providerReason:tr(l??p)})}return new q(`OpenCode error: ${s}`,De,{code:"PROVIDER_CRASHED",kind:"transient"})}function Ju(t){let n=(t&&ue(t.response)?t.response:void 0)?.body;if(ue(n))return n;if(typeof n=="string")try{let r=JSON.parse(n);return ue(r)?r:void 0}catch{return}}function Wo(t){let e=t&&ue(t.error)?t.error:void 0;return qe(e?.message)??qe(t?.message)}function w_(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 E_(t,e,n){let r=t&&ue(t.metadata)?t.metadata:void 0,s=typeof r?.replacement=="string"?r.replacement.trim():void 0;if(!s)return;let o=[r?.model,e?.model,n.model,n.modelID].find(d=>typeof d=="string"&&d.trim().length>0)?.trim(),i=o&&o.includes("/")?o.slice(0,o.indexOf("/")):"opencode-go",u=s.includes("/")?s:`${i}/${s}`;return /^[A-Za-z0-9._/-]{1,128}$/.test(u)?u:void 0}function R_(t){let e=t?.retryAfterMs;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;let r=(t&&ue(t.response)?t.response:void 0)?.body,s=typeof r=="string"?S_(r):ue(r)?r:void 0;if(s){let o=Go(s);if(o)return Gu(o.value,o.key==="retryafterms")}if(typeof r=="string"){let o=r.match(/retry[-_]after(?:\s*[:=]\s*|\s+)["']?([^"'\s,;}]+)/i);if(o?.[1])return Gu(o[1],false)}}function S_(t){try{let e=JSON.parse(t);return ue(e)?e:void 0}catch{return}}function Go(t){if(Array.isArray(t)){for(let e of t){let n=Go(e);if(n)return n}return}if(ue(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=Go(e);if(n)return n}}}function Gu(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 ju(t){let e=y_(t),n=[],r=null,s=0,o=[],i=[],u,d=false;for(let c of e.events){let l=typeof c.type=="string"?c.type:void 0;if(l){if(l==="text"){let p=ue(c.part)?c.part:void 0,f=typeof p?.text=="string"?p.text:void 0;f?.trim()&&n.push(f.trim());continue}if(l==="result"){typeof c.result=="string"&&(r=c.result);continue}if(l==="tool_use"){s++;continue}if(l==="error"){o.push(c),i.push(jo(c));continue}if(l==="step_finish"){d=true;let p=ue(c.part)?c.part:void 0;u=typeof p?.reason=="string"?p.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:s,errorEvents:o,errorMessages:i,terminalReason:u,hasTerminal:d}}function Vu(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function I_(){return new q("OpenCode returned no assistant output.",De,{code:"EMPTY_OUTPUT",kind:"transient"})}function A_(){return new q("OpenCode emitted malformed JSON output.",De,{code:"PROVIDER_CRASHED",kind:"transient"})}function O_(t,e){switch(Vu(t)){case "length":return new q("OpenCode stopped because the context window was exceeded.",De,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new q("OpenCode stopped because the content filter blocked the response.",De,{code:"UNKNOWN",kind:"permanent"});case "error":return new q(`${Ku} while generating a response.`,De,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var p_,De,Ku,f_,g_,__,Bu,ds,h_,Ko,zo=v(()=>{_();xt();xu();er();kn();Yt();Fu();Uo();p_=new Set(["step_start","step_finish"]),De="cli/opencode",Ku="OpenCode provider error",f_=240,g_="Follow the instructions provided on standard input.",__=3e5,h_={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};Ko={command:"opencode",prepare:T_,meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,s=r!==void 0?[...r]:["run"];Ye(s,"--format")||s.push("--format","json"),!Ye(s,"--standalone")&&!Ye(s,"--server")&&s.push("--standalone"),e.resumeSessionId&&!Ye(s,"-s")&&!Ye(s,"--session")&&s.push("-s",e.resumeSessionId);let{agent:o,autoApprove:i}=m_(e.mode);Ye(s,"--agent")||o!==void 0&&s.push("--agent",o),i&&!Ye(s,"--auto")&&s.push("--auto");let u=Ye(s,"--model")||Ye(s,"-m");if(e.model&&!u){let d=e.effort?`${e.model}#${e.effort}`:e.model;s.push("--model",d);}else e.effort&&!e.model&&!u&&console.debug("[opencode] ignoring effort because no model is configured");return s.push(g_),{args:s,stdinMessage:t,env:rr()}},extractText(t){let e=ju(t),n=e.errorEvents[0];if(n)throw Wu(n);let r=O_(e.terminalReason??"");if(r)throw r;let s=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(s!==void 0)return s;if(e.resultText?.trim())return e.resultText;if(e.malformed)throw A_();let o=Vu(e.terminalReason);if(e.hasTerminal&&o==="tool-calls"&&e.toolUseCount>0)return "";throw I_()},interpretExit(t,e,n=""){if(t===0)return null;let s=ju(n).errorEvents[0];return s?Wu(s):null},parseResultMeta(t){let e=yn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n=e??new Date().toISOString(),r=[],s;try{JSON.parse(t),s=[t];}catch{s=zu(t),s.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let o of s){let i;try{i=JSON.parse(o);}catch{continue}let u=Xe(i,n),d=i.type;if(d){if(d==="text"){let l=i.part?.text;l&&r.push({timestamp:u,type:"text",content:l});continue}if(d==="tool_use"){let c=i.part;if(!c)continue;let l=String(c.tool||""),p=String(c.callID||c.id||""),f=c.state,h=String(f?.status||""),m=f?.input,k=Ve(m);if(r.push({timestamp:u,type:"tool_use",toolName:l,toolUseId:p,toolInput:k}),h==="completed"&&f?.output!==void 0){let E=f.output,x=typeof E=="string"?E:JSON.stringify(E);r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:x,isError:false});}else h==="error"&&r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:String(f?.error||"tool error"),isError:true});continue}if(d==="error"){let c=jo(i);r.push({timestamp:u,type:"error",content:c,errorMessage:c});continue}}}return r},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?p_.has(r):!1}catch{return false}}};});var Xu=v(()=>{_();});function us(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function C_(t,e){let n=[];for(let r=0;r<t.length;r+=1){let s=t[r],o=[...e].find(i=>s===i||s.startsWith(`${i}=`));o?s===o&&r+1<t.length&&(r+=1):n.push(s);}return n}function D_(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],s=r.indexOf("="),o=s>0?r.slice(0,s):r;if(!N_.has(o)){e.push(r);continue}r===o&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function Fe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function P_(t,e){if(!(t?v_.has(t)||kt(Jo).some(o=>o.id===t):false)||!t)return e;let r=Tn(Jo,t),s=vo(Jo)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:s&&r.includes(s)?s:void 0:s}function Tt(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function Yo(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 Qo(t){return t.step.step_index}function te(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&Qr(e)?.slice(0,500).trim()||void 0}function L_(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&x_.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(o=>o.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 M_(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 Zu(t){let e=Fe(t)?t:void 0,n=e&&Fe(e.error)?e.error:void 0,r=e?te(e.code)??te(e.error_code)??te(n?.code)??te(n?.error_code):void 0,s=typeof t=="string"?te(t):e?te(e.message)??te(e.error)??te(e.reason)??te(n?.message)??te(n?.error)??te(n?.reason):void 0,o=L_(r,s),i=e?Tt(e.retry_after_ms)??Tt(e.retryAfterMs)??Tt(n?.retry_after_ms)??Tt(n?.retryAfterMs):void 0;return {code:o,kind:M_(o),message:s??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function ls(t){let e=Zu(t);return new q(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function Zo(t){return new q(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function $_(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=Xo))throw new q(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${Xo} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function Vo(){return new q("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 ps(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function fs(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 H_(t){let e=fs(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||ps(e.event)?.status!=="SUCCESS"||cs(t))return false;let r=new Map;for(let s of t){if(s.kind!=="step_update"||s.step.step_type!=="agent_response")continue;let o=Yo(s),i=Qo(s);!o||!Number.isSafeInteger(i)||r.set(JSON.stringify([o,i]),s.step);}if(r.size===0)return false;for(let s of r.values())if(s.state!=="DONE"||!Fe(s.usage)||Tt(s.usage.input_tokens)===void 0||Tt(s.usage.output_tokens)===void 0)return false;return true}function U_(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function q_(t,e){return Fe(t)&&Fe(e)?{...e,...t}:Fe(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&Fe(e)?{...e,message:t}:t??e}function F_(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let o of e){let i=Fe(o)?o:void 0,u=typeof o=="string"?te(o):te(i?.display_name)??te(i?.action);u&&!n.includes(u)&&n.length<5&&n.push(u.slice(0,80));}let r=Math.max(0,e.length-n.length),s=n.length>0?` (${n.join(", ")}${r>0?`, +${r} more`:""})`:"";return new q(`Permission denied: Antigravity blocked ${e.length} requested action${e.length===1?"":"s"}${s}.`,"cli/antigravity",{code:"UNKNOWN",kind:"permanent"})}function cs(t){let e=fs(t);if(!e)return;if(e.event.kind==="agy_error")return ls(e.event.error);let n=ps(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return F_(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return Zo("Antigravity returned a result with an unsupported status.");let r=n.error,s=q_(r==null||r===""?n:r,U_(t,e.index));return ls(s)}function ec(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function B_(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function W_(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function tc(t){let e=ec(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function G_(t){let e=Fe(t)?t:void 0,n=e&&Fe(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,s=(te(e?.type)??te(e?.code)??te(e?.error_type)??te(n?.type)??te(n?.code)??te(n?.error_type)??te(r)??"TOOL_ERROR").slice(0,60),o=Zu(t).message.slice(0,250);return tc({type:s,message:o})??"Antigravity reported a tool error."}function Yu(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function Qu(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var Jo,v_,N_,Xo,x_,ei,ti=v(()=>{_();xt();Xu();To();Yn();Ct();Zn();So();Jo="antigravity",v_=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),N_=new Set(["--conversation","--resume","--continue"]),Xo=18e4,x_=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"]);ei={command:"agy",maxInitialInputBytes:Xo,meta:{displayName:"Antigravity",models:ru(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=Vn(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){$_(t);let{model:r,effort:s}=Dt(e.model),o=Oo(r),i=o.model,u=e.effort??s??o.effort,d=P_(i,u),c=e.additionalArgs??[],l=D_(C_(c,new Set(["--input-format","--output-format"]))),p=i&&!us(c,"--model")?["--model",i]:[],f=us(c,"--effort")?[]:hu(d),h=us(c,"--mode")||us(c,"--dangerously-skip-permissions")?[]:_u(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,...f,...h,...m,...l],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
|
|
72
|
-
`,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=
|
|
73
|
-
`):void 0}if(
|
|
74
|
-
`)||
|
|
75
|
-
`;
|
|
76
|
-
`).flatMap(
|
|
77
|
-
`),
|
|
78
|
-
`).flatMap(
|
|
79
|
-
`).flatMap(
|
|
80
|
-
`)??"";if(!n.trim())return;let r=cc(t.provider);if(!r)return;let s;try{s=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let o=rh(s?.model,t.model),i=s?.usage;if(!i)return {stdout:n,adapter:r};let u=_s(i.inputTokens),d=_s(i.outputTokens),c=_s(i.cachedInputTokens),l=yd(_s(i.costUsd),u,d,c,o);return u!==0||d!==0||c!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:u,outputTokens:d,cachedInputTokens:c,costUsd:l,model:o,...i.complete===void 0?{}:{complete:i.complete}}}:{stdout:n,adapter:r}}var si=v(()=>{_();lc();Kr();});function ii(t){let e=new Set;for(let n of t)for(let r of sh.get(n)??[n])e.add(r);return [...e]}function ai(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.terminalReason;return typeof n=="string"&&oh.has(n)?n:void 0}catch{return}}function Qe(t){let e=ai(t.metadata);if(e)return e;if(t.status==="runner_lost")return "runner_lost";if(t.status==="stopped")return "user_stop";if(t.status==="failed"&&typeof t.error=="string"){if(oi.stopped.test(t.error))return "user_stop";if(oi.runnerLost.test(t.error))return "runner_lost"}}function Pe(t){switch(t.status){case "stopped":case "pending":case "running":case "paused":case "success":return t.status;case "completed":case "done":return "success";case "error":case "runner_lost":return "failed";case "failed":{let e=ai(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&oi.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function ih(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function ir(t){let e=Pe(t);return t.status==="runner_lost"&&ai(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...ih(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}var nn,sh,oi,oh,ar=v(()=>{_();nn=["success","completed","done","failed","error","stopped","runner_lost"],sh=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);oi={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},oh=new Set(["user_stop","runner_lost","launch_failed"]);});function di(t,e,n=1){let r=process.env[t];if(r===void 0||r==="")return e;let s=Number(r);return !Number.isFinite(s)||s<=0?e:Math.max(n,Math.trunc(s))}function ur(){return di("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function In(){return di("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function ks(){return di("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Sn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function ms(t){let e=typeof t=="object"&&t!==null&&"code"in t?String(t.code):t instanceof Error?t.name:typeof t;console.warn(`[crewx] task heartbeat write failed (${e}); execution continues`);}function ah(t){return t?{id:t.id,status:t.status,run_epoch:t.run_epoch,stop_requested_at:t.stop_requested_at,stop_requested_epoch:t.stop_requested_epoch,pid:t.pid,metadata:t.metadata,started_at:t.started_at,duration_ms:t.duration_ms}:null}function pc(t,e){return !!t.stop_requested_at&&Sn(t.stop_requested_epoch)===Sn(e)}function fc(t,e){let n=Sn(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let s=ah(t.getTask(e.taskId));return !s||s.status!=="running"||Sn(s.run_epoch)!==n?{accepted:false,row:s}:{accepted:true,row:s}}function mc(t,e){let n=dr.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),dr.delete(t),true)}function cr(t,e){let n=dr.get(t);return !n||e!==void 0&&n.runEpoch!==Sn(e)?false:mc(t,n)}function kc(t,e){let n=Sn(e.runEpoch);cr(e.taskId);let r=true,s=null;try{let c=fc(t,{...e,runEpoch:n});r=c.accepted,s=c.row;}catch(c){ms(c);}if(!r)return false;let o=ur(),i=Math.min(o,1e3),u=setInterval(()=>{let c=dr.get(e.taskId);if(!(!c||c.timer!==u))try{c.heartbeatElapsedMs+=i;let l=c.heartbeatElapsedMs>=o,p=fc(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){mc(e.taskId,c);return}l&&(c.heartbeatElapsedMs%=o,c.lastHeartbeatAt=Date.now()),p.row&&pc(p.row,n)&&!c.stopRequested&&(c.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(ms));}catch(l){ms(l);}},i),d={timer:u,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return dr.set(e.taskId,d),typeof u=="object"&&u!==null&&"unref"in u&&u.unref(),s&&pc(s,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(s)).catch(ms)),true}var gc,_c,hc,dr,lr=v(()=>{_();gc=1e4,_c=3e4,hc=18e5;dr=new Map;});function ys(t,e=Date.now(),n=gi){let r=t?Date.parse(t):Number.NaN,s=typeof e=="number"?e:Date.parse(e),o=mi(n,gi,0);return Number.isFinite(r)&&Number.isFinite(s)&&s-r>o?"forced":"cooperative"}function yi(t){let e=[],n=typeof t.pid=="number"&&t.pid>0?t.pid:void 0;n!==void 0&&e.push({pid:n,startedAt:t.pid_started_at});let r=Ec(t.metadata),s=r.ownership==="runner"&&typeof r.providerPid=="number"&&Number.isSafeInteger(r.providerPid)&&r.providerPid>0?r.providerPid:void 0;if(s!==void 0&&s!==n){let o=r.providerPidStartedAt;e.push({pid:s,startedAt:typeof o=="string"?o:null});}return e}async function wi(t,e={}){if(t.pid===process.pid||t.pid===process.ppid)return {verdict:"unproven",ownership:"not_owned",reason:"pid is this process or its parent"};let n=typeof t.startedAt=="string"?Date.parse(t.startedAt):Number.NaN,r=Number.isFinite(n),s=e.legacyStartBoundaryMs;if(!r&&s===void 0)return {verdict:"unproven",ownership:"unknown",reason:"no start time recorded"};let o=e.processControlOptions??{},i=e.processControl?.checkProcessOwnershipAsync??vd,u=e.processControl?.readProcessIdentityAsync??Dd,d;try{d=await i(t.pid,e.ownershipMarkers??uh,o);}catch{d="unknown";}let c;try{c=await u(t.pid,o);}catch{c={status:"unknown"};}if(c.status==="not_found")return {verdict:"unproven",ownership:"not_found",reason:"process is no longer running"};if(c.status!=="found")return {verdict:"unproven",ownership:"unknown",reason:"start time could not be read"};let l=new Date(c.startedAtMs).toISOString();if(r){if(Math.abs(c.startedAtMs-n)>Jr)return {verdict:"reused",reason:`started ${l}, not the recorded ${t.startedAt}`}}else return s!==void 0&&c.startedAtMs>s?{verdict:"reused",reason:`started ${l}, after the row's last heartbeat`}:{verdict:"unproven",ownership:"unknown",reason:"no start time recorded and it started before the row's last heartbeat"};return d!=="owned"?{verdict:"unproven",ownership:d,reason:"command line has no owned marker"}:c.groupId!==null&&c.groupId!==t.pid?{verdict:"unproven",ownership:"not_owned",reason:"pid does not lead its process group"}:{verdict:"owned"}}async function Ei(t,e={}){let n=await wi(t,e);return n.verdict==="owned"?"owned":n.verdict==="reused"?"not_owned":n.ownership}function mi(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function Ec(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function _h(t){if(!t)return;let e=Ec(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function Le(t,e){if(!t)return {status:"not_running",finalStatus:"not_running",...e?{pid:e}:{}};let n=typeof t.pid=="number"&&t.pid>0?t.pid:e;if(t.status==="stopped"){let r=_h(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function Ts(t,e,n="Process owner could not be verified"){let r=e??(t.pid&&t.pid>0?t.pid:void 0);return {status:"ownership_unverified",finalStatus:t.status,...r?{pid:r}:{},error:n}}function ee(t,e,n){let r=n??(t?.pid&&t.pid>0?t.pid:void 0);return {status:"failed",finalStatus:t?.status??null,...r?{pid:r}:{},error:e}}function fi(t,e){return ee(t,lh,e)}function hh(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=In():false}function mh(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function kh(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return Le(r,n)}async function Th(t,e,n,r){let s=Date.now()+n;for(;;){let o=kh(t,e);if(o)return o;let i=s-Date.now();if(i<=0)return;await new Promise(u=>{setTimeout(u,Math.min(r,i));});}}async function wc(t,e,n){let r=new Date().toISOString(),s={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},o=t.requestTaskStop({id:e,requestedAt:r,...s}),i=t.getTask(e);if(!o.accepted){if(o.status==="pending"){let C=t.stopPendingTask(e,void 0,void 0,{...s,at:r}),O=t.getTask(e);if(C||!O||O.status!=="running")return Le(O);if(o=t.requestTaskStop({id:e,requestedAt:r,...s}),!o.accepted&&o.status!=="running"||!o.accepted&&!o.alreadyRequestedAt)return Le(t.getTask(e))}else if(!(o.status==="running"&&o.alreadyRequestedAt))return Le(i)}let u=o.runEpoch,d=mi(n.graceMs,gi,0),c=mi(n.pollMs,dh,1),l=await Th(t,e,d,c);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return Le(p);let f=yi(p),h=f.map(C=>C.pid),m=h[0];if(!m){let C=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),O=t.getTask(e);return C||O?.status!=="running"?Le(O):ee(O,"Failed to finalize task stop")}let k=mh(n);if(!hh(p,Date.now())){for(let C of f)if(await Ei(C,{ownershipMarkers:n.ownershipMarkers,processControl:n.processControl,processControlOptions:k})!=="owned")return Ts(p)}let E=n.processControl?.terminateProcessTree??Nt;for(let C of h){let O;try{O=await E(C,{...k,signal:vt});}catch(b){O={status:"failed",pid:C,method:k.platform==="win32"?"taskkill":"process-group",error:b instanceof Error?b.message:String(b)};}if(O.status==="failed")return ee(t.getTask(e),O.error??"Failed to terminate process tree")}let x=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),w=t.getTask(e);return x||w?.status!=="running"?Le(w,m):ee(w,"Task changed before stop was finalized")}function ki(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Ti(t){return Number.isSafeInteger(t)&&t>=0}function pr(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function yh(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function wh(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Eh(t,e){let n=t?.pid&&t.pid>0?t.pid:e;return {status:"stopped",method:"forced",finalStatus:t?.status??"failed",...n?{pid:n}:{}}}function Rh(t){switch(t){case "epoch_mismatch":return _i;case "workspace_mismatch":return hi;default:return}}async function Rc(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return fi(n,ki(e.targetPid)?e.targetPid:void 0);if(!Ti(e.sourceRunEpoch)||!Ti(e.settleRunEpoch)||pr(n.run_epoch)!==e.settleRunEpoch)return ee(n,ui,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return ee(n,ci,e.targetPid);let r=new Date().toISOString(),s;try{s=t.requestTaskStop({id:e.taskId,requestedAt:r,sourceRunEpoch:e.sourceRunEpoch,settleRunEpoch:e.settleRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return ee(n,pi,e.targetPid)}let o=x=>s.stopRequestReceipt?{...x,stopRequestReceipt:s.stopRequestReceipt}:x,i=n,u=()=>{let x=t.getTask(e.taskId);return i=x,x},d=(x,w=false)=>{if(w)try{u();}catch{}return o(ee(i,x,e.targetPid))},c;try{c=u();}catch{return d(pi)}if(!c||c.status!=="running")return o(fi(c,e.targetPid));if(s.runEpoch!==e.settleRunEpoch||pr(c.run_epoch)!==e.settleRunEpoch)return o(ee(c,ui,e.targetPid));if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return o(ee(c,ci,e.targetPid));if(!ki(e.targetPid))return o(ee(c,ch));let l=yh(e),p;try{p=await Ei({pid:e.targetPid,startedAt:c.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:l});}catch{return o(Ts(c,e.targetPid))}if(p!=="owned")return o(Ts(c,e.targetPid));let f;try{f=u();}catch{return d(pi)}if(!f||f.status!=="running")return o(fi(f,e.targetPid));if(pr(f.run_epoch)!==e.settleRunEpoch)return o(ee(f,ui,e.targetPid));if(e.workspaceId!==void 0&&f.workspace_id!==e.workspaceId)return o(ee(f,ci,e.targetPid));let h=e.processControl?.terminateProcessTree??Nt,m;try{m=await h(e.targetPid,{...l,signal:vt});}catch{return d(Tc,true)}if(m.status==="failed")return d(Tc,true);let k;try{k=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return d(li,true)}if(!k)return d(li,true);let E;try{E=u();}catch{return d(li)}return o(Le(E,e.targetPid))}async function Sc(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Le(n);if(!Ti(e.expectedRunEpoch)||pr(n.run_epoch)!==e.expectedRunEpoch)return ee(n,_i);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return ee(n,hi);let r=n.pid;if(!ki(r))return ee(n,ph);let s=wh(e);if(await Ei({pid:r,startedAt:n.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:s})!=="owned")return Ts(n,r,fh);let i=e.processControl?.terminateProcessTree??Nt,u;try{u=await i(r,{...s,signal:vt});}catch{return ee(t.getTask(e.taskId),yc,r)}if(u.status==="failed")return ee(t.getTask(e.taskId),yc,r);let d=t.getTask(e.taskId);if(!d||d.status!=="running")return Le(d,r);if(pr(d.run_epoch)!==e.expectedRunEpoch)return ee(d,_i,r);if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId)return ee(d,hi,r);let c;try{c=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return ee(t.getTask(e.taskId),gh,r)}let l=Rh(c);return l?ee(t.getTask(e.taskId),l,r):c!=="settled"?Le(t.getTask(e.taskId),r):Eh(t.getTask(e.taskId),r)}function Ic(t,e,n={}){if(typeof t=="string"){let r=t,s=e??{};return Promise.resolve().then(()=>(Si(),Ac)).then(({TaskRepository:o})=>wc(new o,r,s))}return wc(t,e,n)}var gi,dh,uh,ch,ui,ci,lh,Tc,li,pi,_i,hi,ph,fh,yc,gh,Ri=v(()=>{_();Vr();lr();gi=5e3,dh=250;uh=["agy","crewx","claude","codex","opencode","grok","node"];ch="INSTRUCTION_STOP_TARGET_PID_MISSING",ui="INSTRUCTION_STOP_EPOCH_MISMATCH",ci="INSTRUCTION_STOP_WORKSPACE_MISMATCH",lh="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",Tc="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",li="INSTRUCTION_STOP_SETTLE_CAS_FAILED",pi="INSTRUCTION_STOP_REQUEST_FAILED",_i="HOST_SHUTDOWN_EPOCH_MISMATCH",hi="HOST_SHUTDOWN_WORKSPACE_MISMATCH",ph="HOST_SHUTDOWN_TARGET_PID_MISSING",fh="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",yc="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",gh="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var Ac={};kl(Ac,{CANONICAL_USER_STOP_ERROR:()=>Pi,DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>Lc,HOST_SHUTDOWN_TERMINAL_ERROR:()=>xc,PENDING_ADOPT_GRACE_MS:()=>Pc,PID_NULL_REAP_GRACE_MS:()=>Hi,RATED_TASK_EXCERPT_MAX_CHARS:()=>Ui,RATED_TASK_LIST_MAX_LIMIT:()=>$c,TASK_HEARTBEAT_HARD_STALE_MS:()=>hc,TASK_HEARTBEAT_INTERVAL_MS:()=>gc,TASK_HEARTBEAT_STALE_MS:()=>_c,TASK_RATINGS:()=>Mc,TaskRatingError:()=>kr,TaskRepository:()=>mr,WORKFLOW_ANCHOR_TASK_KINDS:()=>Ot,buildRatedTasksCountQuery:()=>Uc,buildRatedTasksQuery:()=>Hc,countRatedTasks:()=>Bh,hasRecordedUsage:()=>Mi,isWorkflowAnchorTaskKind:()=>Kn,listRatedTasks:()=>Fh,mergeTerminalReason:()=>Li,resolveTaskHeartbeatHardStaleMs:()=>ks,resolveTaskHeartbeatIntervalMs:()=>ur,resolveTaskHeartbeatStaleMs:()=>In,setTaskRating:()=>qh});function et(t){return ir(t)}function Ai(t){return ir(t)}function Oi(){return or$1(...Ot.map(t=>like(a.metadata,`%"kind":"${t}"%`)))}function Oc(){return and(...Ot.map(t=>notLike(a.metadata,`%"kind":"${t}"%`)))}function vi(t=a.model,e=a.metadata){let n=sql`
|
|
83
|
+
`);r.transaction(i=>{for(let c of i)o.run(c);})(n);}finally{r.close();}}function Ng(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 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"){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=Og(t.additionalArgs);return {...t,...e===void 0?{}:{additionalArgs:e},resumeSessionId:void 0}}function vg(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 Cg(t,e,n){let r=new t(e,{readonly:true,fileMustExist:true});try{return vg(r,n)}finally{r.close();}}async function Qs(t,e={}){let n;try{n=await(e.loadSqlite??Tg)();}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=wg(s),c=Eg(e.userDataHome),d=Sg(n,c);if(d.length>0){if(!eu(n,i))try{await(e.initializeDatabase??Ig)(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{Ag(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=Ng(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 Cg(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;Array.isArray(m)&&m.length>0&&m.every(k=>typeof k=="string")&&c.set(`${d}/${l}`,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 $g(t){return t?Mg[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function rt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Hg(){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+Lg,result:n},n}async function Ug(t){let e=await Qs(t),n=t.additionalArgs??[],r=rt(n,"--model")||rt(n,"-m");if(!t.model||!t.effort||r)return e;let o=(await Hg()).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 ge(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qg(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);ge(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);ge(c)?e.push(c):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function si(t){let e=ge(t.error)?t.error:void 0,n=e&&ge(e.data)?e.data:void 0,r=cu(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,Dg)}function ou(t){let e=ge(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=cu(e),i=s&&ge(s.error)?s.error:void 0,c=typeof i?.type=="string"?i.type:void 0,d=[o,ri(s)].filter(Boolean).join(`
|
|
84
|
+
`);if(r===402||Fg(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:Bg(s,e,t),providerReason:_r(o)});if(n==="provider.free-limit"||r===429){let u=Wg(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 cu(t){let n=(t&&ge(t.response)?t.response:void 0)?.body;if(ge(n))return n;if(typeof n=="string")try{let r=JSON.parse(n);return ge(r)?r:void 0}catch{return}}function ri(t){let e=t&&ge(t.error)?t.error:void 0;return ze(e?.message)??ze(t?.message)}function Fg(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 Bg(t,e,n){let r=t&&ge(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 Wg(t){let e=t?.retryAfterMs;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;let r=(t&&ge(t.response)?t.response:void 0)?.body,o=typeof r=="string"?Gg(r):ge(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 Gg(t){try{let e=JSON.parse(t);return ge(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(ge(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=qg(t),n=[],r=null,o=0,s=[],i=[],c,d=false;for(let u of e.events){let l=typeof u.type=="string"?u.type:void 0;if(l){if(l==="text"){let p=ge(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=ge(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 uu(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function jg(){return new G("OpenCode returned no assistant output.",Ue,{code:"EMPTY_OUTPUT",kind:"transient"})}function Kg(){return new G("OpenCode emitted malformed JSON output.",Ue,{code:"PROVIDER_CRASHED",kind:"transient"})}function zg(t,e){switch(uu(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 bg,Ue,au,Dg,Pg,Lg,ru,Eo,Mg,ii,ai=x(()=>{g();Ht();Kc();pr();On();an();nu();Zs();bg=new Set(["step_start","step_finish"]),Ue="cli/opencode",au="OpenCode provider error",Dg=240,Pg="Follow the instructions provided on standard input.",Lg=3e5,Mg={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:Ug,meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];rt(o,"--format")||o.push("--format","json"),!rt(o,"--standalone")&&!rt(o,"--server")&&o.push("--standalone"),e.resumeSessionId&&!rt(o,"-s")&&!rt(o,"--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=$g(e.mode);rt(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!rt(o,"--auto")&&o.push("--auto");let c=rt(o,"--model")||rt(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(Pg),{args:o,stdinMessage:t,env:gr()}},extractText(t){let e=iu(t),n=e.errorEvents[0];if(n)throw ou(n);let r=zg(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 Kg();let s=uu(e.terminalReason);if(e.hasTerminal&&s==="tool-calls"&&e.toolUseCount>0)return "";throw jg()},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){let n=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=du(t),o.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let c=nt(i,n),d=i.type;if(d){if(d==="text"){let l=i.part?.text;l&&r.push({timestamp:c,type:"text",content:l});continue}if(d==="tool_use"){let u=i.part;if(!u)continue;let l=String(u.tool||""),p=String(u.callID||u.id||""),_=u.state,h=String(_?.status||""),m=_?.input,k=tt(m);if(r.push({timestamp:c,type:"tool_use",toolName:l,toolUseId:p,toolInput:k}),h==="completed"&&_?.output!==void 0){let E=_.output,P=typeof E=="string"?E:JSON.stringify(E);r.push({timestamp:c,type:"tool_result",toolUseId:p,resultPreview:P,isError:false});}else h==="error"&&r.push({timestamp:c,type:"tool_result",toolUseId:p,resultPreview:String(_?.error||"tool error"),isError:true});continue}if(d==="error"){let u=si(i);r.push({timestamp:c,type:"error",content:u,errorMessage:u});continue}}}return r},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?bg.has(r):!1}catch{return false}}};});var lu=x(()=>{g();});function Ro(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Qg(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 Zg(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(!Xg.has(s)){e.push(r);continue}r===s&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function Je(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function eh(t,e){if(!(t?Vg.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 th(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&Yg.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 nh(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 fu(t){let e=Je(t)?t:void 0,n=e&&Je(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=th(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:nh(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function Io(t){let e=fu(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 rh(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 oh(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"||!Je(o.usage)||Nt(o.usage.input_tokens)===void 0||Nt(o.usage.output_tokens)===void 0)return false;return true}function sh(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function ih(t,e){return Je(t)&&Je(e)?{...e,...t}:Je(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&Je(e)?{...e,message:t}:t??e}function ah(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let s of e){let i=Je(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 ah(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=ih(r==null||r===""?n:r,sh(t,e.index));return Io(o)}function gu(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function dh(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function ch(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function hu(t){let e=gu(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function uh(t){let e=Je(t)?t:void 0,n=e&&Je(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=fu(t).message.slice(0,250);return hu({type:o,message:s})??"Antigravity reported a tool error."}function pu(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function _u(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var di,Vg,Xg,ui,Yg,fi,gi=x(()=>{g();Ht();lu();Ds();cr();Ut();lr();Hs();di="antigravity",Vg=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),Xg=new Set(["--conversation","--resume","--continue"]),ui=18e4,Yg=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){rh(t);let{model:r,effort:o}=qt(e.model),s=Fs(r),i=s.model,c=e.effort??o??s.effort,d=eh(i,c),u=e.additionalArgs??[],l=Zg(Qg(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"||!Je(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:oh(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 [_u(o,Io(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let h=So([r]);return h?[_u(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")&&pu(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=Je(s.tool_info)?s.tool_info:void 0,l=ch(s,u);if(!l)return [];let p=dh(s);if(s.state==="ACTIVE"){if(pu(n,`antigravity:active:${d}`))return [];let h=gu(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:l,toolUseId:p,...h===void 0?{}:{toolInput:h}}]}let _=s.state==="ERROR"?uh(u?.error):hu(u?.output);return [{timestamp:o,type:"tool_result",toolName:l,toolUseId:p,..._===void 0?{}:{resultPreview:_},...s.state==="ERROR"?{isError:true}:{}}]}};});var mu=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 yh(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 yh(e).flatMap(n=>{try{let r=JSON.parse(n);return bn(r)?[r]:[]}catch{return []}})}}function Su(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
|
+
`):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 Th(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
|
+
`)||c.endsWith("\r")?"":`
|
|
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 Iu(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?Au(n):"Grok CLI reported an error."}function Au(t){return (t.replace(kh,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Eu(t){return mh.test(t)}function wh(t){let e=Dn(t.modelUsage);return e?Object.keys(e)[0]??null:null}function Eh(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 Rh(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
|
|
89
|
+
`).flatMap(mr)){if(i.type!=="usage")continue;let c=Dn(i.usage);if(!c)continue;let d=De(i.signature);if(d&&d.length>0){let l=`signature:${d}`;if(s.has(l))continue;s.add(l);}let u=ln(c.cache_read_input_tokens);e+=ln(c.input_tokens)+u,n+=u,r+=ln(c.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function Sh(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,yu)){if(!bn(s))continue;let i=De(s.content)?.trim();if(!i)continue;let c=De(s.status)?.trim(),d=De(s.priority)?.trim(),u=[c?`status=${c}`:void 0,d?`priority=${d}`:void 0].filter(p=>!!p),l=u.length>0?` (${u.join(", ")})`:"";n.push(`- ${i}${l}`);}if(n.length===0)return [];e.entries.length>yu&&n.push(wu);let r=n.join(`
|
|
90
|
+
`),o=r.length>Tu?`${r.slice(0,Tu-1)}${wu}`:r;return [{timestamp:t,type:"info",content:o}]}function Ih(t,e){let n=De(e.type);if(n==="thought"){let r=De(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=De(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return Sh(t,e);if(n==="tool_call"){let r=De(e.toolCallId),o=De(e.toolName)??De(e.title),s=e.rawInput===void 0?void 0:Su(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:o,toolInput:s}]}if(n==="tool_call_update"){let r=De(e.status);if(r!=="completed"&&r!=="failed"&&r!=="error")return [];let o=Th(e),s=r!=="completed"||e.isError===true;return [{timestamp:t,type:"tool_result",toolUseId:De(e.toolCallId),toolName:De(e.toolName)??De(e.title),...o!==void 0?et(o,s):{isError:s}}]}if(n==="error"){let r=Iu(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}function Ah(t){return process.platform==="win32"?{flags:["--prompt-file",Ru]}:{flags:["--prompt-file","/dev/stdin"],stdinMessage:t}}var Oo,hh,mh,kh,yu,Tu,wu,Ru,hi,mi=x(()=>{g();Ht();bs();Ut();Nn();lr();an();Oo="cli/grok",hh=new Set(["available_commands","usage","end"]),mh=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,kh=/\u001b\[[0-?]*[ -/]*[@-~]/g,yu=20,Tu=4e3,wu="\u2026",Ru="__CREWX_GROK_PROMPT_FILE__";hi={command:"grok",createSessionId:()=>randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=qt(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],c=n?At("grok").some(z=>z.id===n):false,d=n&&c?vn("grok",n):[],u=!o||d.length===0||d.includes(o)?o:void 0,l=vc(u),p=e.additionalArgs??[],_=z=>p.some(ne=>ne===z||ne.startsWith(`${z}=`)),h=e.providerOptions,m=h?.alwaysApprove,k=h?.sandbox,E=_("--permission-mode")?[]:Ac(e.mode),P=_("--always-approve")?[]:Nc(m),w=_("--sandbox")?[]:Oc(k),L=_("--verbatim")?[]:["--verbatim"],N=Ah(t),b=["--no-auto-update",...s,...N.flags,...L,"--output-format","streaming-json","--no-alt-screen",...i,...l,...E,...P,...w,...p],I={args:b,stdinMessage:N.stdinMessage};if(process.platform==="win32"){let z=b.indexOf(Ru);if(z<0)throw new Error("Grok Windows prompt file placeholder is missing from argv");let ne,Pe,Ee;I.prepare=()=>Ee?Promise.reject(new Error("Grok prompt invocation was already disposed")):(Pe||(Pe=(async()=>{ne=await mkdtemp(join(tmpdir(),"crewx-grok-"));let jt=join(ne,"prompt.txt"),Fr=await open(jt,"wx",384);try{await Fr.writeFile(t,{encoding:"utf8"});}finally{await Fr.close();}b[z]=jt;})()),Pe),I.dispose=()=>(Ee||(Ee=(async()=>{await Pe?.catch(()=>{}),ne&&(await rm$1(ne,{recursive:true,force:true}),ne=void 0);})()),Ee);}return I},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
91
|
+
`).flatMap(mr))typeof r.type=="string"&&(n=true),r.type==="text"&&typeof r.data=="string"&&e.push(r.data);return e.length>0?e.join(""):n?"":t.trim()},extractFailure(t){for(let e of mr(t))if(e.type==="error"){let n=Iu(e);return Eu(Su(e))?new sn(n,Oo):new G(n,Oo)}return null},interpretExit(t,e){if(t===0)return null;let n=Au(e)||`Grok CLI exited with code ${t}.`;return Eu(e)?new sn(n,Oo):new G(n,Oo)},parseResultMeta(t){let n=t.split(`
|
|
92
|
+
`).flatMap(mr).find(r=>r.type==="end");return n?{usage:Eh(n),model:wh(n)}:{usage:Rh(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return mr(t).flatMap(r=>Ih(nt(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return bn(n)&&typeof n.type=="string"?hh.has(n.type):!1}catch{return false}}};});var ti,ni=x(()=>{g();Gs();Ks();Js();ai();gi();mu();mi();Gs();Ks();Js();ai();gi();mi();An();ti={codex:zs,claude:ko,opencode:ii,antigravity:fi,copilot:js,grok:hi};});function Nu(t){if(t.startsWith("cli/"))return ti[t.slice(4)]}var Ou=x(()=>{g();oc();ni();});function vo(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Nh(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function Co(t){if(typeof t.provider!="string"||t.provider.length===0)return;let n=t.taskLogRepository.readLogs(t.taskId)?.entries.filter(_=>_.level==="stdout").map(_=>_.message).join(`
|
|
93
|
+
`)??"";if(!n.trim())return;let r=Nu(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=Nh(o?.model,t.model),i=o?.usage;if(!i)return {stdout:n,adapter:r};let c=vo(i.inputTokens),d=vo(i.outputTokens),u=vo(i.cachedInputTokens),l=Ld(vo(i.costUsd),c,d,u,s);return c!==0||d!==0||u!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:c,outputTokens:d,cachedInputTokens:u,costUsd:l,model:s,...i.complete===void 0?{}:{complete:i.complete}}}:{stdout:n,adapter:r}}var ki=x(()=>{g();Ou();so();});function Ti(t){let e=new Set;for(let n of t)for(let r of Oh.get(n)??[n])e.add(r);return [...e]}function wi(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.terminalReason;return typeof n=="string"&&vh.has(n)?n:void 0}catch{return}}function ot(t){let e=wi(t.metadata);if(e)return e;if(t.status==="runner_lost")return "runner_lost";if(t.status==="stopped")return "user_stop";if(t.status==="failed"&&typeof t.error=="string"){if(yi.stopped.test(t.error))return "user_stop";if(yi.runnerLost.test(t.error))return "runner_lost"}}function qe(t){switch(t.status){case "stopped":case "pending":case "running":case "paused":case "success":return t.status;case "completed":case "done":return "success";case "error":case "runner_lost":return "failed";case "failed":{let e=wi(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&yi.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function Ch(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function kr(t){let e=qe(t);return t.status==="runner_lost"&&wi(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...Ch(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}var pn,Oh,yi,vh,yr=x(()=>{g();pn=["success","completed","done","failed","error","stopped","runner_lost"],Oh=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);yi={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},vh=new Set(["user_stop","runner_lost","launch_failed"]);});function Ei(t,e,n=1){let r=process.env[t];if(r===void 0||r==="")return e;let o=Number(r);return !Number.isFinite(o)||o<=0?e:Math.max(n,Math.trunc(o))}function wr(){return Ei("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Ln(){return Ei("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function bo(){return Ei("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Pn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function xo(t){let e=typeof t=="object"&&t!==null&&"code"in t?String(t.code):t instanceof Error?t.name:typeof t;console.warn(`[crewx] task heartbeat write failed (${e}); execution continues`);}function xh(t){return t?{id:t.id,status:t.status,run_epoch:t.run_epoch,stop_requested_at:t.stop_requested_at,stop_requested_epoch:t.stop_requested_epoch,pid:t.pid,metadata:t.metadata,started_at:t.started_at,duration_ms:t.duration_ms}:null}function vu(t,e){return !!t.stop_requested_at&&Pn(t.stop_requested_epoch)===Pn(e)}function Cu(t,e){let n=Pn(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let o=xh(t.getTask(e.taskId));return !o||o.status!=="running"||Pn(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function Pu(t,e){let n=Tr.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),Tr.delete(t),true)}function Er(t,e){let n=Tr.get(t);return !n||e!==void 0&&n.runEpoch!==Pn(e)?false:Pu(t,n)}function Lu(t,e){let n=Pn(e.runEpoch);Er(e.taskId);let r=true,o=null;try{let u=Cu(t,{...e,runEpoch:n});r=u.accepted,o=u.row;}catch(u){xo(u);}if(!r)return false;let s=wr(),i=Math.min(s,1e3),c=setInterval(()=>{let u=Tr.get(e.taskId);if(!(!u||u.timer!==c))try{u.heartbeatElapsedMs+=i;let l=u.heartbeatElapsedMs>=s,p=Cu(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){Pu(e.taskId,u);return}l&&(u.heartbeatElapsedMs%=s,u.lastHeartbeatAt=Date.now()),p.row&&vu(p.row,n)&&!u.stopRequested&&(u.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(xo));}catch(l){xo(l);}},i),d={timer:c,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return Tr.set(e.taskId,d),typeof c=="object"&&c!==null&&"unref"in c&&c.unref(),o&&vu(o,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(xo)),true}var xu,bu,Du,Tr,Rr=x(()=>{g();xu=1e4,bu=3e4,Du=18e5;Tr=new Map;});function Po(t,e=Date.now(),n=Oi){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=xi(n,Oi,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function Pi(t){let e=[],n=typeof t.pid=="number"&&t.pid>0?t.pid:void 0;n!==void 0&&e.push({pid:n,startedAt:t.pid_started_at});let r=Uu(t.metadata),o=r.ownership==="runner"&&typeof r.providerPid=="number"&&Number.isSafeInteger(r.providerPid)&&r.providerPid>0?r.providerPid:void 0;if(o!==void 0&&o!==n){let s=r.providerPidStartedAt;e.push({pid:o,startedAt:typeof s=="string"?s:null});}return e}async function Li(t,e={}){if(t.pid===process.pid||t.pid===process.ppid)return {verdict:"unproven",ownership:"not_owned",reason:"pid is this process or its parent"};let n=typeof t.startedAt=="string"?Date.parse(t.startedAt):Number.NaN,r=Number.isFinite(n),o=e.legacyStartBoundaryMs;if(!r&&o===void 0)return {verdict:"unproven",ownership:"unknown",reason:"no start time recorded"};let s=e.processControlOptions??{},i=e.processControl?.checkProcessOwnershipAsync??Gd,c=e.processControl?.readProcessIdentityAsync??Jd,d;try{d=await i(t.pid,e.ownershipMarkers??Dh,s);}catch{d="unknown";}let u;try{u=await c(t.pid,s);}catch{u={status:"unknown"};}if(u.status==="not_found")return {verdict:"unproven",ownership:"not_found",reason:"process is no longer running"};if(u.status!=="found")return {verdict:"unproven",ownership:"unknown",reason:"start time could not be read"};let l=new Date(u.startedAtMs).toISOString();if(r){if(Math.abs(u.startedAtMs-n)>ao)return {verdict:"reused",reason:`started ${l}, not the recorded ${t.startedAt}`}}else return o!==void 0&&u.startedAtMs>o?{verdict:"reused",reason:`started ${l}, after the row's last heartbeat`}:{verdict:"unproven",ownership:"unknown",reason:"no start time recorded and it started before the row's last heartbeat"};return d!=="owned"?{verdict:"unproven",ownership:d,reason:"command line has no owned marker"}:u.groupId!==null&&u.groupId!==t.pid?{verdict:"unproven",ownership:"not_owned",reason:"pid does not lead its process group"}:{verdict:"owned"}}async function Mi(t,e={}){let n=await Li(t,e);return n.verdict==="owned"?"owned":n.verdict==="reused"?"not_owned":n.ownership}function xi(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function Uu(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function Uh(t){if(!t)return;let e=Uu(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function Fe(t,e){if(!t)return {status:"not_running",finalStatus:"not_running",...e?{pid:e}:{}};let n=typeof t.pid=="number"&&t.pid>0?t.pid:e;if(t.status==="stopped"){let r=Uh(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function Do(t,e,n="Process owner could not be verified"){let r=e??(t.pid&&t.pid>0?t.pid:void 0);return {status:"ownership_unverified",finalStatus:t.status,...r?{pid:r}:{},error:n}}function se(t,e,n){let r=n??(t?.pid&&t.pid>0?t.pid:void 0);return {status:"failed",finalStatus:t?.status??null,...r?{pid:r}:{},error:e}}function Ni(t,e){return se(t,Lh,e)}function qh(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=Ln():false}function Fh(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Bh(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return Fe(r,n)}async function Wh(t,e,n,r){let o=Date.now()+n;for(;;){let s=Bh(t,e);if(s)return s;let i=o-Date.now();if(i<=0)return;await new Promise(c=>{setTimeout(c,Math.min(r,i));});}}async function Hu(t,e,n){let r=new Date().toISOString(),o={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},s=t.requestTaskStop({id:e,requestedAt:r,...o}),i=t.getTask(e);if(!s.accepted){if(s.status==="pending"){let L=t.stopPendingTask(e,void 0,void 0,{...o,at:r}),N=t.getTask(e);if(L||!N||N.status!=="running")return Fe(N);if(s=t.requestTaskStop({id:e,requestedAt:r,...o}),!s.accepted&&s.status!=="running"||!s.accepted&&!s.alreadyRequestedAt)return Fe(t.getTask(e))}else if(!(s.status==="running"&&s.alreadyRequestedAt))return Fe(i)}let c=s.runEpoch,d=xi(n.graceMs,Oi,0),u=xi(n.pollMs,bh,1),l=await Wh(t,e,d,u);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return Fe(p);let _=Pi(p),h=_.map(L=>L.pid),m=h[0];if(!m){let L=t.finalizeTaskStop({id:e,runEpoch:c,method:"forced"}),N=t.getTask(e);return L||N?.status!=="running"?Fe(N):se(N,"Failed to finalize task stop")}let k=Fh(n);if(!qh(p,Date.now())){for(let L of _)if(await Mi(L,{ownershipMarkers:n.ownershipMarkers,processControl:n.processControl,processControlOptions:k})!=="owned")return Do(p)}let E=n.processControl?.terminateProcessTree??$t;for(let L of h){let N;try{N=await E(L,{...k,signal:Mt});}catch(b){N={status:"failed",pid:L,method:k.platform==="win32"?"taskkill":"process-group",error:b instanceof Error?b.message:String(b)};}if(N.status==="failed")return se(t.getTask(e),N.error??"Failed to terminate process tree")}let P=t.finalizeTaskStop({id:e,runEpoch:c,method:"forced"}),w=t.getTask(e);return P||w?.status!=="running"?Fe(w,m):se(w,"Task changed before stop was finalized")}function bi(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Di(t){return Number.isSafeInteger(t)&&t>=0}function Sr(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Gh(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function jh(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Kh(t,e){let n=t?.pid&&t.pid>0?t.pid:e;return {status:"stopped",method:"forced",finalStatus:t?.status??"failed",...n?{pid:n}:{}}}function zh(t){switch(t){case "epoch_mismatch":return vi;case "workspace_mismatch":return Ci;default:return}}async function qu(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Ni(n,bi(e.targetPid)?e.targetPid:void 0);if(!Di(e.sourceRunEpoch)||!Di(e.settleRunEpoch)||Sr(n.run_epoch)!==e.settleRunEpoch)return se(n,Ri,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return se(n,Si,e.targetPid);let r=new Date().toISOString(),o;try{o=t.requestTaskStop({id:e.taskId,requestedAt:r,sourceRunEpoch:e.sourceRunEpoch,settleRunEpoch:e.settleRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return se(n,Ai,e.targetPid)}let s=P=>o.stopRequestReceipt?{...P,stopRequestReceipt:o.stopRequestReceipt}:P,i=n,c=()=>{let P=t.getTask(e.taskId);return i=P,P},d=(P,w=false)=>{if(w)try{c();}catch{}return s(se(i,P,e.targetPid))},u;try{u=c();}catch{return d(Ai)}if(!u||u.status!=="running")return s(Ni(u,e.targetPid));if(o.runEpoch!==e.settleRunEpoch||Sr(u.run_epoch)!==e.settleRunEpoch)return s(se(u,Ri,e.targetPid));if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId)return s(se(u,Si,e.targetPid));if(!bi(e.targetPid))return s(se(u,Ph));let l=Gh(e),p;try{p=await Mi({pid:e.targetPid,startedAt:u.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:l});}catch{return s(Do(u,e.targetPid))}if(p!=="owned")return s(Do(u,e.targetPid));let _;try{_=c();}catch{return d(Ai)}if(!_||_.status!=="running")return s(Ni(_,e.targetPid));if(Sr(_.run_epoch)!==e.settleRunEpoch)return s(se(_,Ri,e.targetPid));if(e.workspaceId!==void 0&&_.workspace_id!==e.workspaceId)return s(se(_,Si,e.targetPid));let h=e.processControl?.terminateProcessTree??$t,m;try{m=await h(e.targetPid,{...l,signal:Mt});}catch{return d(Mu,true)}if(m.status==="failed")return d(Mu,true);let k;try{k=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return d(Ii,true)}if(!k)return d(Ii,true);let E;try{E=c();}catch{return d(Ii)}return s(Fe(E,e.targetPid))}async function Fu(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Fe(n);if(!Di(e.expectedRunEpoch)||Sr(n.run_epoch)!==e.expectedRunEpoch)return se(n,vi);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return se(n,Ci);let r=n.pid;if(!bi(r))return se(n,Mh);let o=jh(e);if(await Mi({pid:r,startedAt:n.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:o})!=="owned")return Do(n,r,$h);let i=e.processControl?.terminateProcessTree??$t,c;try{c=await i(r,{...o,signal:Mt});}catch{return se(t.getTask(e.taskId),$u,r)}if(c.status==="failed")return se(t.getTask(e.taskId),$u,r);let d=t.getTask(e.taskId);if(!d||d.status!=="running")return Fe(d,r);if(Sr(d.run_epoch)!==e.expectedRunEpoch)return se(d,vi,r);if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId)return se(d,Ci,r);let u;try{u=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return se(t.getTask(e.taskId),Hh,r)}let l=zh(u);return l?se(t.getTask(e.taskId),l,r):u!=="settled"?Fe(t.getTask(e.taskId),r):Kh(t.getTask(e.taskId),r)}function Bu(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(Hi(),Wu)).then(({TaskRepository:s})=>Hu(new s,r,o))}return Hu(t,e,n)}var Oi,bh,Dh,Ph,Ri,Si,Lh,Mu,Ii,Ai,vi,Ci,Mh,$h,$u,Hh,$i=x(()=>{g();co();Rr();Oi=5e3,bh=250;Dh=["agy","crewx","claude","codex","opencode","grok","node"];Ph="INSTRUCTION_STOP_TARGET_PID_MISSING",Ri="INSTRUCTION_STOP_EPOCH_MISMATCH",Si="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Lh="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",Mu="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",Ii="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Ai="INSTRUCTION_STOP_REQUEST_FAILED",vi="HOST_SHUTDOWN_EPOCH_MISMATCH",Ci="HOST_SHUTDOWN_WORKSPACE_MISMATCH",Mh="HOST_SHUTDOWN_TARGET_PID_MISSING",$h="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",$u="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",Hh="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var Wu={};Pl(Wu,{CANONICAL_USER_STOP_ERROR:()=>Ji,DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>Qu,HOST_SHUTDOWN_TERMINAL_ERROR:()=>Ju,PENDING_ADOPT_GRACE_MS:()=>Yu,PID_NULL_REAP_GRACE_MS:()=>Qi,RATED_TASK_EXCERPT_MAX_CHARS:()=>Zi,RATED_TASK_LIST_MAX_LIMIT:()=>el,TASK_HEARTBEAT_HARD_STALE_MS:()=>Du,TASK_HEARTBEAT_INTERVAL_MS:()=>xu,TASK_HEARTBEAT_STALE_MS:()=>bu,TASK_RATINGS:()=>Zu,TaskRatingError:()=>Cr,TaskRepository:()=>vr,WORKFLOW_ANCHOR_TASK_KINDS:()=>Pt,buildRatedTasksCountQuery:()=>nl,buildRatedTasksQuery:()=>tl,countRatedTasks:()=>pm,hasRecordedUsage:()=>Xi,isWorkflowAnchorTaskKind:()=>or,listRatedTasks:()=>lm,mergeTerminalReason:()=>Vi,resolveTaskHeartbeatHardStaleMs:()=>bo,resolveTaskHeartbeatIntervalMs:()=>wr,resolveTaskHeartbeatStaleMs:()=>Ln,setTaskRating:()=>um});function it(t){return kr(t)}function qi(t){return kr(t)}function Fi(){return or$1(...Pt.map(t=>like(a.metadata,`%"kind":"${t}"%`)))}function Gu(){return and(...Pt.map(t=>notLike(a.metadata,`%"kind":"${t}"%`)))}function Wi(t=a.model,e=a.metadata){let n=sql`
|
|
81
94
|
CASE
|
|
82
95
|
WHEN ${t} LIKE 'claude-%' OR ${t} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
83
96
|
WHEN ${t} LIKE 'gpt-%' OR ${t} LIKE 'codex-%' THEN 'codex'
|
|
@@ -88,12 +101,12 @@ ${r.join(`
|
|
|
88
101
|
WHEN ${t} LIKE 'qwen%' THEN 'qwen'
|
|
89
102
|
ELSE 'unknown'
|
|
90
103
|
END
|
|
91
|
-
`,r=sql`json_extract(${e}, '$.provider')`,
|
|
104
|
+
`,r=sql`json_extract(${e}, '$.provider')`,o=sql`trim(${r})`,s=sql`substr(${o}, 1, instr(${o}, '/') - 1)`,i=sql`
|
|
92
105
|
CASE
|
|
93
|
-
WHEN instr(${
|
|
94
|
-
AND ${
|
|
95
|
-
THEN substr(${
|
|
96
|
-
ELSE ${
|
|
106
|
+
WHEN instr(${o}, '/') > 0
|
|
107
|
+
AND ${s} IN ('cli', 'acp', 'api', 'plugin', 'remote')
|
|
108
|
+
THEN substr(${o}, instr(${o}, '/') + 1)
|
|
109
|
+
ELSE ${o}
|
|
97
110
|
END
|
|
98
111
|
`;return sql`
|
|
99
112
|
CASE
|
|
@@ -102,11 +115,11 @@ ${r.join(`
|
|
|
102
115
|
WHEN json_type(${e}, '$') IS NOT 'object' THEN 'unknown'
|
|
103
116
|
WHEN json_type(${e}, '$.provider') IS NULL THEN ${n}
|
|
104
117
|
WHEN json_type(${e}, '$.provider') IS NOT 'text' THEN 'unknown'
|
|
105
|
-
WHEN ${
|
|
118
|
+
WHEN ${o} = '' THEN 'unknown'
|
|
106
119
|
WHEN trim(${i}) = '' THEN 'unknown'
|
|
107
120
|
ELSE ${i}
|
|
108
121
|
END
|
|
109
|
-
`}function
|
|
122
|
+
`}function tm(t){let e={status:t.status,metadata:t.metadata},n=qe(e);return n==="stopped"||n==="failed"&&ot(e)==="runner_lost"}function Nr(t){return sql`${t} NOT IN (${sql.join(nm.map(e=>sql`${e}`),sql`, `)})`}function Lo(t){let e=sql`
|
|
110
123
|
CASE
|
|
111
124
|
WHEN json_valid(${t}) = 1
|
|
112
125
|
THEN json_extract(${t}, '$.usageAccounting')
|
|
@@ -116,7 +129,7 @@ ${r.join(`
|
|
|
116
129
|
COALESCE(SUM(
|
|
117
130
|
CASE WHEN ${e} = 'unavailable' THEN 1 ELSE 0 END
|
|
118
131
|
), 0)
|
|
119
|
-
`}function
|
|
132
|
+
`}function _n(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pe(t){if(!t)return {};try{let e=JSON.parse(t);return _n(e)?{...e}:{}}catch{return {}}}function qo(t){return t==null||t===""}function Mo(t,e){return qo(t)&&!qo(e)?e:t}function rm(t,e){let n=pe(t);if(!e)return n;for(let[r,o]of Object.entries(e))qo(n[r])&&!qo(o)&&(n[r]=o);return n}function $o(t,e){let n=t.origin&&Vu.has(t.origin)?t.origin:"internal",r=t.callerPid!==void 0&&Number.isInteger(t.callerPid)&&t.callerPid>0?t.callerPid:process.pid;return {origin:n,at:t.at??e,callerPid:r,...t.callerTaskId?{callerTaskId:t.callerTaskId}:{}}}function om(t){let e=pe(t).stopRequest;if(_n(e)&&!(typeof e.origin!="string"||!Vu.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function ju(){return or$1(isNull(a.stop_requested_at),ne(sql`COALESCE(${a.stop_requested_epoch}, 0)`,sql`COALESCE(${a.run_epoch}, 0)`))}function Vi(t,e){let n=pe(t??null);return n.terminalReason=e,JSON.stringify(n)}function ji(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==Ji&&(n[em]=e),{error:Ji,metadata:n}}function Te(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Xi(t){return Te(t.input_tokens)!==0||Te(t.output_tokens)!==0||Te(t.cached_input_tokens)!==0||Te(t.cost_usd)!==0}function J(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Ku(t){return {inputTokens:Te(t.inputTokens??0),outputTokens:Te(t.outputTokens??0),cachedInputTokens:Te(t.cachedInputTokens??0),costUsd:Te(t.costUsd??0)}}function Xu(t){if(_n(t))return {inputTokens:Te(t.inputTokens),outputTokens:Te(t.outputTokens),cachedInputTokens:Te(t.cachedInputTokens),costUsd:Te(t.costUsd)}}function Or(t){if(!_n(t))return;let e=t.accounting;return e==="recorded"||e==="partial"||e==="unavailable"?e:void 0}function Yi(t){return t.inputTokens!==0||t.outputTokens!==0||t.cachedInputTokens!==0||t.costUsd!==0}function sm(t){let e=Or(t);if(e==="recorded"||e==="partial")return true;if(e==="unavailable")return false;let n=Xu(t);return n!==void 0&&Yi(n)}function im(t){return Object.values(t).some(e=>{let n=Or(e);return n==="partial"||n==="unavailable"})}function am(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){if(Or(n)==="unavailable")continue;let r=Xu(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function Ho(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}function Ki(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return null;let n=zd(t,e);return n.status==="found"?new Date(n.startedAtMs).toISOString():null}function Un(t,e){if(typeof t!="string"||t.length===0)throw new f("VALIDATION",`${e} is required`);return t}function ea(t,e){let n=Date.parse(t);if(!Number.isFinite(n))throw new f("VALIDATION",`${e} is not a valid ISO time: ${t}`);return new Date(n).toISOString()}function um(t,e){let n=Un(e.workspaceId,"workspaceId"),r=Un(e.taskId,"taskId"),o=e.rating;if(o!==null&&!Zu.includes(o))throw new f("VALIDATION","rating must be 'up', 'down' or null");let s=e.now===void 0?new Date().toISOString():ea(e.now,"now");try{return t.transaction(i=>{let c=and(eq(a.id,r),eq(a.workspace_id,n),inArray(a.status,[...pn])),d=i.update(a).set({rating:o,rated_at:o===null?null:s}).where(and(c,sql`${a.rating} IS NOT ${o}`)).returning({rating:a.rating,ratedAt:a.rated_at}).all();if(d.length>0)return {taskId:r,rating:d[0].rating,ratedAt:d[0].ratedAt,changed:!0};let u=i.select({status:a.status,rating:a.rating,rated_at:a.rated_at}).from(a).where(and(eq(a.id,r),eq(a.workspace_id,n))).limit(1).get();if(!u)throw new Cr("TASK_NOT_FOUND",r);if(!cm.has(u.status))throw new Cr("TASK_RATING_NOT_TERMINAL",r);return {taskId:r,rating:u.rating,ratedAt:u.rated_at,changed:!1}},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to set task rating",i)}}function tl(t){let e=sql`
|
|
120
133
|
SELECT id, rated_at FROM tasks
|
|
121
134
|
WHERE workspace_id = ${t.workspaceId}
|
|
122
135
|
AND rating IS NOT NULL
|
|
@@ -126,41 +139,41 @@ ${r.join(`
|
|
|
126
139
|
LIMIT ${t.limit}
|
|
127
140
|
`;return sql`
|
|
128
141
|
SELECT t.id AS taskId, t.agent_id AS agentId, t.thread_id AS threadId, t.status AS status,
|
|
129
|
-
substr(t.error, 1, ${
|
|
142
|
+
substr(t.error, 1, ${dm}) AS errorHead,
|
|
130
143
|
CASE WHEN json_valid(t.metadata) THEN json_extract(t.metadata, '$.terminalReason') END AS terminalReason,
|
|
131
144
|
t.rating AS rating, t.rated_at AS ratedAt,
|
|
132
|
-
NULLIF(substr(t.prompt, 1, ${
|
|
133
|
-
NULLIF(substr(t.result, 1, ${
|
|
145
|
+
NULLIF(substr(t.prompt, 1, ${Zi}), '') AS promptExcerpt,
|
|
146
|
+
NULLIF(substr(t.result, 1, ${Zi}), '') AS resultExcerpt
|
|
134
147
|
FROM (${e}) AS page
|
|
135
148
|
JOIN tasks t ON t.id = page.id
|
|
136
149
|
ORDER BY page.rated_at DESC, page.id DESC
|
|
137
|
-
`}function
|
|
150
|
+
`}function lm(t,e){let n=Un(e.workspaceId,"workspaceId");if(e.agentId!==void 0&&Un(e.agentId,"agentId"),!Number.isFinite(e.limit)||Math.trunc(e.limit)<1)throw new f("VALIDATION","limit must be a positive integer");let r=Math.min(Math.trunc(e.limit),el),o=e.sinceIso===void 0?void 0:ea(e.sinceIso,"sinceIso");try{return t.all(tl({workspaceId:n,agentId:e.agentId,sinceIso:o,limit:r})).map(i=>({taskId:i.taskId,agentId:i.agentId,threadId:i.threadId,status:qe({status:i.status,error:i.errorHead,metadata:i.terminalReason===null?null:JSON.stringify({terminalReason:i.terminalReason})}),rating:i.rating,ratedAt:i.ratedAt,promptExcerpt:i.promptExcerpt,resultExcerpt:i.resultExcerpt}))}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to list rated tasks",s)}}function nl(t){return sql`
|
|
138
151
|
SELECT COUNT(*) AS total FROM tasks
|
|
139
152
|
WHERE workspace_id = ${t.workspaceId}
|
|
140
153
|
AND rating IS NOT NULL
|
|
141
154
|
${t.agentId!==void 0?sql`AND agent_id = ${t.agentId}`:sql``}
|
|
142
155
|
${t.sinceIso!==void 0?sql`AND rated_at >= ${t.sinceIso}`:sql``}
|
|
143
|
-
`}function Bh(t,e){let n=vn(e.workspaceId,"workspaceId");e.agentId!==void 0&&vn(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:qi(e.sinceIso,"sinceIso");try{return t.all(Uc({workspaceId:n,agentId:e.agentId,sinceIso:r}))[0]?.total??0}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to count rated tasks",s)}}var bi,An,bh,On,bn,vh,Ni,gr,Be,Pi,xc,Nh,Ch,Cc,Hi,Pc,Lc,mr,Mc,Ui,$c,Hh,kr,Uh,Si=v(()=>{_();St();Ut();qt();Rt();Vt();Gr();Kr();Id();Vr();qd();Bd();si();ar();lr();Ri();lr();Gr();bi=40,An="2026-05-09",bh="0.8.9-rc.13",On=10,bn=parseInt(bh.split("rc.")[1]);vh=new Set(["workflow","mcp"]),Ni="usageByEpoch",gr="lateUsage",Be="usageAccounting",Pi="Stopped by user",xc="Stopped by app shutdown",Nh="terminalErrorOriginal";Ch=["pending","running"];Cc=new Set(["http","cli","instruction","workflow","internal"]);Hi=600*1e3,Pc=600*1e3,Lc=300*1e3;mr=class extends Ie{dbPath;clock;taskLogRepository;processControl;lastReaperTickAt;orphanReapInFlight;pidNullObservedSince=new Map;constructor(e={}){super(),this.clock=e.clock??(()=>Date.now()),this.processControl=e.processControl??{},e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Xr({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?Ht(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=dirname(n);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(n))throw new g("NOT_FOUND","Database not found");let r=$(n);if(e)try{$e(r.db,n);}catch(s){throw r.close(),s}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=W(e.runEpoch),s=r===0?or$1(eq(a.run_epoch,0),isNull(a.run_epoch)):eq(a.run_epoch,r);return n.db.update(a).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(and(eq(a.id,e.id),s,eq(a.status,"running"))).run().changes>0}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to heartbeat task",r)}finally{n.close();}}requestTaskStop(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(s=>{let o=s.select({id:a.id,status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!o)return;let i=W(o.run_epoch);if(o.status!=="running"){r={accepted:!1,status:o.status,runEpoch:i};return}let u=o.stop_requested_at!==null&&W(o.stop_requested_epoch)===i,d=u?o.stop_requested_at:e.requestedAt,c=ie(o.metadata),l=u?Ph(o.metadata)??Rs({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):Rs({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:sql`${a.run_epoch}`,metadata:JSON.stringify({...c,stopRequest:l})}).where(and(eq(a.id,e.id),eq(a.status,"running"),bc())).run().changes===0){let m=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:W(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:W(m.run_epoch),...m.stop_requested_at&&W(m.stop_requested_epoch)===W(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:o.status,runEpoch:i};let f=new Set([e.id]),h=(m,k)=>{if(k>=8)return;let E=s.select({id:a.id,status:a.status,metadata:a.metadata}).from(a).where(and(eq(a.parent_task_id,m),eq(a.status,"running"))).all();for(let x of E)f.has(x.id)||(f.add(x.id),s.update(a).set({stop_requested_at:d,stop_requested_epoch:sql`${a.run_epoch}`,metadata:JSON.stringify({...ie(x.metadata),stopRequest:l})}).where(and(eq(a.id,x.id),eq(a.status,"running"),bc())).run(),h(x.id,k+1));};h(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to request task stop",r)}finally{n.close();}}requestTaskStopForInstruction(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(s=>{let o=s.select({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!o)return;let i=W(o.run_epoch),u=W(e.sourceRunEpoch),d=W(e.settleRunEpoch);if(o.status!=="running"||i!==d||e.workspaceId!==void 0&&o.workspace_id!==e.workspaceId){r={accepted:!1,status:o.status,runEpoch:i};return}let c=d===0?or$1(eq(a.run_epoch,0),isNull(a.run_epoch)):eq(a.run_epoch,d),l=or$1(isNull(a.stop_requested_at),isNull(a.stop_requested_epoch),ne(a.stop_requested_epoch,u)),p=Rs({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),f=JSON.stringify({...ie(o.metadata),stopRequest:p}),h=w=>s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:u,metadata:f}).where(and(eq(a.id,e.id),eq(a.status,"running"),c,w,l)).returning({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).all(),k=(e.workspaceId===void 0?h():e.workspaceId===null?h(isNull(a.workspace_id)):h(eq(a.workspace_id,e.workspaceId)))[0];if(k){if(k.stop_requested_at===null||k.stop_requested_epoch===null||k.metadata===null)throw new Error("Instruction stop request write returned incomplete fields");r={accepted:!0,status:k.status,runEpoch:W(k.run_epoch),stopRequestReceipt:{taskId:k.id,workspaceId:k.workspace_id,sourceRunEpoch:u,settleRunEpoch:W(k.run_epoch),stopRequestedAt:k.stop_requested_at,stopRequestedEpoch:W(k.stop_requested_epoch),metadataBefore:o.metadata,metadataAfter:k.metadata}};return}let E=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!E||E.status!=="running"){r={accepted:!1,status:E?.status??"not_running",runEpoch:W(E?.run_epoch)};return}let x=W(E.run_epoch);r={accepted:!1,status:E.status,runEpoch:x,...E.stop_requested_at&&W(E.stop_requested_epoch)===u?{alreadyRequestedAt:E.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to request instruction task stop",r)}finally{n.close();}}finalizeTaskStop(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),s=!1;return n.db.transaction(o=>{let i=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||W(i.run_epoch)!==W(e.runEpoch))return;let u=i.stop_requested_at!==null&&W(i.stop_requested_epoch)===W(e.runEpoch),d=ie(i.metadata),c=u?xi(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...c.metadata,stopMethod:e.method},p=i.duration_ms??e.durationMs??Ss(i.started_at,r,void 0),f=i.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,i.run_epoch);s=o.update(a).set({status:"stopped",error:c.error,completed_at:r,duration_ms:p,metadata:JSON.stringify(l)}).where(and(eq(a.id,e.id),eq(a.status,"running"),f)).run().changes>0;},{behavior:"immediate"}),s}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to finalize task stop",r)}finally{n.close();}}finalizeTaskForHostShutdown(e){if(!this.dbExists())return "not_running";let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),s=W(e.expectedRunEpoch),o="not_running";return n.db.transaction(i=>{let u=i.select({status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!u||u.status!=="running"){o="not_running";return}if(W(u.run_epoch)!==s){o="epoch_mismatch";return}if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId){o="workspace_mismatch";return}let c=u.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,u.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?isNull(a.workspace_id):eq(a.workspace_id,e.workspaceId),p={...ie(u.metadata),terminalReason:"runner_lost"},f=u.duration_ms??Ss(u.started_at,r,void 0);o=i.update(a).set({status:"failed",error:xc,completed_at:r,duration_ms:f,metadata:JSON.stringify(p)}).where(and(eq(a.id,e.id),eq(a.status,"running"),c,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),o}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return Ic(this,e,n)}async stopTaskGenerationForInstruction(e){return Rc({requestTaskStop:n=>this.requestTaskStopForInstruction(n),getTask:n=>this.getTask(n),finalizeTaskStop:n=>this.finalizeTaskStop(n)},e)}startTask(e){let n=this.openHandle(true);try{let r=e.actorKind==="human"&&typeof e.workspaceId=="string"&&e.workspaceId.length>0&&typeof e.actorId=="string"&&e.actorId.length>0,s=r?n.db.select({id:a.id}).from(a).where(eq(a.id,e.id)).get()!==void 0:!0,o={id:e.id,agent_id:e.agentId,actor_kind:e.actorKind??null,actor_id:e.actorId??null,user_id:e.userId??null,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,pid_started_at:Ci(e.pid,this.processControl),parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workflow_run_id:kd(e.metadata),schedule_id:Sd(e.metadata),workspace_id:e.workspaceId??null,cwd:e.cwd??null,project_id:e.projectId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,security_key:e.securityKey??null,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},i=u=>{n.db.insert(a).values(u).onConflictDoUpdate({target:a.id,set:{status:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN 'running' ELSE ${a.status} END`,pid:sql`COALESCE(excluded.pid, ${a.pid})`,pid_started_at:sql`CASE WHEN excluded.pid IS NULL THEN ${a.pid_started_at} ELSE excluded.pid_started_at END`,actor_kind:sql`CASE WHEN ${a.status} IN ('pending', 'running') AND ${a.pid} IS NULL AND ${a.actor_kind} IS NULL AND COALESCE(${a.run_epoch}, 0) = 0 THEN excluded.actor_kind ELSE ${a.actor_kind} END`,actor_id:sql`CASE WHEN ${a.status} IN ('pending', 'running') AND ${a.pid} IS NULL AND ${a.actor_kind} IS NULL AND COALESCE(${a.run_epoch}, 0) = 0 THEN excluded.actor_id ELSE ${a.actor_id} END`,command:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.command ELSE ${a.command} END`,metadata:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.metadata ELSE ${a.metadata} END`,workflow_run_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.workflow_run_id ELSE ${a.workflow_run_id} END`,schedule_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.schedule_id ELSE ${a.schedule_id} END`,workspace_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.workspace_id}, excluded.workspace_id) ELSE ${a.workspace_id} END`,cwd:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.cwd}, excluded.cwd) ELSE ${a.cwd} END`,project_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.project_id}, excluded.project_id) ELSE ${a.project_id} END`,crewx_version:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.crewx_version ELSE ${a.crewx_version} END`,model:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.model ELSE ${a.model} END`,rendered_prompt:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.rendered_prompt ELSE ${a.rendered_prompt} END`,security_key:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.security_key ELSE ${a.security_key} END`,coding_agent_command:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.coding_agent_command ELSE ${a.coding_agent_command} END`},setWhere:or$1(eq(a.status,"running"),and(eq(a.status,"pending"),isNull(a.pid)))}).run();};try{i(o);}catch(u){let d=u instanceof Error?u.message:typeof u=="object"&&u!==null&&"message"in u?String(u.message):String(u);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch|pid_started_at|cwd|actor_kind|actor_id/i.test(d)||!/no such column|no column named/i.test(d))throw u;let c=new Set(n.db.all("PRAGMA table_info(tasks)").map(vr=>vr.name)),l=c.has("cwd"),p=c.has("user_id"),f=c.has("actor_kind"),h=c.has("actor_id"),m=c.has("log_storage"),k=l?", cwd":"",E=l?", ?":"",x=l?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",w=m?", log_storage":"",C=m?", ?":"",O=p?", user_id":"",b=p?", ?":"",I=f?", actor_kind":"",z=f?", ?":"",he=h?", actor_id":"",wt=h?", ?":"",ot=m?`,
|
|
156
|
+
`}function pm(t,e){let n=Un(e.workspaceId,"workspaceId");e.agentId!==void 0&&Un(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:ea(e.sinceIso,"sinceIso");try{return t.all(nl({workspaceId:n,agentId:e.agentId,sinceIso:r}))[0]?.total??0}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to count rated tasks",o)}}var Bi,Mn,Qh,$n,Hn,Zh,Gi,Ar,Ve,Ji,Ju,em,nm,Vu,Qi,Yu,Qu,vr,Zu,Zi,el,dm,Cr,cm,Hi=x(()=>{g();xt();zt();Jt();Ct();on();ro();so();qd();co();tc();rc();ki();yr();Rr();$i();Rr();ro();Bi=40,Mn="2026-05-09",Qh="0.8.9-rc.13",$n=10,Hn=parseInt(Qh.split("rc.")[1]);Zh=new Set(["workflow","mcp"]),Gi="usageByEpoch",Ar="lateUsage",Ve="usageAccounting",Ji="Stopped by user",Ju="Stopped by app shutdown",em="terminalErrorOriginal";nm=["pending","running"];Vu=new Set(["http","cli","instruction","workflow","internal"]);Qi=600*1e3,Yu=600*1e3,Qu=300*1e3;vr=class extends Ce{dbPath;clock;taskLogRepository;processControl;lastReaperTickAt;orphanReapInFlight;pidNullObservedSince=new Map;constructor(e={}){super(),this.clock=e.clock??(()=>Date.now()),this.processControl=e.processControl??{},e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new uo({dbPath:this.dbPath});}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}heartbeatTask(e){let n=this.openHandle(true);try{let r=J(e.runEpoch),o=r===0?or$1(eq(a.run_epoch,0),isNull(a.run_epoch)):eq(a.run_epoch,r);return n.db.update(a).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(and(eq(a.id,e.id),o,eq(a.status,"running"))).run().changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to heartbeat task",r)}finally{n.close();}}requestTaskStop(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:a.id,status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!s)return;let i=J(s.run_epoch);if(s.status!=="running"){r={accepted:!1,status:s.status,runEpoch:i};return}let c=s.stop_requested_at!==null&&J(s.stop_requested_epoch)===i,d=c?s.stop_requested_at:e.requestedAt,u=pe(s.metadata),l=c?om(s.metadata)??$o({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):$o({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(o.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:sql`${a.run_epoch}`,metadata:JSON.stringify({...u,stopRequest:l})}).where(and(eq(a.id,e.id),eq(a.status,"running"),ju())).run().changes===0){let m=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:J(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:J(m.run_epoch),...m.stop_requested_at&&J(m.stop_requested_epoch)===J(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:s.status,runEpoch:i};let _=new Set([e.id]),h=(m,k)=>{if(k>=8)return;let E=o.select({id:a.id,status:a.status,metadata:a.metadata}).from(a).where(and(eq(a.parent_task_id,m),eq(a.status,"running"))).all();for(let P of E)_.has(P.id)||(_.add(P.id),o.update(a).set({stop_requested_at:d,stop_requested_epoch:sql`${a.run_epoch}`,metadata:JSON.stringify({...pe(P.metadata),stopRequest:l})}).where(and(eq(a.id,P.id),eq(a.status,"running"),ju())).run(),h(P.id,k+1));};h(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request task stop",r)}finally{n.close();}}requestTaskStopForInstruction(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!s)return;let i=J(s.run_epoch),c=J(e.sourceRunEpoch),d=J(e.settleRunEpoch);if(s.status!=="running"||i!==d||e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId){r={accepted:!1,status:s.status,runEpoch:i};return}let u=d===0?or$1(eq(a.run_epoch,0),isNull(a.run_epoch)):eq(a.run_epoch,d),l=or$1(isNull(a.stop_requested_at),isNull(a.stop_requested_epoch),ne(a.stop_requested_epoch,c)),p=$o({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),_=JSON.stringify({...pe(s.metadata),stopRequest:p}),h=w=>o.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:c,metadata:_}).where(and(eq(a.id,e.id),eq(a.status,"running"),u,w,l)).returning({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).all(),k=(e.workspaceId===void 0?h():e.workspaceId===null?h(isNull(a.workspace_id)):h(eq(a.workspace_id,e.workspaceId)))[0];if(k){if(k.stop_requested_at===null||k.stop_requested_epoch===null||k.metadata===null)throw new Error("Instruction stop request write returned incomplete fields");r={accepted:!0,status:k.status,runEpoch:J(k.run_epoch),stopRequestReceipt:{taskId:k.id,workspaceId:k.workspace_id,sourceRunEpoch:c,settleRunEpoch:J(k.run_epoch),stopRequestedAt:k.stop_requested_at,stopRequestedEpoch:J(k.stop_requested_epoch),metadataBefore:s.metadata,metadataAfter:k.metadata}};return}let E=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!E||E.status!=="running"){r={accepted:!1,status:E?.status??"not_running",runEpoch:J(E?.run_epoch)};return}let P=J(E.run_epoch);r={accepted:!1,status:E.status,runEpoch:P,...E.stop_requested_at&&J(E.stop_requested_epoch)===c?{alreadyRequestedAt:E.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request instruction task stop",r)}finally{n.close();}}finalizeTaskStop(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=!1;return n.db.transaction(s=>{let i=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||J(i.run_epoch)!==J(e.runEpoch))return;let c=i.stop_requested_at!==null&&J(i.stop_requested_epoch)===J(e.runEpoch),d=pe(i.metadata),u=c?ji(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...u.metadata,stopMethod:e.method},p=i.duration_ms??e.durationMs??Ho(i.started_at,r,void 0),_=i.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,i.run_epoch);o=s.update(a).set({status:"stopped",error:u.error,completed_at:r,duration_ms:p,metadata:JSON.stringify(l)}).where(and(eq(a.id,e.id),eq(a.status,"running"),_)).run().changes>0;},{behavior:"immediate"}),o}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task stop",r)}finally{n.close();}}finalizeTaskForHostShutdown(e){if(!this.dbExists())return "not_running";let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=J(e.expectedRunEpoch),s="not_running";return n.db.transaction(i=>{let c=i.select({status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!c||c.status!=="running"){s="not_running";return}if(J(c.run_epoch)!==o){s="epoch_mismatch";return}if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId){s="workspace_mismatch";return}let u=c.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,c.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?isNull(a.workspace_id):eq(a.workspace_id,e.workspaceId),p={...pe(c.metadata),terminalReason:"runner_lost"},_=c.duration_ms??Ho(c.started_at,r,void 0);s=i.update(a).set({status:"failed",error:Ju,completed_at:r,duration_ms:_,metadata:JSON.stringify(p)}).where(and(eq(a.id,e.id),eq(a.status,"running"),u,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),s}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return Bu(this,e,n)}async stopTaskGenerationForInstruction(e){return qu({requestTaskStop:n=>this.requestTaskStopForInstruction(n),getTask:n=>this.getTask(n),finalizeTaskStop:n=>this.finalizeTaskStop(n)},e)}startTask(e){let n=this.openHandle(true);try{let r=e.actorKind==="human"&&typeof e.workspaceId=="string"&&e.workspaceId.length>0&&typeof e.actorId=="string"&&e.actorId.length>0,o=r?n.db.select({id:a.id}).from(a).where(eq(a.id,e.id)).get()!==void 0:!0,s={id:e.id,agent_id:e.agentId,actor_kind:e.actorKind??null,actor_id:e.actorId??null,user_id:e.userId??null,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,pid_started_at:Ki(e.pid,this.processControl),parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workflow_run_id:Dd(e.metadata),schedule_id:Ud(e.metadata),workspace_id:e.workspaceId??null,cwd:e.cwd??null,project_id:e.projectId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,security_key:e.securityKey??null,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},i=c=>{n.db.insert(a).values(c).onConflictDoUpdate({target:a.id,set:{status:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN 'running' ELSE ${a.status} END`,pid:sql`COALESCE(excluded.pid, ${a.pid})`,pid_started_at:sql`CASE WHEN excluded.pid IS NULL THEN ${a.pid_started_at} ELSE excluded.pid_started_at END`,actor_kind:sql`CASE WHEN ${a.status} IN ('pending', 'running') AND ${a.pid} IS NULL AND ${a.actor_kind} IS NULL AND COALESCE(${a.run_epoch}, 0) = 0 THEN excluded.actor_kind ELSE ${a.actor_kind} END`,actor_id:sql`CASE WHEN ${a.status} IN ('pending', 'running') AND ${a.pid} IS NULL AND ${a.actor_kind} IS NULL AND COALESCE(${a.run_epoch}, 0) = 0 THEN excluded.actor_id ELSE ${a.actor_id} END`,command:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.command ELSE ${a.command} END`,metadata:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.metadata ELSE ${a.metadata} END`,workflow_run_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.workflow_run_id ELSE ${a.workflow_run_id} END`,schedule_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.schedule_id ELSE ${a.schedule_id} END`,workspace_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.workspace_id}, excluded.workspace_id) ELSE ${a.workspace_id} END`,cwd:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.cwd}, excluded.cwd) ELSE ${a.cwd} END`,project_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.project_id}, excluded.project_id) ELSE ${a.project_id} END`,crewx_version:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.crewx_version ELSE ${a.crewx_version} END`,model:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.model ELSE ${a.model} END`,rendered_prompt:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.rendered_prompt ELSE ${a.rendered_prompt} END`,security_key:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.security_key ELSE ${a.security_key} END`,coding_agent_command:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.coding_agent_command ELSE ${a.coding_agent_command} END`},setWhere:or$1(eq(a.status,"running"),and(eq(a.status,"pending"),isNull(a.pid)))}).run();};try{i(s);}catch(c){let d=c instanceof Error?c.message:typeof c=="object"&&c!==null&&"message"in c?String(c.message):String(c);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch|pid_started_at|cwd|actor_kind|actor_id/i.test(d)||!/no such column|no column named/i.test(d))throw c;let u=new Set(n.db.all("PRAGMA table_info(tasks)").map(jt=>jt.name)),l=u.has("cwd"),p=u.has("user_id"),_=u.has("actor_kind"),h=u.has("actor_id"),m=u.has("log_storage"),k=l?", cwd":"",E=l?", ?":"",P=l?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",w=m?", log_storage":"",L=m?", ?":"",N=p?", user_id":"",b=p?", ?":"",I=_?", actor_kind":"",z=_?", ?":"",ne=h?", actor_id":"",Pe=h?", ?":"",Ee=m?`,
|
|
144
157
|
log_storage = CASE WHEN tasks.status = 'pending' THEN excluded.log_storage ELSE tasks.log_storage END`:"";n.runRaw(`INSERT INTO tasks (
|
|
145
158
|
id, agent_id, prompt, mode, status, started_at, pid,
|
|
146
159
|
parent_task_id, caller_agent_id, trace_id, command, metadata,
|
|
147
160
|
workspace_id${k}, project_id, platform, crewx_version, thread_id,
|
|
148
|
-
model, rendered_prompt, coding_agent_command${
|
|
149
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${E}${b}${z}${
|
|
161
|
+
model, rendered_prompt, coding_agent_command${N}${I}${ne}${w}
|
|
162
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${E}${b}${z}${Pe}${L})
|
|
150
163
|
ON CONFLICT(id) DO UPDATE SET
|
|
151
164
|
status = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN 'running' ELSE tasks.status END,
|
|
152
165
|
pid = COALESCE(excluded.pid, tasks.pid),
|
|
153
166
|
command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.command ELSE tasks.command END,
|
|
154
167
|
metadata = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.metadata ELSE tasks.metadata END,
|
|
155
|
-
workspace_id = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.workspace_id, excluded.workspace_id) ELSE tasks.workspace_id END${
|
|
168
|
+
workspace_id = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.workspace_id, excluded.workspace_id) ELSE tasks.workspace_id END${P},
|
|
156
169
|
project_id = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.project_id, excluded.project_id) ELSE tasks.project_id END,
|
|
157
170
|
crewx_version = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.crewx_version ELSE tasks.crewx_version END,
|
|
158
171
|
model = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.model ELSE tasks.model END,
|
|
159
172
|
rendered_prompt = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.rendered_prompt ELSE tasks.rendered_prompt END,
|
|
160
|
-
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${
|
|
161
|
-
WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[
|
|
162
|
-
AND COALESCE(${a.stop_requested_epoch}, 0) <> COALESCE(${a.run_epoch}, 0)`)).run(),i.changes>0}catch(r){throw r instanceof
|
|
163
|
-
`);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=and(eq(a.id,e.id),eq(a.workspace_id,e.workspaceId)),s={status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs};if(e.terminalReason){let o=n.db.select({metadata:a.metadata}).from(a).where(r).limit(1).get(),i=ie(o?.metadata??null);i.terminalReason=e.terminalReason,s.metadata=JSON.stringify(i);}n.db.update(a).set(s).where(r).run();}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to update task lifecycle",r)}finally{n.close();}}appendLog(e,n){this.taskLogRepository.appendLog(e,n);}appendLogs(e,n){this.taskLogRepository.appendLogs(e,n);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,n){return this.taskLogRepository.readLogsTail(e,n)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(se).from(a).where(eq(a.status,"running")).orderBy(desc(a.started_at)).all().map(et)}catch(n){throw new g("DB_ERROR","Failed to get running tasks",n)}finally{e.close();}}getActiveTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(se).from(a).where(inArray(a.status,["pending","running"])).orderBy(desc(a.started_at)).all().map(et)}catch(n){throw new g("DB_ERROR","Failed to get active tasks",n)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(se).from(a).orderBy(desc(a.started_at)).limit(100).all().map(et)}catch(n){throw new g("DB_ERROR","Failed to get all tasks",n)}finally{e.close();}}readTaskSecurityKey(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({security_key:a.security_key}).from(a).where(eq(a.id,e)).limit(1).get()?.security_key??null}catch(r){throw new g("DB_ERROR","Failed to read task security key",r)}finally{n.close();}}recordProviderInput(e){if(!this.dbExists())return false;let n=W(e.runEpoch);if(n===0&&e.interceptedRequest!==true)return false;let r=e.recordedAt??new Date(this.clock()).toISOString(),s=this.openHandle(true);try{let o=!1;return s.db.transaction(i=>{let u=i.select({run_epoch:a.run_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!u||W(u.run_epoch)!==n)return;o=i.insert(ht).values({task_id:e.id,run_epoch:n,input:e.input,key_wrap_skipped:e.keyWrapSkipped?1:0,recorded_at:r}).onConflictDoNothing().run().changes>0;}),o}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to record provider input",o)}finally{s.close();}}listProviderInputEpochs(e,n={}){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=r.db.select({run_epoch:a.run_epoch}).from(a).where(eq(a.id,e)).limit(1).get();if(!s)return [];let o=W(s.run_epoch),i=r.db.select({run_epoch:ht.run_epoch,key_wrap_skipped:ht.key_wrap_skipped}).from(ht).where(eq(ht.task_id,e)).all(),u=new Map(i.map(c=>[c.run_epoch,c])),d=[];for(let c=1;c<=o;c++){let l=u.get(c);l?d.push({runEpoch:c,available:!0,...l.key_wrap_skipped===1?{keyWrapSkipped:!0}:{}}):d.push({runEpoch:c,available:!1,reason:n.archivedRunEpochs?.has(c)?"pruned":"absent"});}return d}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to list provider inputs",s)}finally{r.close();}}readProviderInput(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let s=r.db.select().from(ht).where(and(eq(ht.task_id,e),eq(ht.run_epoch,W(n)))).limit(1).get();return s?{runEpoch:s.run_epoch,input:s.input,keyWrapSkipped:s.key_wrap_skipped===1,recordedAt:s.recorded_at}:void 0}catch(s){throw new g("DB_ERROR","Failed to read provider input",s)}finally{r.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=n.db.select(se).from(a).where(eq(a.id,e)).limit(1).get();return r?et(r):void 0}catch(r){throw new g("DB_ERROR","Failed to get task",r)}finally{n.close();}}async killTask(e){let n=await this.stopTask(e);return n.status==="stopped"?{status:"terminated",killed:n.method==="forced"||n.method==="cooperative",...n.pid?{pid:n.pid}:{}}:n.status==="not_running"?{status:"not_running",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}:{status:"failed",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}}reapOrphanedTasks(e={}){return this.orphanReapInFlight===void 0&&(this.orphanReapInFlight=this.runOrphanReaperPass(e).finally(()=>{this.orphanReapInFlight=void 0;})),this.orphanReapInFlight}async runOrphanReaperPass(e){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=n.db.select({id:a.id,status:a.status,pid:a.pid,pid_started_at:a.pid_started_at,platform:a.platform,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at,started_at:a.started_at,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(or$1(eq(a.status,"running"),eq(a.status,"pending"))).all(),s=this.clock(),o=Math.max(1,Math.trunc(e.tickIntervalMs??Lc)),i=this.lastReaperTickAt,u=i===void 0?Number.POSITIVE_INFINITY:s-i,d=i!==void 0&&u>=0&&u<=o*2;this.lastReaperTickAt=s;let c=In(),l=ks(),p=new Date(s-Pc).toISOString(),f=new Date(s).toISOString(),h=new Set,m=[],k=0,E=(w,C)=>{let O=ie(Li(w.metadata,"runner_lost")),b=typeof O.provider=="string"?O.provider:void 0,I;try{I=hs({taskLogRepository:this.taskLogRepository,taskId:w.id,provider:b,model:w.model})?.usage;}catch{}let z={status:"failed",error:C,completed_at:f};I?(z.input_tokens=I.inputTokens,z.output_tokens=I.outputTokens,z.cached_input_tokens=I.cachedInputTokens,z.cost_usd=I.costUsd,w.model===null&&I.model!==null&&(z.model=I.model),O[Be]="recorded"):!Mi(w)&&O[Be]!=="recorded"&&(O[Be]="unavailable"),z.metadata=JSON.stringify(O);let he=w.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,w.run_epoch),wt=w.heartbeat_at===null?isNull(a.heartbeat_at):eq(a.heartbeat_at,w.heartbeat_at),ot=n.db.update(a).set(z).where(and(eq(a.id,w.id),eq(a.status,"running"),he,wt)).run();return ot.changes>0&&k++,ot.changes>0};for(let w of r){if(w.status==="pending"){if(w.pid!==null||w.started_at>=p)continue;let I=Li(w.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:f,metadata:I}).where(and(eq(a.id,w.id),eq(a.status,"pending"),isNull(a.pid),lt(a.started_at,p))).run().changes>0&&k++;continue}if(vh.has(w.platform??"cli"))continue;if(w.pid===null){let I=`${w.id}:${w.run_epoch??0}`;h.add(I);let z=this.pidNullObservedSince.get(I);if(z===void 0){this.pidNullObservedSince.set(I,s);continue}s-z>=Hi&&E(w,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(I);continue}if(w.heartbeat_at===null){bt(w.pid,this.processControl.kill)==="not_found"&&E(w,"Reaped: process not found (orphaned task)");continue}let C=Date.parse(w.heartbeat_at),O=Number.isFinite(C)?s-C:Number.POSITIVE_INFINITY;if(O<=c)continue;let b=yi(w).filter(I=>bt(I.pid,this.processControl.kill)!=="not_found");b.length===0?E(w,"Reaped: process not found (orphaned task)"):O>l&&d&&m.push({row:w,targets:b});}let x=new Map;for(let w of m){let{row:C,targets:O}=w,b=n.db.select({status:a.status,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at}).from(a).where(eq(a.id,C.id)).get();if(!b||b.status!=="running"||W(b.run_epoch)!==W(C.run_epoch)||b.heartbeat_at!==C.heartbeat_at)continue;let I=await this.judgeRecordedTargets(C,O);if(I.unproven!==void 0){console.warn("[crewx] reaper left running task",{taskId:C.id,reason:I.unproven});continue}if(I.owned.length>0){let z=await this.terminateRecordedProcesses(I.owned,x);if(z!==void 0){console.warn("[crewx] reaper left running task",{taskId:C.id,reason:z});continue}}E(C,"Reaped: heartbeat stale beyond hard limit (orphaned task)")&&I.reused.length>0&&console.warn("[crewx] reaper reaped task whose recorded pid was reused",{taskId:C.id,reason:I.reused.join("; ")});}for(let w of Array.from(this.pidNullObservedSince.keys()))h.has(w)||this.pidNullObservedSince.delete(w);return k}finally{n.close();}}async judgeRecordedTargets(e,n){let r=e.heartbeat_at===null?Number.NaN:Date.parse(e.heartbeat_at),s=Number.isFinite(r)?r+ur()+Jr:void 0,o=[],i=[];for(let u of n){let d=await wi(u,{processControlOptions:this.processControl,legacyStartBoundaryMs:s});if(d.verdict==="owned")o.push(u);else if(d.verdict==="reused")i.push(`pid ${u.pid} reused (${d.reason})`);else return {owned:o,reused:i,unproven:`pid ${u.pid} not proven owned (${d.ownership}): ${d.reason}`}}return {owned:o,reused:i}}async terminateRecordedProcesses(e,n){for(let r of e){if(!n.has(r.pid)){let s;try{s=(await Nt(r.pid,{...this.processControl,signal:vt})).status==="failed"?"failed":"terminated";}catch{s="failed";}n.set(r.pid,s);}if(n.get(r.pid)==="failed")return `pid ${r.pid} termination not confirmed`;if(bt(r.pid,this.processControl.kill)!=="not_found")return `pid ${r.pid} still alive after termination`}}reapRunningWorkflowTasks(e=Hi){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),s=and(eq(a.status,"running"),eq(a.platform,"workflow"),isNull(a.pid),lt(a.started_at,r),or$1(isNull(a.metadata),Oc())),o=n.db.select({id:a.id,metadata:a.metadata}).from(a).where(s).all(),i=new Date().toISOString(),u=0;for(let d of o){let c=ie(d.metadata);c.terminalReason="runner_lost";let l=n.db.update(a).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:i,metadata:JSON.stringify(c)}).where(and(eq(a.id,d.id),eq(a.status,"running"))).run();u+=l.changes??0;}return u}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let o=$(s);try{let i=n?eq(a.workspace_id,n):void 0,u=i?and(eq(a.id,e),i):eq(a.id,e),d=o.db.select(se).from(a).where(u).limit(1).get()??void 0;if(!d){let c=i?and(eq(a.thread_id,e),i):eq(a.thread_id,e);d=o.db.select(se).from(a).where(c).orderBy(desc(a.started_at)).limit(1).get()??void 0;}if(d)return et(d)}catch(i){throw new g("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!existsSync(i))continue;let u=$(i);try{let d=n?and(eq(a.parent_task_id,e),eq(a.workspace_id,n)):eq(a.parent_task_id,e),c=u.db.select(se).from(a).where(d).orderBy(asc(a.started_at)).all();for(let l of c)s.has(l.id)||(s.add(l.id),o.push(et(l)));}catch(d){throw new g("DB_ERROR","Failed to find child tasks",d)}finally{u.close();}}return o}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?sql`
|
|
173
|
+
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${Ee}
|
|
174
|
+
WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[s.id,s.agent_id,s.prompt,s.mode,s.status,s.started_at,s.pid,s.parent_task_id,s.caller_agent_id,s.trace_id,s.command,s.metadata,s.workspace_id,...l?[s.cwd]:[],s.project_id,s.platform,s.crewx_version,s.thread_id,s.model,s.rendered_prompt,s.coding_agent_command,...p?[s.user_id]:[],..._?[s.actor_kind]:[],...h?[s.actor_id]:[],...m?[s.log_storage]:[]]);}r&&!o&&new lo({dbPath:this.resolveDbPath()}).recordAccepted({workspaceId:e.workspaceId,actorId:e.actorId,actorKind:e.actorKind,agentId:e.agentId});}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to start task",r)}finally{n.close();}}recordTaskPid(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=n.db.select({status:a.status,run_epoch:a.run_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||J(r.run_epoch)!==J(e.runEpoch))return !1;let o=r.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,r.run_epoch);return n.db.update(a).set({pid:e.pid,pid_started_at:Ki(e.pid,this.processControl)}).where(and(eq(a.id,e.id),eq(a.status,"running"),o)).run().changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to record task pid",r)}finally{n.close();}}updateTaskOwnership(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=n.db.select({status:a.status,run_epoch:a.run_epoch,metadata:a.metadata,model:a.model,rendered_prompt:a.rendered_prompt,security_key:a.security_key,coding_agent_command:a.coding_agent_command}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||J(r.run_epoch)!==J(e.runEpoch))return !1;let o=rm(r.metadata,e.runtime?.metadata);if(o.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0){o.providerPid=e.providerPid;let c=Ki(e.providerPid,this.processControl);c!==null?o.providerPidStartedAt=c:delete o.providerPidStartedAt;}let s=r.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,r.run_epoch),i=n.db.update(a).set({metadata:JSON.stringify(o),model:Mo(r.model,e.runtime?.model),rendered_prompt:Mo(r.rendered_prompt,e.runtime?.renderedPrompt),security_key:Mo(r.security_key,e.runtime?.securityKey),coding_agent_command:Mo(r.coding_agent_command,e.runtime?.codingAgentCommand)}).where(and(eq(a.id,e.id),eq(a.status,"running"),s)).run();return i.changes>0&&J(e.runEpoch)>0&&n.db.update(a).set({stop_requested_at:null,stop_requested_epoch:null}).where(and(eq(a.id,e.id),eq(a.status,"running"),s,sql`${a.stop_requested_at} IS NOT NULL
|
|
175
|
+
AND COALESCE(${a.stop_requested_epoch}, 0) <> COALESCE(${a.run_epoch}, 0)`)).run(),i.changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to update task ownership",r)}finally{n.close();}}adoptPendingTask(e){let n=this.openHandle(true);try{return n.db.update(a).set({status:"running"}).where(and(eq(a.id,e),eq(a.status,"pending"),isNull(a.pid))).run().changes===1}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to adopt pending task",r)}finally{n.close();}}failPendingTask(e,n,r=new Date().toISOString()){let o=this.openHandle(true);try{return o.db.update(a).set({status:"failed",error:n,completed_at:r}).where(and(eq(a.id,e),eq(a.status,"pending"))).run().changes>0}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to fail pending task",s)}finally{o.close();}}stopPendingTask(e,n,r=new Date().toISOString(),o={}){let s=this.openHandle(true);try{let i=!1;return s.db.transaction(c=>{let d=c.select({metadata:a.metadata}).from(a).where(and(eq(a.id,e),eq(a.status,"pending"))).limit(1).get();if(!d)return;let u=ji(pe(d.metadata),n),l={...u.metadata,stopMethod:"cooperative",stopRequest:$o(o,r)};i=c.update(a).set({status:"stopped",error:u.error,completed_at:r,metadata:JSON.stringify(l)}).where(and(eq(a.id,e),eq(a.status,"pending"))).run().changes===1;},{behavior:"immediate"}),i}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to stop pending task",i)}finally{s.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select(ce).from(a).where(eq(a.project_id,e)).orderBy(desc(a.started_at)).all().map(it)}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true),r,o;try{n.db.transaction(s=>{let i=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,result:a.result,exit_code:a.exit_code,error:a.error,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!i)return;let c=J(i.run_epoch),d=J(e.runEpoch),u=i.status==="running"&&c===d,l=i.stop_requested_at!==null&&J(i.stop_requested_epoch)===c,p=u&&l,_=i.status==="stopped"&&c===d&&l,h=pe(i.metadata),m=_n(h[Ar])?h[Ar]:{},k=String(d),E=tm(i),P=E&&c===d&&!Xi(i)&&!Object.prototype.hasOwnProperty.call(m,k),w=E&&c===d&&!Object.prototype.hasOwnProperty.call(m,k),L=c>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||e.usageComplete!==void 0||c!==d,N={},b;if(i.status!=="running"&&(r=i.status,o=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),L&&(i.status==="running"||w)){b=pe(i.metadata);let I=_n(b[Gi])?{...b[Gi]}:{},z=String(d),ne=Ku(e),Pe=Or(I[z]);e.usageComplete!==void 0?I[z]={...ne,accounting:e.usagePresent===!0?e.usageComplete?"recorded":"partial":"unavailable"}:Pe!==void 0?I[z]={...ne,accounting:Pe}:I[z]=ne,b[Gi]=I;let Ee=am(I),jt=Yi(Ee),Fr=Object.values(I).some(sm),xl=Object.values(I).some(bl=>Or(bl)!==void 0);e.usageComplete!==void 0||xl?(b[Ve]=Fr?"recorded":"unavailable",im(I)?b.usageIncomplete=!0:delete b.usageIncomplete):jt&&h[Ve]==="unavailable"?b[Ve]="recorded":i.status!=="running"&&!jt&&h[Ve]===void 0&&(b[Ve]="unavailable"),N.metadata=JSON.stringify(b),N.input_tokens=Ee.inputTokens,N.output_tokens=Ee.outputTokens,N.cached_input_tokens=Ee.cachedInputTokens,N.cost_usd=Ee.costUsd;}else if(u||P)if(u)N.input_tokens=Te(e.inputTokens??0),N.output_tokens=Te(e.outputTokens??0),N.cached_input_tokens=Te(e.cachedInputTokens??0),N.cost_usd=Te(e.costUsd??0);else {let I=Ku(e),z=e.usageComplete!==void 0?e.usagePresent===!0:Yi(I);z&&(N.input_tokens=I.inputTokens,N.output_tokens=I.outputTokens,N.cached_input_tokens=I.cachedInputTokens,N.cost_usd=I.costUsd),b={...h};let ne=_n(h[Ar])?{...h[Ar]}:{};ne[k]={at:e.completedAt},b[Ar]=ne,b[Ve]===void 0?b[Ve]=z?"recorded":"unavailable":z&&b[Ve]==="unavailable"&&(b[Ve]="recorded"),N.metadata=JSON.stringify(b);}if((u||P)&&e.model!==void 0&&e.model!==null&&(!P||i.model===null)&&(N.model=e.model),p){b??=pe(i.metadata);let I=ji(b,e.error);b={...I.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:Po(i.stop_requested_at,e.completedAt)},N.status="stopped",N.result=e.result??i.result,N.error=I.error,N.completed_at=e.completedAt,N.duration_ms=i.duration_ms??e.durationMs??Ho(i.started_at,e.completedAt,void 0),N.exit_code=e.exitCode??i.exit_code,N.metadata=JSON.stringify(b);}else if(u)e.partialResultRecovered===!0&&(b??=pe(i.metadata),b.partialResultRecovered=!0,N.metadata=JSON.stringify(b)),N.status=e.status,N.result=e.result??null,N.error=e.error??null,N.completed_at=e.completedAt,N.duration_ms=c>0?Ho(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,N.exit_code=e.exitCode??null;else if(_){let I=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(N.result=e.result,I=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(N.exit_code=e.exitCode),e.partialResultRecovered===!0&&(b??=pe(i.metadata),b.partialResultRecovered=!0,N.metadata=JSON.stringify(b)),I&&(r=void 0,o=void 0);}Object.keys(N).length>0&&s.update(a).set(N).where(eq(a.id,e.id)).run();},{behavior:"immediate"});}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to finish task",s)}finally{n.close();}if(r!==void 0){try{this.taskLogRepository.appendLog(e.id,{timestamp:e.completedAt,level:"late-result",message:o??`task:end status=${e.status}`});}catch(s){console.error(`[crewx] failed to preserve late task result for ${e.id}: ${s instanceof Error?s.message:String(s)}`);}process.stderr.write(`Task ${e.id} was already finalized (${r}); late result kept in task log
|
|
176
|
+
`);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=and(eq(a.id,e.id),eq(a.workspace_id,e.workspaceId)),o={status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs};if(e.terminalReason){let s=n.db.select({metadata:a.metadata}).from(a).where(r).limit(1).get(),i=pe(s?.metadata??null);i.terminalReason=e.terminalReason,o.metadata=JSON.stringify(i);}n.db.update(a).set(o).where(r).run();}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to update task lifecycle",r)}finally{n.close();}}appendLog(e,n){this.taskLogRepository.appendLog(e,n);}appendLogs(e,n){this.taskLogRepository.appendLogs(e,n);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,n){return this.taskLogRepository.readLogsTail(e,n)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(ce).from(a).where(eq(a.status,"running")).orderBy(desc(a.started_at)).all().map(it)}catch(n){throw new f("DB_ERROR","Failed to get running tasks",n)}finally{e.close();}}getActiveTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(ce).from(a).where(inArray(a.status,["pending","running"])).orderBy(desc(a.started_at)).all().map(it)}catch(n){throw new f("DB_ERROR","Failed to get active tasks",n)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(ce).from(a).orderBy(desc(a.started_at)).limit(100).all().map(it)}catch(n){throw new f("DB_ERROR","Failed to get all tasks",n)}finally{e.close();}}readTaskSecurityKey(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({security_key:a.security_key}).from(a).where(eq(a.id,e)).limit(1).get()?.security_key??null}catch(r){throw new f("DB_ERROR","Failed to read task security key",r)}finally{n.close();}}recordProviderInput(e){if(!this.dbExists())return false;let n=J(e.runEpoch);if(n===0&&e.interceptedRequest!==true)return false;let r=e.recordedAt??new Date(this.clock()).toISOString(),o=this.openHandle(true);try{let s=!1;return o.db.transaction(i=>{let c=i.select({run_epoch:a.run_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!c||J(c.run_epoch)!==n)return;s=i.insert(Et).values({task_id:e.id,run_epoch:n,input:e.input,key_wrap_skipped:e.keyWrapSkipped?1:0,recorded_at:r}).onConflictDoNothing().run().changes>0;}),s}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to record provider input",s)}finally{o.close();}}listProviderInputEpochs(e,n={}){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=r.db.select({run_epoch:a.run_epoch}).from(a).where(eq(a.id,e)).limit(1).get();if(!o)return [];let s=J(o.run_epoch),i=r.db.select({run_epoch:Et.run_epoch,key_wrap_skipped:Et.key_wrap_skipped}).from(Et).where(eq(Et.task_id,e)).all(),c=new Map(i.map(u=>[u.run_epoch,u])),d=[];for(let u=1;u<=s;u++){let l=c.get(u);l?d.push({runEpoch:u,available:!0,...l.key_wrap_skipped===1?{keyWrapSkipped:!0}:{}}):d.push({runEpoch:u,available:!1,reason:n.archivedRunEpochs?.has(u)?"pruned":"absent"});}return d}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to list provider inputs",o)}finally{r.close();}}readProviderInput(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let o=r.db.select().from(Et).where(and(eq(Et.task_id,e),eq(Et.run_epoch,J(n)))).limit(1).get();return o?{runEpoch:o.run_epoch,input:o.input,keyWrapSkipped:o.key_wrap_skipped===1,recordedAt:o.recorded_at}:void 0}catch(o){throw new f("DB_ERROR","Failed to read provider input",o)}finally{r.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=n.db.select(ce).from(a).where(eq(a.id,e)).limit(1).get();return r?it(r):void 0}catch(r){throw new f("DB_ERROR","Failed to get task",r)}finally{n.close();}}async killTask(e){let n=await this.stopTask(e);return n.status==="stopped"?{status:"terminated",killed:n.method==="forced"||n.method==="cooperative",...n.pid?{pid:n.pid}:{}}:n.status==="not_running"?{status:"not_running",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}:{status:"failed",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}}reapOrphanedTasks(e={}){return this.orphanReapInFlight===void 0&&(this.orphanReapInFlight=this.runOrphanReaperPass(e).finally(()=>{this.orphanReapInFlight=void 0;})),this.orphanReapInFlight}async runOrphanReaperPass(e){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=n.db.select({id:a.id,status:a.status,pid:a.pid,pid_started_at:a.pid_started_at,platform:a.platform,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at,started_at:a.started_at,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(or$1(eq(a.status,"running"),eq(a.status,"pending"))).all(),o=this.clock(),s=Math.max(1,Math.trunc(e.tickIntervalMs??Qu)),i=this.lastReaperTickAt,c=i===void 0?Number.POSITIVE_INFINITY:o-i,d=i!==void 0&&c>=0&&c<=s*2;this.lastReaperTickAt=o;let u=Ln(),l=bo(),p=new Date(o-Yu).toISOString(),_=new Date(o).toISOString(),h=new Set,m=[],k=0,E=(w,L)=>{let N=pe(Vi(w.metadata,"runner_lost")),b=typeof N.provider=="string"?N.provider:void 0,I;try{I=Co({taskLogRepository:this.taskLogRepository,taskId:w.id,provider:b,model:w.model})?.usage;}catch{}let z={status:"failed",error:L,completed_at:_};I?(z.input_tokens=I.inputTokens,z.output_tokens=I.outputTokens,z.cached_input_tokens=I.cachedInputTokens,z.cost_usd=I.costUsd,w.model===null&&I.model!==null&&(z.model=I.model),N[Ve]="recorded"):!Xi(w)&&N[Ve]!=="recorded"&&(N[Ve]="unavailable"),z.metadata=JSON.stringify(N);let ne=w.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,w.run_epoch),Pe=w.heartbeat_at===null?isNull(a.heartbeat_at):eq(a.heartbeat_at,w.heartbeat_at),Ee=n.db.update(a).set(z).where(and(eq(a.id,w.id),eq(a.status,"running"),ne,Pe)).run();return Ee.changes>0&&k++,Ee.changes>0};for(let w of r){if(w.status==="pending"){if(w.pid!==null||w.started_at>=p)continue;let I=Vi(w.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:_,metadata:I}).where(and(eq(a.id,w.id),eq(a.status,"pending"),isNull(a.pid),lt(a.started_at,p))).run().changes>0&&k++;continue}if(Zh.has(w.platform??"cli"))continue;if(w.pid===null){let I=`${w.id}:${w.run_epoch??0}`;h.add(I);let z=this.pidNullObservedSince.get(I);if(z===void 0){this.pidNullObservedSince.set(I,o);continue}o-z>=Qi&&E(w,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(I);continue}if(w.heartbeat_at===null){Lt(w.pid,this.processControl.kill)==="not_found"&&E(w,"Reaped: process not found (orphaned task)");continue}let L=Date.parse(w.heartbeat_at),N=Number.isFinite(L)?o-L:Number.POSITIVE_INFINITY;if(N<=u)continue;let b=Pi(w).filter(I=>Lt(I.pid,this.processControl.kill)!=="not_found");b.length===0?E(w,"Reaped: process not found (orphaned task)"):N>l&&d&&m.push({row:w,targets:b});}let P=new Map;for(let w of m){let{row:L,targets:N}=w,b=n.db.select({status:a.status,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at}).from(a).where(eq(a.id,L.id)).get();if(!b||b.status!=="running"||J(b.run_epoch)!==J(L.run_epoch)||b.heartbeat_at!==L.heartbeat_at)continue;let I=await this.judgeRecordedTargets(L,N);if(I.unproven!==void 0){console.warn("[crewx] reaper left running task",{taskId:L.id,reason:I.unproven});continue}if(I.owned.length>0){let z=await this.terminateRecordedProcesses(I.owned,P);if(z!==void 0){console.warn("[crewx] reaper left running task",{taskId:L.id,reason:z});continue}}E(L,"Reaped: heartbeat stale beyond hard limit (orphaned task)")&&I.reused.length>0&&console.warn("[crewx] reaper reaped task whose recorded pid was reused",{taskId:L.id,reason:I.reused.join("; ")});}for(let w of Array.from(this.pidNullObservedSince.keys()))h.has(w)||this.pidNullObservedSince.delete(w);return k}finally{n.close();}}async judgeRecordedTargets(e,n){let r=e.heartbeat_at===null?Number.NaN:Date.parse(e.heartbeat_at),o=Number.isFinite(r)?r+wr()+ao:void 0,s=[],i=[];for(let c of n){let d=await Li(c,{processControlOptions:this.processControl,legacyStartBoundaryMs:o});if(d.verdict==="owned")s.push(c);else if(d.verdict==="reused")i.push(`pid ${c.pid} reused (${d.reason})`);else return {owned:s,reused:i,unproven:`pid ${c.pid} not proven owned (${d.ownership}): ${d.reason}`}}return {owned:s,reused:i}}async terminateRecordedProcesses(e,n){for(let r of e){if(!n.has(r.pid)){let o;try{o=(await $t(r.pid,{...this.processControl,signal:Mt})).status==="failed"?"failed":"terminated";}catch{o="failed";}n.set(r.pid,o);}if(n.get(r.pid)==="failed")return `pid ${r.pid} termination not confirmed`;if(Lt(r.pid,this.processControl.kill)!=="not_found")return `pid ${r.pid} still alive after termination`}}reapRunningWorkflowTasks(e=Qi){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),o=and(eq(a.status,"running"),eq(a.platform,"workflow"),isNull(a.pid),lt(a.started_at,r),or$1(isNull(a.metadata),Gu())),s=n.db.select({id:a.id,metadata:a.metadata}).from(a).where(o).all(),i=new Date().toISOString(),c=0;for(let d of s){let u=pe(d.metadata);u.terminalReason="runner_lost";let l=n.db.update(a).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:i,metadata:JSON.stringify(u)}).where(and(eq(a.id,d.id),eq(a.status,"running"))).run();c+=l.changes??0;}return c}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=q(o);try{let i=n?eq(a.workspace_id,n):void 0,c=i?and(eq(a.id,e),i):eq(a.id,e),d=s.db.select(ce).from(a).where(c).limit(1).get()??void 0;if(!d){let u=i?and(eq(a.thread_id,e),i):eq(a.thread_id,e);d=s.db.select(ce).from(a).where(u).orderBy(desc(a.started_at)).limit(1).get()??void 0;}if(d)return it(d)}catch(i){throw new f("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let c=q(i);try{let d=n?and(eq(a.parent_task_id,e),eq(a.workspace_id,n)):eq(a.parent_task_id,e),u=c.db.select(ce).from(a).where(d).orderBy(asc(a.started_at)).all();for(let l of u)o.has(l.id)||(o.add(l.id),s.push(it(l)));}catch(d){throw new f("DB_ERROR","Failed to find child tasks",d)}finally{c.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?sql`
|
|
164
177
|
SELECT
|
|
165
178
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
166
179
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -181,33 +194,33 @@ ${r.join(`
|
|
|
181
194
|
FROM tasks
|
|
182
195
|
GROUP BY workspace_id
|
|
183
196
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
184
|
-
`)}catch(r){throw new
|
|
197
|
+
`)}catch(r){throw new f("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,i=0,c=0;for(let d of r){if(!existsSync(d))continue;let u=q(d);try{let l=eq(a.thread_id,e),p=n?and(l,eq(a.workspace_id,n)):l,_=u.db.select({id:a.id,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd}).from(a).where(p).all();for(let h of _)o.has(h.id)||(o.add(h.id),s+=h.input_tokens??0,i+=h.output_tokens??0,c+=h.cost_usd??0);}catch(l){throw new f("DB_ERROR","Failed to get thread token usage",l)}finally{u.close();}}return {inputTokens:s,outputTokens:i,costUsd:c}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[],c=r?.projection==="activity-log";for(let d of o){if(!existsSync(d))continue;let u=q(d);try{let l=eq(a.thread_id,e),p=n?and(l,eq(a.workspace_id,n)):l,_=c?u.db.select({id:a.id,thread_id:a.thread_id,agent_id:a.agent_id,parent_task_id:a.parent_task_id,started_at:a.started_at,completed_at:a.completed_at}).from(a).where(p).orderBy(asc(a.started_at)).all():u.db.select(ce).from(a).where(p).orderBy(asc(a.started_at)).all().map(it);for(let h of _)s.has(h.id)||(s.add(h.id),i.push(h));}catch(l){throw new f("DB_ERROR","Failed to find tasks by thread",l)}finally{u.close();}}return i}parseWorkflowCardMetadata(e){if(!e)return {};try{let n=JSON.parse(e);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let r=q(n);try{e.push(...r.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(and(eq(a.platform,"workflow"),inArray(a.status,["running","pending"]),Fi())).orderBy(desc(a.started_at)).all().map(qi));}catch(o){throw new f("DB_ERROR","Failed to find workflow parent tasks",o)}finally{r.close();}}return e}findWorkflowParentTasksByWorkspace(e){let n=[],r=new Map;for(let o of this.resolveDbPaths()){if(!existsSync(o))continue;let s=q(o);try{let i=s.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(and(eq(a.platform,"workflow"),eq(a.workspace_id,e))).orderBy(desc(a.started_at),desc(a.id)).all();for(let c of i){let d=this.parseWorkflowCardMetadata(c.metadata);if(!or(d.kind)||typeof d.workflowRunId!="string")continue;let u=d.kind,l=r.get(u)??new Set;l.has(d.workflowRunId)||(l.add(d.workflowRunId),r.set(u,l),n.push(qi(c)));}}catch(i){throw new f("DB_ERROR","Failed to find workflow parent tasks by workspace",i)}finally{s.close();}}return n}findWorkflowParentTask(e){if(this.dbExists())for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let r=q(n);try{let o=r.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(and(eq(a.platform,"workflow"),eq(a.workspace_id,e.workspaceId))).orderBy(desc(a.started_at),desc(a.id)).all();for(let s of o){let i=this.parseWorkflowCardMetadata(s.metadata);if(i.kind===e.kind&&i.workflowRunId===e.workflowRunId)return qi(s)}}catch(o){throw new f("DB_ERROR","Failed to find workflow parent task",o)}finally{r.close();}}}batchFetchWorkflowCards(e,n){let r=new Map;if(e.length===0)return r;let o=new Set(e),s=new Map,i=n?eq(a.workspace_id,n):void 0,c=(d,u)=>{if(!d)return;let l=s.get(d);if(l&&u.started_at<=l)return;let p=this.parseWorkflowCardMetadata(u.metadata);or(p.kind)&&(s.set(d,u.started_at),r.set(d,{taskId:u.id,workflowRunId:p.workflowRunId,raw:u.result??void 0}));};for(let d of this.resolveDbPaths()){if(!existsSync(d))continue;let u=q(d);try{let l=and(inArray(a.thread_id,e),Fi()),p=u.db.select({id:a.id,thread_id:a.thread_id,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?and(l,i):l).all();for(let m of p)c(m.thread_id,m);let _=and(isNull(a.thread_id),Fi()),h=u.db.select({id:a.id,command:a.command,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?and(_,i):_).all();for(let m of h){let k=this.extractThreadIdFromCommand(m.command);!k||!o.has(k)||c(k,m);}}catch(l){throw new f("DB_ERROR","Failed to batch fetch workflow cards",l)}finally{u.close();}}return r}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(eq(a.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&r.push(inArray(a.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&r.push(inArray(a.status,Ti(s)));let i=e.q??e.search;i&&r.push(like(a.prompt,`%${i}%`)),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt(a.started_at,e.to));let c=r.length>0?and(...r):void 0,d=n.db.select({count:sql`count(*)`}).from(a).where(c).get(),u=(e.sortDir??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at);return {rows:n.db.select(ce).from(a).where(c).orderBy(u).limit(e.limit).offset(e.offset).all().map(it),total:d?.count??0}}catch(r){throw new f("DB_ERROR","Failed to find all tasks",r)}finally{n.close();}}getAgentUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Wi(sql.raw("t.model"),sql.raw("t.metadata")),i=Nr(sql.raw("t.status")),c=Lo(sql.raw("t.metadata")),d=sql`
|
|
185
198
|
COALESCE(t.input_tokens, 0)
|
|
186
199
|
+ CASE
|
|
187
|
-
WHEN t.started_at >= ${
|
|
200
|
+
WHEN t.started_at >= ${Mn}
|
|
188
201
|
AND (
|
|
189
202
|
t.crewx_version IS NULL
|
|
190
203
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
191
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
204
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${$n}) AS INTEGER) < ${Hn})
|
|
192
205
|
)
|
|
193
206
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
194
207
|
ELSE 0
|
|
195
208
|
END
|
|
196
|
-
`,
|
|
209
|
+
`,u=r?sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n} AND t.workspace_id = ${r} AND t.agent_id != 'workflow'`:sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n} AND t.agent_id != 'workflow'`,l=o.db.all(sql`
|
|
197
210
|
SELECT
|
|
198
211
|
t.agent_id,
|
|
199
212
|
t.workspace_id,
|
|
200
|
-
${
|
|
213
|
+
${s} AS provider,
|
|
201
214
|
COUNT(*) AS total_tasks,
|
|
202
|
-
${
|
|
215
|
+
${c} AS unavailable_task_count,
|
|
203
216
|
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
204
217
|
COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
|
|
205
218
|
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
206
219
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
207
220
|
FROM tasks t
|
|
208
|
-
${
|
|
209
|
-
GROUP BY t.agent_id, t.workspace_id, ${
|
|
210
|
-
`),p=new Map;for(let m of l){let k=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",E={provider:k,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,totalTokens:m.input_tokens+m.output_tokens,costUsd:m.cost_usd,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count},
|
|
221
|
+
${u}
|
|
222
|
+
GROUP BY t.agent_id, t.workspace_id, ${s}
|
|
223
|
+
`),p=new Map;for(let m of l){let k=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",E={provider:k,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,totalTokens:m.input_tokens+m.output_tokens,costUsd:m.cost_usd,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count},P=m.workspace_id??null,w=JSON.stringify([m.agent_id,P]),L=p.get(w);if(!L){p.set(w,{agentId:m.agent_id,workspaceId:P,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,costUsd:m.cost_usd,totalTokens:m.input_tokens+m.output_tokens,providers:[E]});continue}L.totalTasks+=m.total_tasks,L.unavailableTaskCount=(L.unavailableTaskCount??0)+m.unavailable_task_count,L.inputTokens+=m.input_tokens,L.outputTokens+=m.output_tokens,L.cachedInputTokens+=m.cached_input_tokens,L.costUsd+=m.cost_usd,L.totalTokens+=m.input_tokens+m.output_tokens;let N=L.providers.find(b=>b.provider===k);N?(N.inputTokens+=E.inputTokens,N.outputTokens+=E.outputTokens,N.cachedInputTokens+=E.cachedInputTokens,N.totalTokens+=E.totalTokens,N.costUsd+=E.costUsd,N.totalTasks+=E.totalTasks,N.unavailableTaskCount+=E.unavailableTaskCount):L.providers.push(E);}let _=[...p.values()];for(let m of _)m.providers.sort((k,E)=>k.provider===E.provider?0:k.provider==="unknown"?1:E.provider==="unknown"?-1:k.totalTokens!==E.totalTokens?E.totalTokens-k.totalTokens:k.provider<E.provider?-1:1);let h=(m,k)=>m===k?0:m<k?-1:1;return _.sort((m,k)=>{if(m.totalTokens!==k.totalTokens)return k.totalTokens-m.totalTokens;let E=h(m.agentId,k.agentId);return E!==0?E:m.workspaceId===k.workspaceId?0:m.workspaceId===null?1:k.workspaceId===null?-1:h(m.workspaceId,k.workspaceId)}),_}catch(s){throw new f("DB_ERROR","Failed to get agent usage",s)}finally{o.close();}}getAgentUsageTrendRaw(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Nr(sql.raw("t.status")),i=Lo(sql.raw("t.metadata"));return o.db.all(r?sql`
|
|
211
224
|
SELECT
|
|
212
225
|
date(t.started_at) AS date,
|
|
213
226
|
t.agent_id,
|
|
@@ -215,11 +228,11 @@ ${r.join(`
|
|
|
215
228
|
COALESCE(SUM(
|
|
216
229
|
COALESCE(t.input_tokens, 0)
|
|
217
230
|
+ CASE
|
|
218
|
-
WHEN t.started_at >= ${
|
|
231
|
+
WHEN t.started_at >= ${Mn}
|
|
219
232
|
AND (
|
|
220
233
|
t.crewx_version IS NULL
|
|
221
234
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
222
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
235
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${$n}) AS INTEGER) < ${Hn})
|
|
223
236
|
)
|
|
224
237
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
225
238
|
ELSE 0
|
|
@@ -229,7 +242,7 @@ ${r.join(`
|
|
|
229
242
|
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
230
243
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
231
244
|
FROM tasks t
|
|
232
|
-
WHERE ${
|
|
245
|
+
WHERE ${s}
|
|
233
246
|
AND t.started_at >= ${e}
|
|
234
247
|
AND t.started_at < ${n}
|
|
235
248
|
AND t.workspace_id = ${r}
|
|
@@ -244,11 +257,11 @@ ${r.join(`
|
|
|
244
257
|
COALESCE(SUM(
|
|
245
258
|
COALESCE(t.input_tokens, 0)
|
|
246
259
|
+ CASE
|
|
247
|
-
WHEN t.started_at >= ${
|
|
260
|
+
WHEN t.started_at >= ${Mn}
|
|
248
261
|
AND (
|
|
249
262
|
t.crewx_version IS NULL
|
|
250
263
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
251
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
264
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${$n}) AS INTEGER) < ${Hn})
|
|
252
265
|
)
|
|
253
266
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
254
267
|
ELSE 0
|
|
@@ -258,29 +271,29 @@ ${r.join(`
|
|
|
258
271
|
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
259
272
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
260
273
|
FROM tasks t
|
|
261
|
-
WHERE ${
|
|
274
|
+
WHERE ${s}
|
|
262
275
|
AND t.started_at >= ${e}
|
|
263
276
|
AND t.started_at < ${n}
|
|
264
277
|
AND t.agent_id != 'workflow'
|
|
265
278
|
GROUP BY date(t.started_at), t.agent_id
|
|
266
279
|
ORDER BY date(t.started_at) ASC
|
|
267
|
-
`).map(d=>({date:d.date,agentId:d.agent_id,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(
|
|
280
|
+
`).map(d=>({date:d.date,agentId:d.agent_id,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(s){throw new f("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let o=r.db.select(ce).from(a).where(and(eq(a.id,e),eq(a.workspace_id,n))).limit(1).get();return o?it(o):void 0}catch(o){throw new f("DB_ERROR","Failed to find task for stop",o)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:a.id,thread_id:a.thread_id,status:a.status,result:a.result,error:a.error,started_at:a.started_at,completed_at:a.completed_at,metadata:a.metadata}).from(a).where(and(eq(a.agent_id,e.agentId),eq(a.workspace_id,e.workspaceId),sql`${a.metadata} IS NOT NULL AND json_valid(${a.metadata}) AND json_extract(${a.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(desc(a.started_at)).limit(1).get()??null}catch(r){throw new f("DB_ERROR","Failed to find latest task by metadata",r)}finally{n.close();}}markTaskFailed(e,n,r,o="failed",s){if(!this.dbExists())return;let i=this.openHandle(true);try{let c=new Date().toISOString(),d=r?and(eq(a.id,e),eq(a.status,"running"),eq(a.workspace_id,r)):and(eq(a.id,e),eq(a.status,"running")),u=i.db.select({metadata:a.metadata}).from(a).where(d).limit(1).get();if(!u)return;let l={status:o,error:n,completed_at:c};if(s){let p=pe(u.metadata);p.terminalReason=s,l.metadata=JSON.stringify(p);}i.db.update(a).set(l).where(d).run();}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to mark task failed",c)}finally{i.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let c=q(i);try{let d=n?and(like(a.prompt,`%${e}%`),eq(a.workspace_id,n)):like(a.prompt,`%${e}%`),u=c.db.select(ce).from(a).where(d).orderBy(asc(a.started_at)).all();for(let l of u)o.has(l.id)||(o.add(l.id),s.push(it(l)));}catch(d){throw new f("DB_ERROR","Failed to find tasks by prompt hint",d)}finally{c.close();}}return s}getProviderUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Wi(),i=Nr(a.status),c=Lo(a.metadata),d=sql`
|
|
268
281
|
COALESCE(${a.input_tokens}, 0)
|
|
269
282
|
+ CASE
|
|
270
|
-
WHEN ${a.started_at} >= ${
|
|
283
|
+
WHEN ${a.started_at} >= ${Mn}
|
|
271
284
|
AND (
|
|
272
285
|
${a.crewx_version} IS NULL
|
|
273
286
|
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
274
|
-
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${
|
|
287
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${$n}) AS INTEGER) < ${Hn})
|
|
275
288
|
)
|
|
276
289
|
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
277
290
|
ELSE 0
|
|
278
291
|
END
|
|
279
|
-
`,
|
|
292
|
+
`,u=r?sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`;return o.db.all(sql`
|
|
280
293
|
SELECT
|
|
281
|
-
${
|
|
294
|
+
${s} AS provider,
|
|
282
295
|
COUNT(*) AS total_tasks,
|
|
283
|
-
${
|
|
296
|
+
${c} AS unavailable_task_count,
|
|
284
297
|
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
285
298
|
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens,
|
|
286
299
|
COALESCE(SUM(${a.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
@@ -288,27 +301,27 @@ ${r.join(`
|
|
|
288
301
|
COALESCE(SUM(${a.duration_ms}), 0) AS active_duration_ms,
|
|
289
302
|
MAX(${a.completed_at}) AS last_active_at
|
|
290
303
|
FROM ${a}
|
|
291
|
-
${
|
|
292
|
-
GROUP BY ${
|
|
304
|
+
${u}
|
|
305
|
+
GROUP BY ${s}
|
|
293
306
|
ORDER BY (COALESCE(SUM(${d}), 0) + COALESCE(SUM(${a.output_tokens}), 0)) DESC
|
|
294
|
-
`).map(p=>({provider:p.provider,totalTasks:p.total_tasks,unavailableTaskCount:p.unavailable_task_count,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null}))}catch(
|
|
307
|
+
`).map(p=>({provider:p.provider,totalTasks:p.total_tasks,unavailableTaskCount:p.unavailable_task_count,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null}))}catch(s){throw new f("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Wi(),i=Nr(a.status),c=Lo(a.metadata),d=sql`
|
|
295
308
|
COALESCE(${a.input_tokens}, 0)
|
|
296
309
|
+ CASE
|
|
297
|
-
WHEN ${a.started_at} >= ${
|
|
310
|
+
WHEN ${a.started_at} >= ${Mn}
|
|
298
311
|
AND (
|
|
299
312
|
${a.crewx_version} IS NULL
|
|
300
313
|
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
301
|
-
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${
|
|
314
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${$n}) AS INTEGER) < ${Hn})
|
|
302
315
|
)
|
|
303
316
|
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
304
317
|
ELSE 0
|
|
305
318
|
END
|
|
306
|
-
`,
|
|
319
|
+
`,u=r?sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`,l=o.db.all(sql`
|
|
307
320
|
SELECT
|
|
308
321
|
${a.model} AS model,
|
|
309
|
-
${
|
|
322
|
+
${s} AS provider,
|
|
310
323
|
COUNT(*) AS total_tasks,
|
|
311
|
-
${
|
|
324
|
+
${c} AS unavailable_task_count,
|
|
312
325
|
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
313
326
|
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens,
|
|
314
327
|
COALESCE(SUM(${a.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
@@ -316,9 +329,9 @@ ${r.join(`
|
|
|
316
329
|
COALESCE(SUM(${a.duration_ms}), 0) AS active_duration_ms,
|
|
317
330
|
MAX(${a.completed_at}) AS last_active_at
|
|
318
331
|
FROM ${a}
|
|
319
|
-
${
|
|
320
|
-
GROUP BY ${a.model}, ${
|
|
321
|
-
`),p=new Map;for(let
|
|
332
|
+
${u}
|
|
333
|
+
GROUP BY ${a.model}, ${s}
|
|
334
|
+
`),p=new Map;for(let _ of l){let h=Os(_.model??""),m=JSON.stringify([_.provider,h]),k=p.get(m);k?(k.totalTasks+=_.total_tasks,k.unavailableTaskCount=(k.unavailableTaskCount??0)+_.unavailable_task_count,k.inputTokens+=_.input_tokens,k.outputTokens+=_.output_tokens,k.cachedInputTokens+=_.cached_input_tokens,k.costUsd+=_.cost_usd,k.totalTokens+=_.input_tokens+_.output_tokens,k.activeDurationMs+=_.active_duration_ms??0,_.last_active_at&&(!k.lastActiveAt||_.last_active_at>k.lastActiveAt)&&(k.lastActiveAt=_.last_active_at)):p.set(m,{model:h,provider:_.provider,totalTasks:_.total_tasks,unavailableTaskCount:_.unavailable_task_count,inputTokens:_.input_tokens,outputTokens:_.output_tokens,cachedInputTokens:_.cached_input_tokens,costUsd:_.cost_usd,totalTokens:_.input_tokens+_.output_tokens,activeDurationMs:_.active_duration_ms??0,lastActiveAt:_.last_active_at??null});}return Array.from(p.values()).sort((_,h)=>h.costUsd-_.costUsd)}catch(s){throw new f("DB_ERROR","Failed to get model usage",s)}finally{o.close();}}getTasksForReport(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=r?sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`;return o.db.all(sql`
|
|
322
335
|
SELECT
|
|
323
336
|
${a.thread_id} AS thread_id,
|
|
324
337
|
${a.agent_id} AS agent_id,
|
|
@@ -328,53 +341,53 @@ ${r.join(`
|
|
|
328
341
|
${a.exit_code} AS exit_code,
|
|
329
342
|
${a.metadata} AS metadata
|
|
330
343
|
FROM ${a}
|
|
331
|
-
${
|
|
344
|
+
${s}
|
|
332
345
|
ORDER BY ${a.started_at} ASC
|
|
333
|
-
`).map(
|
|
346
|
+
`).map(c=>({threadId:c.thread_id,agentId:c.agent_id,startedAt:c.started_at,status:c.status,error:c.error,exitCode:c.exit_code,terminalReason:ot({status:c.status,error:c.error,metadata:c.metadata})??null}))}catch(s){throw new f("DB_ERROR","Failed to get tasks for report",s)}finally{o.close();}}getDelegationMatrix(e,n,r){if(!this.dbExists())return {edges:[],truncated:false};let o=this.openHandle(false);try{let s=sql`
|
|
334
347
|
COALESCE(${a.input_tokens}, 0)
|
|
335
348
|
+ CASE
|
|
336
|
-
WHEN ${a.started_at} >= ${
|
|
349
|
+
WHEN ${a.started_at} >= ${Mn}
|
|
337
350
|
AND (
|
|
338
351
|
${a.crewx_version} IS NULL
|
|
339
352
|
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
340
|
-
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${
|
|
353
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${$n}) AS INTEGER) < ${Hn})
|
|
341
354
|
)
|
|
342
355
|
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
343
356
|
ELSE 0
|
|
344
357
|
END
|
|
345
|
-
`,i=
|
|
358
|
+
`,i=Nr(a.status),c=r?sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`,d=o.db.all(sql`
|
|
346
359
|
SELECT
|
|
347
360
|
${a.caller_agent_id} AS caller_agent_id,
|
|
348
361
|
${a.agent_id} AS agent_id,
|
|
349
362
|
COUNT(*) AS task_count,
|
|
350
|
-
COALESCE(SUM(${
|
|
363
|
+
COALESCE(SUM(${s}), 0) AS input_tokens,
|
|
351
364
|
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens
|
|
352
365
|
FROM ${a}
|
|
353
|
-
${
|
|
366
|
+
${c}
|
|
354
367
|
GROUP BY ${a.caller_agent_id}, ${a.agent_id}
|
|
355
368
|
ORDER BY task_count DESC, ${a.caller_agent_id} ASC, ${a.agent_id} ASC
|
|
356
|
-
LIMIT ${
|
|
357
|
-
`),
|
|
369
|
+
LIMIT ${Bi+1}
|
|
370
|
+
`),u=d.length>Bi;return {edges:d.slice(0,Bi).map(p=>({callerAgentId:p.caller_agent_id??null,agentId:p.agent_id,taskCount:p.task_count,totalTokens:p.input_tokens+p.output_tokens,outputTokens:p.output_tokens})),truncated:u}}catch(s){throw new f("DB_ERROR","Failed to get delegation matrix",s)}finally{o.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(eq(a.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(inArray(a.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(inArray(a.status,Ti(e.statuses))),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt(a.started_at,e.to));let o=r.length>0?and(...r):void 0,s=(e.order??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at),i={id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id,error:a.error,metadata:a.metadata};return (e.limit?n.db.select(i).from(a).where(o).orderBy(s).limit(e.limit).all():n.db.select(i).from(a).where(o).orderBy(s).all()).map(({error:d,metadata:u,...l})=>({...l,status:qe({status:l.status,error:d,metadata:u}),terminalReason:ot({status:l.status,error:d,metadata:u})??null}))}catch(r){throw new f("DB_ERROR","Failed to find task evidence",r)}finally{n.close();}}findThreadChains(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=e.maxThreads??8,o=e.maxTurnsPerThread??4,s=[isNotNull(a.thread_id),isNull(a.parent_task_id),isNull(a.caller_agent_id),or$1(isNull(a.platform),ne(a.platform,"workflow")),or$1(isNull(a.metadata),Gu()),or$1(isNull(a.metadata),notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(eq(a.workspace_id,e.workspaceId)),e.from&&s.push(gte(a.started_at,e.from)),e.to&&s.push(lt(a.started_at,e.to));let i=n.db.select({id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id}).from(a).where(and(...s)).orderBy(asc(a.started_at),asc(a.id)).all(),c=new Map;for(let u of i){if(!u.thread_id)continue;let l={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},p=c.get(u.thread_id);p?p.push(l):c.set(u.thread_id,[l]);}let d=[];for(let[u,l]of c){let p=l.filter(_=>_.agentId===e.targetAgentId).length;p<2||d.push({threadId:u,targetAgentTurnCount:p,turns:l});}return d.sort((u,l)=>{let p=u.turns[u.turns.length-1].startedAt,_=l.turns[l.turns.length-1].startedAt;return p<_?1:p>_?-1:0}),d.slice(0,r).map(u=>({threadId:u.threadId,targetAgentTurnCount:u.targetAgentTurnCount,turns:u.turns.slice(-o)}))}catch(r){throw new f("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}},Zu=["up","down"],Zi=1e3,el=200,dm=64,Cr=class extends f{stableCode;taskId;constructor(e,n){super(e==="TASK_NOT_FOUND"?"NOT_FOUND":"CONFLICT",e==="TASK_NOT_FOUND"?`Task not found: ${n}`:`Task is not finished, so it cannot be rated: ${n}`),this.name="TaskRatingError",this.stableCode=e,this.taskId=n;}},cm=new Set(pn);});g();g();g();var vt=class{detach(e){}};g();function ga(t){let e=n=>String(n).padStart(2,"0");return `${t.getFullYear()}${e(t.getMonth()+1)}${e(t.getDate())}T${e(t.getHours())}${e(t.getMinutes())}${e(t.getSeconds())}`}function ts(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var ns=class extends vt{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(e){super(),this.logsDir=join(e?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=e?.version??"unknown";}attach(e){this.unsubs.push(e.on("task:start",n=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let r=ga(n.timestamp),o=join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,o);let s=`=== TASK LOG: ${n.traceId} ===
|
|
358
371
|
CrewX Version: ${this.version}
|
|
359
372
|
Mode: ${n.mode}
|
|
360
373
|
Agent: ${n.agentRef}
|
|
361
|
-
Started: ${
|
|
374
|
+
Started: ${ts(n.timestamp)}
|
|
362
375
|
Message: ${n.message}
|
|
363
376
|
|
|
364
|
-
`;writeFileSync(s,
|
|
365
|
-
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let
|
|
366
|
-
[${
|
|
367
|
-
`;appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};_();_();var sa=Symbol.for("crewx.interceptor.run-stops");function Al(){let t=globalThis,e=t[sa];if(e)return e;let n=new Map;return t[sa]=n,n}function oa(t){let e=Al().get(t);return e?(e.abort(),true):false}_();var an=new Map;function Nr(t){let e=ke.resolve(t);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(n,r)=>`${r.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function da(t){let e=Nr(t);return createHash("sha256").update(e).digest("hex")}function ua(t){let e=Nr(t),n=an.get(e);if(n!==void 0)return n;let r=e;try{let s=ke.join(e,".git");if(!lstatSync(s).isFile())return an.set(e,r),r;let o=/^gitdir:\s*(.+?)\s*$/i.exec(readFileSync(s,"utf8").trim());if(!o)return an.set(e,r),r;let i=o[1],u=ke.isAbsolute(i)?i:ke.resolve(ke.dirname(s),i),d=readFileSync(ke.join(u,"commondir"),"utf8").trim();if(!d)return an.set(e,r),r;let c=ke.isAbsolute(d)?d:ke.resolve(u,d);if(ke.basename(c)!==".git"||!statSync(c).isDirectory())return an.set(e,r),r;let l=Nr(realpathSync.native(e)),p=Nr(realpathSync.native(ke.dirname(c)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return an.set(e,r),r}Rt();Si();_n();si();lr();Ri();Vr();var Gh=200,jh=200;function Kh(t){if(typeof t!="object"||t===null||!("code"in t))return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function zh(t){let e=t instanceof g?t.code:void 0,n=t instanceof g?t.cause:t,r=Kh(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function Fc(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function Jh(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Bc(t){if(!t)return {};try{let e=JSON.parse(t);return Jh(e)?e:{}}catch{return {}}}function Nn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Vh=new Set(["workflow","mcp"]),Fi=class extends Et{name="sqlite-tracing";unsubs=[];dbPath;version;inheritWorktreeOwner;runnerIdentity;taskRepo;heartbeatTaskIds=new Set;ownedTaskRuns=new Map;ignoredDetachedTaskIds=new Set;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super();let n=process.env.CREWX_DB;this.dbPath=e?.dbRoot!==void 0?join(e.dbRoot,".crewx","crewx.db"):n??join(homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown",this.inheritWorktreeOwner=e?.inheritWorktreeOwner===true;let r=e?.runnerIdentity;this.runnerIdentity={detachedRunner:r?.detachedRunner===true,assignedTaskId:r?.detachedRunner===true&&r.assignedTaskId?.trim()||void 0};}attach(e){let n=new mr({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),s=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml")),o=this.inheritWorktreeOwner?ua(r):r,i=s?da(o):null,u=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let c=d.callerAgentId??null,l=d.parentTaskId??null,p=d.rootTraceId??d.traceId,{detachedRunner:f,assignedTaskId:h}=this.runnerIdentity,m=h??d.traceId,k=Nn(d.metadata?.runEpoch),E=f?"runner":"caller",x=d.workspaceId??i,w=f?n.getTask(m):void 0,C=d.pid??null,O={...d.metadata??{provider:d.provider??"cli/claude"},ownership:E,...f&&C!==null?{providerPid:C}:{}},b=JSON.stringify(O);if(f&&w?.status==="running"&&w.pid!==null&&k===0){this.ignoredDetachedTaskIds.add(m);return}n.startTask({id:m,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",actorKind:d.actorKind??null,actorId:d.actorId??null,pid:f?process.pid:C,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,securityKey:d.renderedPrompt==null?null:d.securityKey??null,command:u,codingAgentCommand:d.codingAgentCommand??null,workspaceId:x,projectId:d.projectId??null,callerAgentId:c,parentTaskId:l,traceId:p,metadata:b,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:m,runEpoch:k,ownership:E,...f?{providerPid:C}:{},runtime:{model:d.model??null,renderedPrompt:d.renderedPrompt??null,codingAgentCommand:d.codingAgentCommand??null,metadata:O}})?this.recordOwnedTaskRun({taskId:m,runEpoch:k,workspaceId:x,ownership:E}):console.warn("[crewx] task execution metadata not recorded",{taskId:m,runEpoch:k,ownership:E}),Vh.has(d.platform??"cli")||kc(n,{taskId:m,runEpoch:k,onStopRequested:wt=>this.handleStopRequested(n,wt)})&&this.heartbeatTaskIds.add(m);}catch(c){console.warn("[crewx] task:start tracing failed",{cause:c instanceof Error?c.name:typeof c});}}),e.on("task:output",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;this.enqueueLog(c,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(c){let l={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(c,[l],Fc(l));}}),e.on("task:run-update",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;let l=Nn(d.runEpoch),p=this.runnerIdentity.detachedRunner;n.updateTaskOwnership({id:c,runEpoch:l,ownership:p?"runner":"caller",...p&&d.pid!==void 0?{providerPid:d.pid}:{},runtime:{...d.model!==void 0?{model:d.model}:{},...d.renderedPrompt!==void 0?{renderedPrompt:d.renderedPrompt}:{},...d.securityKey!==void 0?{securityKey:d.securityKey}:{},...d.codingAgentCommand!==void 0?{codingAgentCommand:d.codingAgentCommand}:{},...d.metadata?{metadata:d.metadata}:{}}}),!p&&d.pid!==void 0&&n.recordTaskPid({id:c,runEpoch:l,pid:d.pid});}catch(c){console.warn("[crewx] task:run-update tracing failed",{cause:c instanceof Error?c.name:typeof c});}}),e.on("task:provider-input",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;n.recordProviderInput({id:c,runEpoch:d.runEpoch,input:d.input,keyWrapSkipped:d.keyWrapSkipped,interceptedRequest:d.interceptedRequest===!0,recordedAt:d.timestamp.toISOString()});}catch(c){console.warn("[crewx] task:provider-input tracing failed",{cause:c instanceof Error?c.name:typeof c});}}),e.on("task:end",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.delete(c))return;let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null;this.removeOwnedTaskRun(c,Nn(l)),cr(c,l)&&this.heartbeatTaskIds.delete(c),this.flushTaskLogs(c);let f=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{},...d.error.mode?{mode:d.error.mode}:{}}):null,h=d.result??null,m=!1,k=d.metadata?.suppressPartialResultRecovery===!0;if(d.error&&!k&&(!h||h.trim()==="")){let E=this.recoverPartialResult(c,d,l);E&&(h=E,m=!0);}n.finishTask({id:c,status:d.error?"failed":"success",result:h,error:f,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,usagePresent:d.inputTokens!==void 0||d.outputTokens!==void 0||d.cachedInputTokens!==void 0,usageComplete:d.usageComplete,model:d.model??null,runEpoch:l,partialResultRecovered:m});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers();for(let n of this.heartbeatTaskIds)cr(n);this.heartbeatTaskIds.clear(),this.ownedTaskRuns.clear(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.ignoredDetachedTaskIds.clear(),this.taskRepo=void 0;}}listOwnedRunningTasks(){return Array.from(this.ownedTaskRuns.values(),e=>({...e}))}async stopOwnedRunningTasksForHostShutdown(){let e=this.taskRepo;if(!e)return;let n=this.listOwnedRunningTasks();for(let r of n)try{let s=await Sc(e,{taskId:r.taskId,expectedRunEpoch:r.runEpoch,workspaceId:r.workspaceId});(s.status==="failed"||s.status==="ownership_unverified")&&console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,status:s.status,...s.error?{error:s.error}:{}});}catch(s){console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,cause:s instanceof Error?s.name:typeof s});}}getMetrics(){let e=0,n=0;for(let r of this.queues.values())e+=r.entries.length,n+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:n}}resolveTaskId(e){return this.runnerIdentity.detachedRunner?this.runnerIdentity.assignedTaskId??e:e}recordOwnedTaskRun(e){let n=this.ownedTaskRuns.get(e.taskId);n&&n.runEpoch>e.runEpoch||this.ownedTaskRuns.set(e.taskId,{...e});}removeOwnedTaskRun(e,n){let r=this.ownedTaskRuns.get(e);!r||r.runEpoch!==n||this.ownedTaskRuns.delete(e);}enqueueLog(e,n){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(n),r.bytes+=Fc(n),this.metrics.maxQueueEntries=Math.max(this.metrics.maxQueueEntries,r.entries.length),this.metrics.maxQueueBytes=Math.max(this.metrics.maxQueueBytes,r.bytes),r.entries.length>=Gh){this.flushTaskLogs(e);return}if(!r.timer){let s=setTimeout(()=>{let o=this.queues.get(e);!o||o.timer!==s||(o.timer=void 0,this.flushTaskLogs(e));},jh);r.timer=s;}}recoverPartialResult(e,n,r){try{let s=this.taskRepo;if(!s)return;let o=s.getTask(e);if(!o||o.status!=="running"||Nn(o.run_epoch)!==Nn(r))return;let i=Bc(o.metadata),u=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!u)return;let d=hs({taskLogRepository:s,taskId:e,provider:u,model:o.model});if(!d?.adapter.extractPartialText)return;let c=d.adapter.extractPartialText(d.stdout);return !c||!c.trim()||pt(c,u)?void 0:c}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let s=Nn(n.run_epoch),o=Bc(n.metadata??null),i=o.ownership==="runner"?"runner":"caller";if(i==="runner"&&n.pid!==process.pid){console.warn("[crewx] ignored stop request for task owned by another runner",{taskId:r});return}let u=typeof o.providerPid=="number"&&Number.isSafeInteger(o.providerPid)&&o.providerPid>0?o.providerPid:void 0,d=i==="runner"?u:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if(oa(r),d!==void 0){let c;try{c=await Nt(d,{signal:vt});}catch(l){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:l instanceof Error?l.name:typeof l});return}if(c.status==="failed"){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:c.error??"process termination failed"});return}}try{let c=e.finalizeTaskStop({id:r,runEpoch:s,method:ys(n.stop_requested_at)}),l=e.getTask(r);(c||l?.status!=="running")&&cr(r,s)&&this.heartbeatTaskIds.delete(r);}catch(c){console.warn("[crewx] cooperative task stop finalization failed",{taskId:r,cause:c instanceof Error?c.name:typeof c});}}flushTaskLogs(e){let n=this.queues.get(e);if(!n||n.entries.length===0){n?.timer&&clearTimeout(n.timer),this.queues.delete(e);return}n.timer&&(clearTimeout(n.timer),n.timer=void 0);let r=n.entries,s=n.bytes;n.entries=[],n.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(i){this.recordAppendFailure(i,r,s);}let o=this.queues.get(e);o&&o.entries.length===0&&(o.timer&&clearTimeout(o.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,n,r){let s=zh(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=n.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[s.code]=(this.metrics.appendFailureByCode[s.code]??0)+1,this.metrics.appendFailureByCause[s.cause]=(this.metrics.appendFailureByCause[s.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:s.code,cause:s.cause,pendingEntries:n.length,pendingBytes:r});}};_();_();_();St();Ut();qt();Rt();Vt();Gr();ar();_();function bs(t){return t!==null&&t!==""}function Xh(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":bs(t.parent_task_id)||bs(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function Wc(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&bs(e)?e:null}}function vs(t){let e=Xh(t),n=bs(t.caller_agent_id)?t.caller_agent_id:null,r=t.parent_thread_id!==null&&t.parent_thread_id!==t.thread_id;return {origin:e==="human"?"direct":"delegated",delegatedByAgentId:e==="agent"?n??(r&&t.parent_agent_id||null):null}}function Gc(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?Wc(t.creator_actor_kind,t.creator_actor_id):e?vs(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?Wc(t.created_by_kind,t.created_by_id):n?vs(n):void 0}function Tr(t){return ir(t)}function nm({metadata:t,...e}){return {...e,status:Pe({...e,metadata:t}),terminalReason:Qe({...e,metadata:t})??null}}var yr=32,Kc=100,rm=["running","failed"];function sm(t){return t==="running"?0:t==="failed"?1:2}function zc(t,e){return t[0]!==e[0]?t[0]-e[0]:t[1]!==e[1]?t[1]===null?1:e[1]===null||t[1]<e[1]?-1:1:t[2]<e[2]?-1:t[2]>e[2]?1:0}function om(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function im(t){try{let e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(Array.isArray(e)&&e.length===3&&Number.isInteger(e[0])&&e[0]>=0&&e[0]<=2&&(e[1]===null||typeof e[1]=="string")&&typeof e[2]=="string")return [e[0],e[1],e[2]]}catch{}throw new g("VALIDATION","Invalid descendant cursor")}function Jc(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function Bi(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function am(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function Wi(t,e,n,r){let s=am(e);s&&(t[s]+=r,t.total+=r,s==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var xs=900,Vc=20;function Xc(t,e){return (t?.origin??"direct")===e}function Yc(t,e){let n=new Date(e.updated_at).getTime()-new Date(t.updated_at).getTime();return n!==0?n:t.id.localeCompare(e.id)}var xn=class extends g{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function Cn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function dm(t){let n=Cn(t).threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {priority:null,state:null};let r=n;return {priority:typeof r.priority=="string"?r.priority:null,state:typeof r.state=="string"?r.state:null}}function Qc(t,e,n){return t.get(sql`
|
|
377
|
+
`;writeFileSync(o,s,{encoding:"utf8",mode:384});}catch{}}),e.on("task:output",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=new Date().toISOString();appendFileSync(r,`[${o}] STDOUT: ${n.output}
|
|
378
|
+
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=ts(new Date),s=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${o}] INFO: Task ${s} in ${n.durationMs}ms
|
|
379
|
+
[${o}] INFO: Process closed with exit code: ${n.error?1:0}
|
|
380
|
+
`;appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};g();g();var ka=Symbol.for("crewx.interceptor.run-stops");function Bl(){let t=globalThis,e=t[ka];if(e)return e;let n=new Map;return t[ka]=n,n}function ya(t){let e=Bl().get(t);return e?(e.abort(),true):false}g();var hn=new Map;function Br(t){let e=Se.resolve(t);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(n,r)=>`${r.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function Ea(t){let e=Br(t);return createHash("sha256").update(e).digest("hex")}function Ra(t){let e=Br(t),n=hn.get(e);if(n!==void 0)return n;let r=e;try{let o=Se.join(e,".git");if(!lstatSync(o).isFile())return hn.set(e,r),r;let s=/^gitdir:\s*(.+?)\s*$/i.exec(readFileSync(o,"utf8").trim());if(!s)return hn.set(e,r),r;let i=s[1],c=Se.isAbsolute(i)?i:Se.resolve(Se.dirname(o),i),d=readFileSync(Se.join(c,"commondir"),"utf8").trim();if(!d)return hn.set(e,r),r;let u=Se.isAbsolute(d)?d:Se.resolve(c,d);if(Se.basename(u)!==".git"||!statSync(u).isDirectory())return hn.set(e,r),r;let l=Br(realpathSync.native(e)),p=Br(realpathSync.native(Se.dirname(u)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return hn.set(e,r),r}Ct();Hi();In();ki();Rr();$i();co();var fm=200,gm=200;function hm(t){if(typeof t!="object"||t===null||!("code"in t))return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function mm(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=hm(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function ol(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function km(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function sl(t){if(!t)return {};try{let e=JSON.parse(t);return km(e)?e:{}}catch{return {}}}function qn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var ym=new Set(["workflow","mcp"]),ta=class extends vt{name="sqlite-tracing";unsubs=[];dbPath;version;inheritWorktreeOwner;runnerIdentity;taskRepo;heartbeatTaskIds=new Set;ownedTaskRuns=new Map;ignoredDetachedTaskIds=new Set;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super();let n=process.env.CREWX_DB;this.dbPath=e?.dbRoot!==void 0?join(e.dbRoot,".crewx","crewx.db"):n??join(homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown",this.inheritWorktreeOwner=e?.inheritWorktreeOwner===true;let r=e?.runnerIdentity;this.runnerIdentity={detachedRunner:r?.detachedRunner===true,assignedTaskId:r?.detachedRunner===true&&r.assignedTaskId?.trim()||void 0};}attach(e){let n=new vr({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),o=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml")),s=this.inheritWorktreeOwner?Ra(r):r,i=o?Ea(s):null,c=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let u=d.callerAgentId??null,l=d.parentTaskId??null,p=d.rootTraceId??d.traceId,{detachedRunner:_,assignedTaskId:h}=this.runnerIdentity,m=h??d.traceId,k=qn(d.metadata?.runEpoch),E=_?"runner":"caller",P=d.workspaceId??i,w=_?n.getTask(m):void 0,L=d.pid??null,N={...d.metadata??{provider:d.provider??"cli/claude"},ownership:E,..._&&L!==null?{providerPid:L}:{}},b=JSON.stringify(N);if(_&&w?.status==="running"&&w.pid!==null&&k===0){this.ignoredDetachedTaskIds.add(m);return}n.startTask({id:m,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",actorKind:d.actorKind??null,actorId:d.actorId??null,pid:_?process.pid:L,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,securityKey:d.renderedPrompt==null?null:d.securityKey??null,command:c,codingAgentCommand:d.codingAgentCommand??null,workspaceId:P,projectId:d.projectId??null,callerAgentId:u,parentTaskId:l,traceId:p,metadata:b,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:m,runEpoch:k,ownership:E,..._?{providerPid:L}:{},runtime:{model:d.model??null,renderedPrompt:d.renderedPrompt??null,codingAgentCommand:d.codingAgentCommand??null,metadata:N}})?this.recordOwnedTaskRun({taskId:m,runEpoch:k,workspaceId:P,ownership:E}):console.warn("[crewx] task execution metadata not recorded",{taskId:m,runEpoch:k,ownership:E}),ym.has(d.platform??"cli")||Lu(n,{taskId:m,runEpoch:k,onStopRequested:Pe=>this.handleStopRequested(n,Pe)})&&this.heartbeatTaskIds.add(m);}catch(u){console.warn("[crewx] task:start tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:output",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;this.enqueueLog(u,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(u){let l={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(u,[l],ol(l));}}),e.on("task:run-update",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;let l=qn(d.runEpoch),p=this.runnerIdentity.detachedRunner;n.updateTaskOwnership({id:u,runEpoch:l,ownership:p?"runner":"caller",...p&&d.pid!==void 0?{providerPid:d.pid}:{},runtime:{...d.model!==void 0?{model:d.model}:{},...d.renderedPrompt!==void 0?{renderedPrompt:d.renderedPrompt}:{},...d.securityKey!==void 0?{securityKey:d.securityKey}:{},...d.codingAgentCommand!==void 0?{codingAgentCommand:d.codingAgentCommand}:{},...d.metadata?{metadata:d.metadata}:{}}}),!p&&d.pid!==void 0&&n.recordTaskPid({id:u,runEpoch:l,pid:d.pid});}catch(u){console.warn("[crewx] task:run-update tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:provider-input",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;n.recordProviderInput({id:u,runEpoch:d.runEpoch,input:d.input,keyWrapSkipped:d.keyWrapSkipped,interceptedRequest:d.interceptedRequest===!0,recordedAt:d.timestamp.toISOString()});}catch(u){console.warn("[crewx] task:provider-input tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:end",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.delete(u))return;let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null;this.removeOwnedTaskRun(u,qn(l)),Er(u,l)&&this.heartbeatTaskIds.delete(u),this.flushTaskLogs(u);let _=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{},...d.error.mode?{mode:d.error.mode}:{}}):null,h=d.result??null,m=!1,k=d.metadata?.suppressPartialResultRecovery===!0;if(d.error&&!k&&(!h||h.trim()==="")){let E=this.recoverPartialResult(u,d,l);E&&(h=E,m=!0);}n.finishTask({id:u,status:d.error?"failed":"success",result:h,error:_,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,usagePresent:d.inputTokens!==void 0||d.outputTokens!==void 0||d.cachedInputTokens!==void 0,usageComplete:d.usageComplete,model:d.model??null,runEpoch:l,partialResultRecovered:m});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers();for(let n of this.heartbeatTaskIds)Er(n);this.heartbeatTaskIds.clear(),this.ownedTaskRuns.clear(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.ignoredDetachedTaskIds.clear(),this.taskRepo=void 0;}}listOwnedRunningTasks(){return Array.from(this.ownedTaskRuns.values(),e=>({...e}))}async stopOwnedRunningTasksForHostShutdown(){let e=this.taskRepo;if(!e)return;let n=this.listOwnedRunningTasks();for(let r of n)try{let o=await Fu(e,{taskId:r.taskId,expectedRunEpoch:r.runEpoch,workspaceId:r.workspaceId});(o.status==="failed"||o.status==="ownership_unverified")&&console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,status:o.status,...o.error?{error:o.error}:{}});}catch(o){console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,cause:o instanceof Error?o.name:typeof o});}}getMetrics(){let e=0,n=0;for(let r of this.queues.values())e+=r.entries.length,n+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:n}}resolveTaskId(e){return this.runnerIdentity.detachedRunner?this.runnerIdentity.assignedTaskId??e:e}recordOwnedTaskRun(e){let n=this.ownedTaskRuns.get(e.taskId);n&&n.runEpoch>e.runEpoch||this.ownedTaskRuns.set(e.taskId,{...e});}removeOwnedTaskRun(e,n){let r=this.ownedTaskRuns.get(e);!r||r.runEpoch!==n||this.ownedTaskRuns.delete(e);}enqueueLog(e,n){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(n),r.bytes+=ol(n),this.metrics.maxQueueEntries=Math.max(this.metrics.maxQueueEntries,r.entries.length),this.metrics.maxQueueBytes=Math.max(this.metrics.maxQueueBytes,r.bytes),r.entries.length>=fm){this.flushTaskLogs(e);return}if(!r.timer){let o=setTimeout(()=>{let s=this.queues.get(e);!s||s.timer!==o||(s.timer=void 0,this.flushTaskLogs(e));},gm);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo;if(!o)return;let s=o.getTask(e);if(!s||s.status!=="running"||qn(s.run_epoch)!==qn(r))return;let i=sl(s.metadata),c=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!c)return;let d=Co({taskLogRepository:o,taskId:e,provider:c,model:s.model});if(!d?.adapter.extractPartialText)return;let u=d.adapter.extractPartialText(d.stdout);return !u||!u.trim()||kt(u,c)?void 0:u}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let o=qn(n.run_epoch),s=sl(n.metadata??null),i=s.ownership==="runner"?"runner":"caller";if(i==="runner"&&n.pid!==process.pid){console.warn("[crewx] ignored stop request for task owned by another runner",{taskId:r});return}let c=typeof s.providerPid=="number"&&Number.isSafeInteger(s.providerPid)&&s.providerPid>0?s.providerPid:void 0,d=i==="runner"?c:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if(ya(r),d!==void 0){let u;try{u=await $t(d,{signal:Mt});}catch(l){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:l instanceof Error?l.name:typeof l});return}if(u.status==="failed"){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:u.error??"process termination failed"});return}}try{let u=e.finalizeTaskStop({id:r,runEpoch:o,method:Po(n.stop_requested_at)}),l=e.getTask(r);(u||l?.status!=="running")&&Er(r,o)&&this.heartbeatTaskIds.delete(r);}catch(u){console.warn("[crewx] cooperative task stop finalization failed",{taskId:r,cause:u instanceof Error?u.name:typeof u});}}flushTaskLogs(e){let n=this.queues.get(e);if(!n||n.entries.length===0){n?.timer&&clearTimeout(n.timer),this.queues.delete(e);return}n.timer&&(clearTimeout(n.timer),n.timer=void 0);let r=n.entries,o=n.bytes;n.entries=[],n.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(i){this.recordAppendFailure(i,r,o);}let s=this.queues.get(e);s&&s.entries.length===0&&(s.timer&&clearTimeout(s.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,n,r){let o=mm(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=n.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[o.code]=(this.metrics.appendFailureByCode[o.code]??0)+1,this.metrics.appendFailureByCause[o.cause]=(this.metrics.appendFailureByCause[o.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:o.code,cause:o.cause,pendingEntries:n.length,pendingBytes:r});}};g();g();g();xt();zt();Jt();Ct();on();ro();yr();g();function Bo(t){return t!==null&&t!==""}function Tm(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":Bo(t.parent_task_id)||Bo(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function il(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&Bo(e)?e:null}}function Wo(t){let e=Tm(t),n=Bo(t.caller_agent_id)?t.caller_agent_id:null,r=t.parent_thread_id!==null&&t.parent_thread_id!==t.thread_id;return {origin:e==="human"?"direct":"delegated",delegatedByAgentId:e==="agent"?n??(r&&t.parent_agent_id||null):null}}function al(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?il(t.creator_actor_kind,t.creator_actor_id):e?Wo(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?il(t.created_by_kind,t.created_by_id):n?Wo(n):void 0}function xr(t){return kr(t)}function Am({metadata:t,...e}){return {...e,status:qe({...e,metadata:t}),terminalReason:ot({...e,metadata:t})??null}}var br=32,cl=100,Nm=["running","failed"];function Om(t){return t==="running"?0:t==="failed"?1:2}function ul(t,e){return t[0]!==e[0]?t[0]-e[0]:t[1]!==e[1]?t[1]===null?1:e[1]===null||t[1]<e[1]?-1:1:t[2]<e[2]?-1:t[2]>e[2]?1:0}function vm(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function Cm(t){try{let e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(Array.isArray(e)&&e.length===3&&Number.isInteger(e[0])&&e[0]>=0&&e[0]<=2&&(e[1]===null||typeof e[1]=="string")&&typeof e[2]=="string")return [e[0],e[1],e[2]]}catch{}throw new f("VALIDATION","Invalid descendant cursor")}function ll(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function na(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function xm(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function ra(t,e,n,r){let o=xm(e);o&&(t[o]+=r,t.total+=r,o==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var jo=900,pl=20;function _l(t,e){return (t?.origin??"direct")===e}function fl(t,e){let n=new Date(e.updated_at).getTime()-new Date(t.updated_at).getTime();return n!==0?n:t.id.localeCompare(e.id)}var Fn=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function Bn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function bm(t){let n=Bn(t).threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {priority:null,state:null};let r=n;return {priority:typeof r.priority=="string"?r.priority:null,state:typeof r.state=="string"?r.state:null}}function gl(t,e,n){return t.get(sql`
|
|
368
381
|
SELECT id
|
|
369
382
|
FROM tasks INDEXED BY idx_tasks_thread_id
|
|
370
383
|
WHERE thread_id = ${e}
|
|
371
384
|
AND id <> ${n}
|
|
372
385
|
LIMIT 1
|
|
373
|
-
`)!==void 0}function
|
|
386
|
+
`)!==void 0}function Dm(t,e,n){let r=n?and(eq(y.id,e),eq(y.workspace_id,n)):eq(y.id,e),o=t.select({pinned:y.pinned,metadata:y.metadata}).from(y).where(r).get();if(!o)return null;let s=o.pinned?0:1,i=Bn(o.metadata);if(s){let c=n?and(eq(y.pinned,1),eq(y.workspace_id,n)):eq(y.pinned,1),d=t.select({metadata:y.metadata}).from(y).where(c).all(),u=null;for(let l of d){let p=Bn(l.metadata);typeof p.pinOrder=="number"&&(u===null||p.pinOrder<u)&&(u=p.pinOrder);}i.pinOrder=u===null?0:u-1;}else delete i.pinOrder;return t.update(y).set({pinned:s,metadata:Object.keys(i).length>0?JSON.stringify(i):null}).where(r).run(),{pinned:!!s}}function Pm(t,e,n){for(let r=0;r<e.length;r++){let o=n?and(eq(y.id,e[r]),eq(y.workspace_id,n)):eq(y.id,e[r]),s=t.select({metadata:y.metadata}).from(y).where(o).get();if(!s)continue;let i=Bn(s.metadata);i.pinOrder=r+1,t.update(y).set({metadata:JSON.stringify(i)}).where(o).run();}}var Ko=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?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}topLevelTaskPredicateSql(e="child",n){let r=n?`tasks parent INDEXED BY ${n}`:"tasks parent";return sql.raw(`NOT EXISTS (
|
|
374
387
|
SELECT 1 FROM ${r}
|
|
375
388
|
WHERE parent.id = ${e}.parent_task_id
|
|
376
389
|
AND parent.thread_id = ${e}.thread_id
|
|
377
|
-
)`)}workflowAnchorPredicateSql(e){let n=
|
|
390
|
+
)`)}workflowAnchorPredicateSql(e){let n=Pt.map(r=>`OR ${e}.metadata LIKE '%"kind":"${r}"%'`).join(`
|
|
378
391
|
`);return sql.raw(`COALESCE(
|
|
379
392
|
${e}.agent_id = 'workflow'
|
|
380
393
|
${n}
|
|
@@ -411,19 +424,19 @@ Message: ${n.message}
|
|
|
411
424
|
EXISTS (SELECT 1 FROM own_tasks own WHERE own.task_id = ${n}.id)
|
|
412
425
|
AND ${this.topLevelTaskPredicateSql(e)}
|
|
413
426
|
)
|
|
414
|
-
)`}findAllThreadsQuery(e,n){let r=[];e&&r.push(sql`workspace_id = ${e}`),n&&r.push(sql`created_by_kind = ${n}`);let
|
|
427
|
+
)`}findAllThreadsQuery(e,n){let r=[];e&&r.push(sql`workspace_id = ${e}`),n&&r.push(sql`created_by_kind = ${n}`);let o=r.length>0?sql` WHERE ${sql.join(r,sql` AND `)}`:sql``;return sql`SELECT * FROM threads${o} ORDER BY updated_at DESC`}findThreadIdsQuery(e){return e?sql`SELECT id FROM threads INDEXED BY idx_threads_ws_updated
|
|
415
428
|
WHERE workspace_id = ${e}
|
|
416
|
-
ORDER BY updated_at DESC`:sql`SELECT id FROM threads`}readThreadIds(e,n="Failed to find thread ids"){let r=this.resolveDbPaths(),
|
|
429
|
+
ORDER BY updated_at DESC`:sql`SELECT id FROM threads`}readThreadIds(e,n="Failed to find thread ids"){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let c=q(i);try{let d=c.db.all(this.findThreadIdsQuery(e));for(let u of d)o.has(u.id)||(o.add(u.id),s.push(u.id));}catch(d){throw new f("DB_ERROR",n,d)}finally{c.close();}}return s}findThreadSortKeysQuery(e){return sql`SELECT id, updated_at
|
|
417
430
|
FROM threads INDEXED BY idx_threads_ws_updated
|
|
418
|
-
WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,
|
|
431
|
+
WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!existsSync(s))continue;let i=q(s);try{let c=i.db.all(this.findThreadSortKeysQuery(e));for(let d of c)r.has(d.id)||(r.add(d.id),o.push(d));}catch(c){throw new f("DB_ERROR","Failed to find recent direct threads",c)}finally{i.close();}}return o}readThreadRowsByIds(e,n,r="Failed to find threads by ids"){if(e.length===0)return [];let o=this.resolveDbPaths(),s=new Set,i=[];for(let c of o){if(!existsSync(c))continue;let d=q(c);try{for(let u=0;u<e.length;u+=jo){let l=e.slice(u,u+jo),p=inArray(y.id,l),_=n?and(p,eq(y.workspace_id,n)):p,h=d.db.select().from(y).where(_).all();for(let m of h)s.has(m.id)||(s.add(m.id),i.push(m));}}catch(u){throw new f("DB_ERROR",r,u)}finally{d.close();}}return i}readThreadRows(e,n,r="Failed to find all threads"){let o=this.resolveDbPaths(),s=new Set,i=[];for(let c of o){if(!existsSync(c))continue;let d=q(c);try{let u=d.db.all(this.findAllThreadsQuery(e,n));for(let l of u)s.has(l.id)||(s.add(l.id),i.push(l));}catch(u){throw new f("DB_ERROR",r,u)}finally{d.close();}}return i}findAllThreads(e,n){return this.readThreadRows(e,n)}explainFindAllThreadsPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=q(o);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.findAllThreadsQuery(e,n)}`).map(c=>c.detail)}finally{s.close();}}return []}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let c=q(i);try{let d=or$1(inArray(y.id,e),inArray(y.title,e)),u=n?and(d,eq(y.workspace_id,n)):d,l=c.db.select().from(y).where(u).orderBy(desc(y.updated_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(p));}catch(d){throw new f("DB_ERROR","Failed to find threads by ids or titles",d)}finally{c.close();}}return s}findThreadById(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=q(o);try{let i=eq(y.id,e),c=n?and(i,eq(y.workspace_id,n)):i,d=s.db.select().from(y).where(c).limit(1).get()??void 0;if(d)return d}catch(i){throw new f("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}createAppLaunchThread(e){let n=this.openHandle(true);try{return n.db.transaction(r=>{if(!r.select({id:de.id}).from(de).where(eq(de.id,e.workspaceId)).limit(1).get())throw new f("NOT_FOUND","Workspace not found");let s=r.select().from(y).where(eq(y.id,e.threadId)).limit(1).get();if(s){let l=Bn(s.metadata).appLaunch,p=l&&typeof l=="object"&&!Array.isArray(l)?l.appId:void 0,_=r.get(sql`
|
|
419
432
|
SELECT COUNT(*) AS count FROM tasks WHERE thread_id = ${e.threadId}
|
|
420
|
-
`)?.count??0;return
|
|
433
|
+
`)?.count??0;return s.workspace_id===e.workspaceId&&p===e.appId&&s.message_count===0&&s.first_message===null&&s.last_message===null&&_===0?{status:"existing",thread:s}:{status:"conflict"}}let i=new Date().toISOString(),c=JSON.stringify({appLaunch:{appId:e.appId,...e.initialAgentId===void 0?{}:{initialAgentId:e.initialAgentId}}});r.insert(y).values({id:e.threadId,workspace_id:e.workspaceId,platform:e.platform,title:e.title,title_locked:1,created_by_kind:"human",created_by_id:e.createdById,created_by_task_id:null,message_count:0,first_message:null,last_message:null,metadata:c,created_at:i,updated_at:i}).run();let d=r.select().from(y).where(eq(y.id,e.threadId)).limit(1).get();if(!d)throw new f("DB_ERROR","App-launch thread could not be read after insert");return {status:"created",thread:d}},{behavior:"immediate"})}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to create App-launch thread",r)}finally{n.close();}}threadExists(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=q(o);try{let i=eq(y.id,e),c=n?and(i,eq(y.workspace_id,n)):i;if(s.db.select({id:y.id}).from(y).where(c).limit(1).get())return !0}catch(i){throw new f("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),o=0,s=0,i=0,c=0,d=0,u=0,l=0,p=0,_=0,h=0,m=new Set;for(let k of r){if(!existsSync(k))continue;let E=q(k);try{let P=E.db.get(sql`
|
|
421
434
|
SELECT count(*) AS cnt
|
|
422
435
|
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
423
436
|
WHERE child.thread_id = ${e}
|
|
424
437
|
AND ${this.topLevelTaskPredicateSql()}
|
|
425
438
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
426
|
-
`);
|
|
439
|
+
`);P&&(o+=P.cnt);let w=E.db.get(sql`
|
|
427
440
|
SELECT
|
|
428
441
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
429
442
|
COALESCE(SUM(child.output_tokens), 0) AS total_output,
|
|
@@ -432,7 +445,7 @@ Message: ${n.message}
|
|
|
432
445
|
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
433
446
|
WHERE child.thread_id = ${e}
|
|
434
447
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
435
|
-
`);w&&(
|
|
448
|
+
`);w&&(s+=w.total_input,i+=w.total_output,c+=w.total_cached,d+=w.total_cost);let L=E.db.get(sql`
|
|
436
449
|
WITH RECURSIVE
|
|
437
450
|
own_tasks(task_id) AS (
|
|
438
451
|
SELECT own.id
|
|
@@ -447,7 +460,7 @@ Message: ${n.message}
|
|
|
447
460
|
FROM descendants
|
|
448
461
|
JOIN tasks child INDEXED BY idx_tasks_parent_task_id
|
|
449
462
|
ON child.parent_task_id = descendants.task_id
|
|
450
|
-
WHERE descendants.depth < ${
|
|
463
|
+
WHERE descendants.depth < ${br}
|
|
451
464
|
),
|
|
452
465
|
delegated_ids(task_id) AS (
|
|
453
466
|
SELECT DISTINCT descendants.task_id
|
|
@@ -466,20 +479,20 @@ Message: ${n.message}
|
|
|
466
479
|
COALESCE(SUM(task.cost_usd), 0) AS total_cost
|
|
467
480
|
FROM delegated_ids
|
|
468
481
|
JOIN tasks task ON task.id = delegated_ids.task_id
|
|
469
|
-
`);
|
|
482
|
+
`);L&&(u+=L.cnt,l+=L.total_input,p+=L.total_output,_+=L.total_cached,h+=L.total_cost);let N=E.db.all(sql`
|
|
470
483
|
SELECT DISTINCT child.agent_id FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
471
484
|
WHERE child.thread_id = ${e}
|
|
472
485
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
473
486
|
AND child.agent_id != 'workflow'
|
|
474
487
|
AND ${this.topLevelTaskPredicateSql()}
|
|
475
488
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
476
|
-
`);for(let b of
|
|
489
|
+
`);for(let b of N)m.add(b.agent_id);}catch(P){throw new f("DB_ERROR","Failed to aggregate task stats",P)}finally{E.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:c,costUsd:d,agentIds:Array.from(m),delegated:{taskCount:u,inputTokens:l,outputTokens:p,cachedInputTokens:_,costUsd:h}}}getDescendantSummaryByTaskId(e,n){let r=this.resolveDbPaths(),o={},s=new Date().toISOString();for(let i of r){if(!existsSync(i))continue;let c=q(i);try{let d=sql`
|
|
477
490
|
SELECT own.id
|
|
478
491
|
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
479
492
|
WHERE own.thread_id = ${e}
|
|
480
493
|
${n?sql`AND own.workspace_id = ${n}`:sql``}
|
|
481
|
-
`,c
|
|
482
|
-
${this.descendantTraversalSql(d,sql`SELECT own.task_id FROM own_tasks own`,
|
|
494
|
+
`,u=c.db.all(sql`
|
|
495
|
+
${this.descendantTraversalSql(d,sql`SELECT own.task_id FROM own_tasks own`,br)}
|
|
483
496
|
SELECT
|
|
484
497
|
descendant_ids.root_task_id AS root_task_id,
|
|
485
498
|
task.status AS status,
|
|
@@ -490,26 +503,26 @@ Message: ${n.message}
|
|
|
490
503
|
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
491
504
|
WHERE NOT ${this.descendantSkippedSql("task")}
|
|
492
505
|
GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
|
|
493
|
-
`);for(let l of
|
|
506
|
+
`);for(let l of u){let p=o[l.root_task_id]??=na(s);ra(p,qe(l),ot(l),l.task_count);}}catch(d){throw new f("DB_ERROR","Failed to aggregate task descendant summaries",d)}finally{c.close();}}return o}listUnreadReplyCandidates(e,n){let r=new Map,o=new Map;for(let{threadId:i,readThroughAt:c}of e)c!==null&&o.set(i,c);if(o.size===0)return r;let s=new Set;for(let i of this.resolveDbPaths()){if(!existsSync(i))continue;let c=q(i);try{let d=c.db.all(this.unreadReplyCandidatesQuery(o,n));for(let u of d){if(s.has(u.id))continue;s.add(u.id);let l={id:u.id,threadId:u.thread_id,completedAt:u.completed_at,status:qe(u),result:u.result,error:u.error,metadata:u.metadata},p=r.get(u.thread_id);p?p.push(l):r.set(u.thread_id,[l]);}}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to list unread reply candidates",d)}finally{c.close();}}return r}unreadReplyCandidatesQuery(e,n){let r=sql.join([...e].map(([s,i])=>sql`(${s}, ${i})`),sql`, `),o=sql.join(pn.map(s=>sql`${s}`),sql`, `);return sql`
|
|
494
507
|
WITH watermarks(thread_id, read_through_at) AS (VALUES ${r})
|
|
495
508
|
SELECT child.id, child.thread_id, child.completed_at, child.status,
|
|
496
509
|
child.result, child.error, child.metadata
|
|
497
510
|
FROM watermarks w
|
|
498
511
|
JOIN tasks child INDEXED BY idx_tasks_thread_id ON child.thread_id = w.thread_id
|
|
499
512
|
WHERE julianday(child.completed_at) > julianday(w.read_through_at)
|
|
500
|
-
AND child.status IN (${
|
|
513
|
+
AND child.status IN (${o})
|
|
501
514
|
AND ${this.topLevelTaskPredicateSql()}
|
|
502
515
|
AND NOT ${this.workflowAnchorPredicateSql("child")}
|
|
503
516
|
AND COALESCE(length(child.result), 0) > 0
|
|
504
517
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
505
518
|
ORDER BY julianday(child.completed_at), child.id
|
|
506
|
-
`}getThreadTaskStatusBatch(e,n){let r=[...new Set(e)];if(r.length===0)return {tasksByThread:new Map,descendantSummaryByTaskId:{}};let
|
|
519
|
+
`}getThreadTaskStatusBatch(e,n){let r=[...new Set(e)];if(r.length===0)return {tasksByThread:new Map,descendantSummaryByTaskId:{}};let o=this.batchFetchTasks(r,n),s={},i=new Date().toISOString(),c=sql.join(r.map(u=>sql`${u}`),sql`, `),d=sql`
|
|
507
520
|
SELECT own.id
|
|
508
521
|
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
509
|
-
WHERE own.thread_id IN (${
|
|
522
|
+
WHERE own.thread_id IN (${c})
|
|
510
523
|
${n?sql`AND own.workspace_id = ${n}`:sql``}
|
|
511
|
-
`;for(let
|
|
512
|
-
${this.descendantTraversalSql(d,sql`SELECT own.task_id FROM own_tasks own`,
|
|
524
|
+
`;for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let l=q(u);try{let p=l.db.all(sql`
|
|
525
|
+
${this.descendantTraversalSql(d,sql`SELECT own.task_id FROM own_tasks own`,br)}
|
|
513
526
|
SELECT
|
|
514
527
|
descendant_ids.root_task_id AS root_task_id,
|
|
515
528
|
task.status AS status,
|
|
@@ -520,7 +533,7 @@ Message: ${n.message}
|
|
|
520
533
|
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
521
534
|
WHERE NOT ${this.descendantSkippedSql("task")}
|
|
522
535
|
GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
|
|
523
|
-
`);for(let
|
|
536
|
+
`);for(let _ of p){let h=s[_.root_task_id]??=na(i);ra(h,qe(_),ot(_),_.task_count);}}catch(p){throw p instanceof f?p:new f("DB_ERROR","Failed to batch summarize thread task statuses",p)}finally{l.close();}}return {tasksByThread:o,descendantSummaryByTaskId:s}}listDescendantsByTaskId(e,n,r={}){let o=new Set(r.states??Nm),s=ll(r.limit,cl,cl),i=ll(r.maxDepth,br,br),c=r.cursor?Cm(r.cursor):void 0;for(let d of this.resolveDbPaths()){if(!existsSync(d))continue;let u=q(d);try{if(!u.db.get(sql`
|
|
524
537
|
SELECT anchor.id FROM tasks anchor
|
|
525
538
|
WHERE anchor.id = ${e} AND anchor.workspace_id = ${n}
|
|
526
539
|
`))continue;let p=sql`
|
|
@@ -531,7 +544,7 @@ Message: ${n.message}
|
|
|
531
544
|
WHERE anchor.id = ${e} AND anchor.workspace_id = ${n}
|
|
532
545
|
)
|
|
533
546
|
AND own.workspace_id = ${n}
|
|
534
|
-
`,
|
|
547
|
+
`,_=u.db.all(sql`
|
|
535
548
|
${this.descendantTraversalSql(p,sql`SELECT ${e}`,i)}
|
|
536
549
|
SELECT
|
|
537
550
|
task.id AS task_id,
|
|
@@ -554,11 +567,11 @@ Message: ${n.message}
|
|
|
554
567
|
FROM descendant_ids
|
|
555
568
|
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
556
569
|
LEFT JOIN tasks parent ON parent.id = task.parent_task_id
|
|
557
|
-
`),h=
|
|
570
|
+
`),h=na(new Date().toISOString()),m=!1,k=[];for(let b of _){if(b.has_deeper&&(m=!0),b.skipped)continue;let I=qe(b);ra(h,I,ot(b),1),o.has(I)&&k.push({row:b,key:[Om(I),b.started_at?b.started_at:null,b.task_id]});}k.sort((b,I)=>ul(b.key,I.key));let E=c?k.filter(b=>ul(b.key,c)>0):k,P=E.slice(0,s),w=E.length>P.length?vm(P[P.length-1].key):null,L=new Map;if(P.length>0){let b=u.db.select(ce).from(a).where(inArray(a.id,P.map(I=>I.row.task_id))).all();for(let I of b)L.set(I.id,xr(I));}let N=[];for(let{row:b}of P){let I=L.get(b.task_id);!I||!b.parent_task_id||N.push({task:I,parentTaskId:b.parent_task_id,parentAgentId:b.parent_agent_id,depth:b.depth});}return {rows:N,summary:h,nextCursor:w,traversalTruncated:m}}catch(l){throw l instanceof f?l:new f("DB_ERROR","Failed to list task descendants",l)}finally{u.close();}}}findInterceptedRequests(e){let n=new Map;if(e.length===0)return n;for(let r of this.resolveDbPaths()){if(!existsSync(r))continue;let o=q(r);try{let s=o.db.all(sql`
|
|
558
571
|
SELECT task_id, input FROM task_provider_inputs
|
|
559
572
|
WHERE run_epoch = 0
|
|
560
573
|
AND task_id IN (${sql.join(e.map(i=>sql`${i}`),sql`, `)})
|
|
561
|
-
`);for(let i of
|
|
574
|
+
`);for(let i of s)n.set(i.task_id,i.input);}catch{}finally{o.close();}}return n}findTopLevelTasks(e,n,r,o){let s=this.resolveDbPaths(),i=o?sql`(${this.topLevelTaskPredicateSql()} OR child.agent_id = ${o})`:this.topLevelTaskPredicateSql(),c=new Set,d=[];for(let u of s){if(!existsSync(u))continue;let l=q(u);try{let p;r!==void 0?p=l.db.all(sql`
|
|
562
575
|
SELECT * FROM (
|
|
563
576
|
SELECT child.*,
|
|
564
577
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -575,7 +588,7 @@ Message: ${n.message}
|
|
|
575
588
|
AND ${i}
|
|
576
589
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
577
590
|
ORDER BY child.started_at ASC
|
|
578
|
-
`);for(let
|
|
591
|
+
`);for(let _ of p)c.has(_.id)||(c.add(_.id),d.push(xr(_)));}catch(p){throw new f("DB_ERROR","Failed to find top-level tasks",p)}finally{l.close();}}if(r!==void 0&&s.length>1){let u=new Map;for(let l of d){let p=l.agent_id??"";u.has(p)||u.set(p,[]),u.get(p).push(l);}d=[];for(let l of u.values())l.sort((p,_)=>(_.started_at??"").localeCompare(p.started_at??"")),d.push(...l.slice(0,r));d.sort((l,p)=>(l.started_at??"").localeCompare(p.started_at??""));}return d}findAllTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let c=q(i);try{let d=eq(a.thread_id,e),u=n?and(d,eq(a.workspace_id,n)):d,l=c.db.select(ce).from(a).where(u).orderBy(asc(a.started_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(xr(p)));}catch(d){throw new f("DB_ERROR","Failed to find all tasks for thread",d)}finally{c.close();}}return s}findRespondedAgents(e,n){let r=this.resolveDbPaths(),o=new Map;for(let s of r){if(!existsSync(s))continue;let i=q(s,{readOnly:true});try{let c=[eq(a.thread_id,e),sql`${a.completed_at} IS NOT NULL`,sql`length(trim(coalesce(${a.result}, ''))) > 0`];n&&c.push(eq(a.workspace_id,n));let d=i.db.select({agentId:a.agent_id,lastRepliedAt:sql`MAX(${a.completed_at})`}).from(a).where(and(...c)).groupBy(a.agent_id).all();for(let u of d){let l=o.get(u.agentId);u.lastRepliedAt&&(!l||u.lastRepliedAt>l)&&o.set(u.agentId,u.lastRepliedAt);}}catch(c){throw new f("DB_ERROR","Failed to find responded agents for thread",c)}finally{i.close();}}return [...o.entries()].map(([s,i])=>({agentId:s,lastRepliedAt:i})).sort((s,i)=>(s.lastRepliedAt===i.lastRepliedAt?0:s.lastRepliedAt>i.lastRepliedAt?-1:1)||(s.agentId===i.agentId?0:s.agentId<i.agentId?-1:1))}findTaskById(e,n,r){let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=q(s);try{let c=and(eq(a.id,n),eq(a.thread_id,e)),d=r?and(c,eq(a.workspace_id,r)):c,u=i.db.select(ce).from(a).where(d).limit(1).get();if(!u)continue;let l=i.db.select(ce).from(a).where(eq(a.parent_task_id,u.id)).orderBy(asc(a.started_at)).all().map(xr);return {task:xr(u),children:l}}catch(c){throw new f("DB_ERROR","Failed to find task by id",c)}finally{i.close();}}}batchFetchTasksQuery(e,n){return sql`
|
|
579
592
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
580
593
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
581
594
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -585,7 +598,7 @@ Message: ${n.message}
|
|
|
585
598
|
AND ${this.topLevelTaskPredicateSql()}
|
|
586
599
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
587
600
|
ORDER BY child.started_at ASC
|
|
588
|
-
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let
|
|
601
|
+
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=q(s);try{let c=i.db.all(this.batchFetchTasksQuery(e,n));for(let d of c){let u=d.thread_id;r.has(u)||r.set(u,[]),r.get(u).push(Am(d));}}catch(c){throw new f("DB_ERROR","Failed to batch fetch tasks",c)}finally{i.close();}}return r}findThreadOriginsQuery(e,n){return sql`
|
|
589
602
|
WITH root AS (
|
|
590
603
|
SELECT child.thread_id, child.id, child.caller_agent_id, child.parent_task_id,
|
|
591
604
|
CASE
|
|
@@ -610,7 +623,7 @@ Message: ${n.message}
|
|
|
610
623
|
LEFT JOIN tasks parent INDEXED BY idx_tasks_thread_creator
|
|
611
624
|
ON parent.id = root.parent_task_id
|
|
612
625
|
WHERE root.rn = 1
|
|
613
|
-
`}findCreatorPointersQuery(e,n){let r=[sql`thread.id IN (${sql.join(e.map(
|
|
626
|
+
`}findCreatorPointersQuery(e,n){let r=[sql`thread.id IN (${sql.join(e.map(o=>sql`${o}`),sql`, `)})`];return n&&r.unshift(sql`thread.workspace_id = ${n}`),sql`
|
|
614
627
|
SELECT thread.id AS thread_id, thread.created_by_kind, thread.created_by_id,
|
|
615
628
|
thread.created_by_task_id,
|
|
616
629
|
creator.id AS creator_task_id,
|
|
@@ -637,19 +650,19 @@ Message: ${n.message}
|
|
|
637
650
|
FROM tasks AS child
|
|
638
651
|
LEFT JOIN tasks AS parent ON parent.id = child.parent_task_id
|
|
639
652
|
WHERE child.id IN (${sql.join(e.map(n=>sql`${n}`),sql`, `)})
|
|
640
|
-
`}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let
|
|
653
|
+
`}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=q(s);try{for(let c=0;c<e.length;c+=jo){let d=e.slice(c,c+jo),l=i.db.all(this.findCreatorPointersQuery(d,n)).filter(w=>!r.has(w.thread_id)),p=l.filter(w=>w.creator_task_id!==null&&w.creator_pointer_unverified===0&&w.creator_actor_kind===null).map(w=>w.creator_task_id),_=p.length>0?i.db.all(this.findTaskOriginLineageQuery(p)):[],h=new Map(_.map(w=>[w.task_id,w])),m=new Map(l.map(w=>[w.thread_id,w])),k=d.filter(w=>{if(r.has(w))return !1;let L=m.get(w);return L?!(L.creator_task_id!==null&&L.creator_pointer_unverified===0)&&L.created_by_kind===null:!0}),E=k.length>0?i.db.all(this.findThreadOriginsQuery(k,n)):[],P=new Map(E.map(w=>[w.thread_id,w]));for(let w of l){if(r.has(w.thread_id))continue;let L=al(w,w.created_by_task_id!==null?h.get(w.created_by_task_id):void 0,P.get(w.thread_id));L&&r.set(w.thread_id,L);}for(let w of E)r.has(w.thread_id)||m.has(w.thread_id)||r.set(w.thread_id,Wo(w));}}catch(c){throw new f("DB_ERROR","Failed to fetch thread origins",c)}finally{i.close();}}return r}findThreadsByOrigin(e,n){let r=this.readThreadIds(n,"Failed to find threads by origin"),o=this.findThreadOrigins(r,n),s=r.filter(c=>_l(o.get(c),e));return this.readThreadRowsByIds(s,n,"Failed to find threads by origin").sort(fl)}findRecentDirectThreads(e,n=5){if(typeof e!="string"||e.trim().length===0)throw new f("VALIDATION","workspaceId is required");if(!Number.isInteger(n)||n<=0)throw new f("VALIDATION","limit must be a positive integer");let r=this.readThreadSortKeys(e).sort(fl),o=[],s=new Map;for(let u=0;u<r.length;u+=pl){let l=r.slice(u,u+pl),p=this.findThreadOrigins(l.map(_=>_.id),e);for(let[_,h]of p)s.set(_,h);for(let _ of l)if(_l(p.get(_.id),"direct")&&(o.push(_.id),o.length===n))break;if(o.length===n)break}let i=new Map;if(o.length>0){let u=this.readThreadRowsByIds(o,e,"Failed to find recent direct threads");for(let l of u)i.set(l.id,l);}let c=[],d=new Map;for(let u of o){let l=i.get(u);if(!l)continue;c.push(l);let p=s.get(u);p&&d.set(u,p);}return {threads:c,originsByThread:d}}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=q(o);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(c=>c.detail)}finally{s.close();}}return []}explainFindThreadOriginsPlan(e,n){if(e.length===0)return [];let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=q(o);try{let i=s.db.all(sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery(e,n)}`),c=s.db.all(sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery(e)}`),d=s.db.all(sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery(e,n)}`);return [...i,...c,...d].map(u=>u.detail)}finally{s.close();}}return []}explainFindThreadsByOriginPlan(e,n){let r=`__thread_origin_${e}_plan__`,o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=q(s);try{let c=i.db.all(sql`EXPLAIN QUERY PLAN ${this.findThreadIdsQuery(n)}`),d=i.db.all(sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery([r],n)}`),u=i.db.all(sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery([r])}`),l=i.db.all(sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery([r],n)}`);return [...c,...d,...u,...l].map(p=>p.detail)}finally{i.close();}}return []}updateThreadTitle(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=eq(y.id,e),i=r?and(s,eq(y.workspace_id,r)):s;if(!o.db.select({id:y.id}).from(y).where(i).limit(1).get())return;o.db.update(y).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(eq(y.id,e)).run();}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>{let i=(n.workspaceId?o.select({id:de.id}).from(de).where(eq(de.id,n.workspaceId)).limit(1).get():void 0)?n.workspaceId:null,c=new Date().toISOString(),d=o.select({id:y.id,message_count:y.message_count,created_by_task_id:y.created_by_task_id}).from(y).where(eq(y.id,e)).limit(1).get();if(d){let u={updated_at:c};n.title!==void 0&&(u.title=n.title),n.titleLocked!==void 0&&(u.title_locked=n.titleLocked?1:0),d.created_by_task_id===null&&n.createdByTaskId!=null&&d.message_count===0&&!gl(o,e,n.createdByTaskId)&&(u.created_by_task_id=n.createdByTaskId),o.update(y).set(u).where(eq(y.id,e)).run();}else o.insert(y).values({id:e,platform:n.platform,workspace_id:i,created_by_kind:null,created_by_id:null,created_by_task_id:n.createdByTaskId??null,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:c,updated_at:c}).run();},{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to upsert thread",o)}finally{r.close();}}ensureThread(e,n,r,o){let s=this.openHandle(true);try{s.db.transaction(i=>{let d=(r?i.select({id:de.id}).from(de).where(eq(de.id,r)).limit(1).get():void 0)?r:null,u=i.select({id:y.id,platform:y.platform,workspace_id:y.workspace_id,message_count:y.message_count,created_by_task_id:y.created_by_task_id}).from(y).where(eq(y.id,e)).limit(1).get();if(u){let p={};d&&!u.workspace_id&&(p.workspace_id=d),u.created_by_task_id===null&&o?.createdByTaskId!=null&&u.message_count===0&&!gl(i,e,o.createdByTaskId)&&(p.created_by_task_id=o.createdByTaskId),Object.keys(p).length>0&&i.update(y).set(p).where(eq(y.id,e)).run();return}let l=new Date().toISOString();i.insert(y).values({id:e,platform:n,workspace_id:d,created_by_kind:null,created_by_id:null,created_by_task_id:o?.createdByTaskId??null,message_count:0,created_at:l,updated_at:l}).run();},{behavior:"immediate"});}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to ensure thread",i)}finally{s.close();}}saveUserMessage(e,n,r){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:o.db.transaction(c=>{let u=c.select({message_count:y.message_count}).from(y).where(eq(y.id,e)).limit(1).get()?.message_count===0;return c.run(sql`
|
|
641
654
|
UPDATE threads
|
|
642
655
|
SET first_message = COALESCE(first_message, ${n}),
|
|
643
656
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
644
657
|
last_message = ${n},
|
|
645
658
|
message_count = message_count + 1,
|
|
646
|
-
updated_at = ${
|
|
659
|
+
updated_at = ${s}
|
|
647
660
|
WHERE id = ${e}
|
|
648
|
-
`),c},{behavior:"immediate"})}}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to save user message",o)}finally{s.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.update(T).set({last_message:n,updated_at:o}).where(eq(T.id,e)).run();}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to save assistant message",o)}finally{s.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};n.title!==void 0&&(s.title=n.title,s.title_locked=1),n.titleLocked!==void 0&&(s.title_locked=n.titleLocked?1:0),r.db.update(T).set(s).where(eq(T.id,e)).run();}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to update thread",s)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let s=n;if(!s||typeof s!="object"||Array.isArray(s))return new xn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(s).some(d=>d!=="priority"&&d!=="state"))return new xn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=s;if(i.priority===void 0&&i.state===void 0)return new xn("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let d of [i.priority,i.state])if(d!=null&&(typeof d!="string"||d.length===0))return new xn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let u=this.openHandle(true);try{let d=r?and(eq(T.id,e),eq(T.workspace_id,r)):eq(T.id,e);return u.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(d).get();if(!l)return null;let p=Cn(l.metadata),f=p.threadTitle,h=f&&typeof f=="object"&&!Array.isArray(f)?{...f}:{};i.priority===null?delete h.priority:i.priority!==void 0&&(h.priority=i.priority),i.state===null?delete h.state:i.state!==void 0&&(h.state=i.state),Object.keys(h).length>0?p.threadTitle=h:delete p.threadTitle;let m=Object.keys(p).length>0?JSON.stringify(p):null,k=new Date().toISOString();c.update(T).set({metadata:m,updated_at:k}).where(d).run();let E=c.select({metadata:T.metadata}).from(T).where(d).get();if(!E)throw new g("DB_ERROR","Thread-title metadata update could not be read back");let x=dm(E.metadata);return {threadId:e,priority:x.priority,state:x.state}},{behavior:"immediate"})}catch(d){throw d instanceof g?d:new g("DB_ERROR","Failed to patch thread-title metadata",d)}finally{u.close();}}togglePin(e,n){let r=this.openHandle(true);try{return r.db.transaction(s=>um(s,e,n),{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to toggle pin",s)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(s=>cm(s,e,n),{behavior:"immediate"});}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to reorder pins",s)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let s=n?and(eq(T.id,e),eq(T.workspace_id,n)):eq(T.id,e),o=r.db.select({starred:T.starred}).from(T).where(s).get();if(!o)return null;let i=o.starred?0:1;return r.db.update(T).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to toggle star",s)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,s){let i=this.openHandle(true);try{let u=n?and(eq(T.id,e),eq(T.workspace_id,n)):eq(T.id,e);return i.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(u).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},f=p.overdrive??{},h=s?.defaultTurns??f.defaultTurns??3,m=s?.updatedBy??"ui",k=new Date().toISOString(),E,x,w,C;switch(r){case "enable-count":{let O=s?.turns??h,b=s?.consumeCurrent?Math.max(O-1,0):O;E=b>0?"count":"off",x=b,w=!0,C="count";break}case "enable-latch":{E="latch",x=0,w=!0,C="latch";break}case "disable":{E="off",x=0,w=!1;break}default:{let O=f.state??"off",b=typeof f.remaining=="number"?f.remaining:0;if(O==="count"&&b>0){let I=b-1;I<=0?(E="off",x=0):(E="count",x=I),w=!0,C="count";}else O==="latch"?(E="latch",x=0,w=!0,C="latch"):(E="off",x=0,w=!1);break}}return p.overdrive={state:E,remaining:x,defaultTurns:h,updatedAt:k,updatedBy:m},c.update(T).set({metadata:JSON.stringify(p),updated_at:k}).where(u).run(),{applied:w,appliedMode:C,state:E,remaining:x}},{behavior:"immediate"})}catch(u){throw u instanceof g?u:new g("DB_ERROR","Failed to resolve overdrive",u)}finally{i.close();}}};_();St();Ut();qt();Rt();_();var Gi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function lm(t){let e=randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let s=e[r];s<248&&(n+=Gi[s%62]);}for(;n.length<t;)n+=Gi[randomBytes(1)[0]%62];return n}function wr(t){return `${t}_${lm(8)}`}function el(t,e){let{createHash:n}=on("crypto"),r=n("sha256").update(e).digest(),s=Buffer.alloc(8);for(let i=0;i<32;i++)s[i%8]^=r[i];let o="";for(let i of s)o+=Gi[i%62];return `${t}_${o}`}Vt();_();var pm=["urgent","high","medium","low"],fm=["investigating","in-progress","in-review","on-hold","done"],tl="custom:";var gm=new Set(pm),_m=new Set(fm);function ji(t){return typeof t=="string"&&gm.has(t)}function Ki(t){if(typeof t!="string")return false;if(_m.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(tl))return false;let e=t.slice(tl.length);return e.length>=1&&e.length<=20}function nl(t){if(!t)return null;try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function zi(t){let e=nl(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,s={};return ji(r.priority)&&(s.priority=r.priority),Ki(r.state)&&(s.state=r.state),s}function rl(t,e){let n=nl(t)??{},r={...zi(t)};return e.priority===null?delete r.priority:e.priority!==void 0&&(r.priority=e.priority),e.state===null?delete r.state:e.state!==void 0&&(r.state=e.state),r.priority===void 0&&r.state===void 0?delete n.threadTitle:n.threadTitle=r,Object.keys(n).length===0?null:JSON.stringify(n)}ar();var ym="regeneration_replaced";var wm="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Em="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Xi=class extends g{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,s){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${s}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=s;}},br=class extends Xi{},Yi=class extends g{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},Rm=new Set(ed),Sm=new Set(Za),Im=new Set(td),Am=new Set(nd),Om=50,ol=100,il=280,al=40,bm=new Set(rd),Ds=["queued","running"];function Vi(t){return bm.has(t)}function J(t){throw new g("VALIDATION",t)}function rt(t){throw new g("NOT_FOUND",t)}function H(t,e){(typeof t!="string"||t.trim().length===0)&&J(`${e} is required`);}function Rr(t={}){let e=t.actor??t,n=e.actorType??"system";return Rm.has(n)||J(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&J("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function vm(t){H(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&H(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&J("title must not be empty"),t.title.length>120&&J("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!ji(t.priority)&&J(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Ki(t.state)&&J(`invalid state: ${String(t.state)}`);}function Nm(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&J("beforeSeq and afterSeq cannot be used together");for(let[n,r]of [["beforeSeq",t.beforeSeq],["afterSeq",t.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&J(`${n} must be a non-negative integer`);let e=t.limit??Om;return (!Number.isInteger(e)||e<1||e>ol)&&J(`limit must be between 1 and ${ol}`),e}function Qi(t){typeof t!="string"&&J("text is required");let e=t.trim();return e.length===0&&J("text must not be empty"),e.length>il&&J(`text must be at most ${il} characters`),e}function yt(t,e){return H(t??"",e),t}function Zi(t){Am.has(t)||J(`invalid highlight kind: ${String(t)}`);}function xm(t){Im.has(t)||J(`invalid highlight source: ${String(t)}`);}function Cm(t){H(t.threadId,"threadId"),H(t.workspaceId,"workspaceId");let e=t.source??"manual";xm(e),Zi(t.kind);let n=Qi(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,s=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&s&&r===s?r:void 0),p=yt(l,"taskId");return (r!==p||s!==p)&&J("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let o=yt(r,"coversFromTaskId"),i=yt(s,"coversToTaskId"),u=t.sourceTaskId??o,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return yt(u??void 0,"sourceTaskId"),yt(d??void 0,"detectorVersion"),yt(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:o,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:u,detectorVersion:d,contentFingerprint:c}}function Dm(t,e){(!t||typeof t!="object")&&J(`candidates[${e}] is required`),Zi(t.kind);let n=Qi(t.text),r=yt(t.anchorTaskId,`candidates[${e}].anchorTaskId`),s=yt(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),o=yt(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||el("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o}));return H(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o,contentFingerprint:i}}function Pm(t){Array.isArray(t)||J("candidates must be an array"),t.length>al&&J(`candidates must contain at most ${al} items`);let e=new Map;for(let[n,r]of t.entries()){let s=Dm(r,n);e.set(s.contentFingerprint,s);}return [...e.values()]}function Or(t){let e=zi(t.metadata);return {threadId:t.id,workspaceId:t.workspace_id,title:t.title,priority:e.priority??null,state:e.state??null,metadata:t.metadata,titleLocked:t.title_locked===1,updatedAt:t.updated_at}}function Lm(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&J("event payload must be a JSON object"),e}catch(e){throw new g("VALIDATION","event payload must be JSON serializable",e)}}function Sr(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${j.seq}), 0)`}).from(j).where(eq(j.thread_id,e)).get()?.maxSeq??0}function Ir(t,e){return !!t.select({id:j.id}).from(j).where(eq(j.thread_id,e)).limit(1).get()}function sn(t,e){Sm.has(e.type)||J(`invalid thread event type: ${String(e.type)}`);let n=wr("the");t.insert(j).values({id:n,thread_id:e.threadId,seq:e.seq,type:e.type,actor_type:e.actorType,actor_id:e.actorId,task_id:e.taskId??null,highlight_id:e.highlightId??null,payload_json:Lm(e.payload),created_at:e.createdAt}).run();let r=t.select().from(j).where(eq(j.id,n)).get();if(!r)throw new g("DB_ERROR","Thread event insert did not return a row");return r}function Ar(t,e,n,r,s){let o=Or(e);sn(t,{threadId:e.id,seq:s,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:o.title,priority:o.priority,state:o.state}});}function Ls(t){return {highlightId:t.id,source:t.source,kind:t.kind,status:t.status,coversFromTaskId:t.covers_from_task_id,coversToTaskId:t.covers_to_task_id,revision:t.revision,...t.dismissed_at===null?{}:{dismissedAt:t.dismissed_at}}}function Ps(t,e,n,r,s,o,i){let u=s==="thread.highlight.created"?Ls(e):{before:i?Ls({...e,...i,id:e.id}):void 0,after:Ls(e)};return sn(t,{threadId:e.thread_id,seq:o,type:s,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:u})}function Mm(t,e,n,r,s,o){return sn(t,{threadId:e.thread_id,seq:s,type:"thread.highlight.deleted",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:Ls(e),...o??{}}})}var Ms=class extends Ie{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!existsSync(n))throw new g("NOT_FOUND","Database not found");if(e){let s=dirname(n);existsSync(s)||mkdirSync(s,{recursive:true});}let r=$(n);if(e)try{$e(r.db,n);}catch(s){throw r.close(),s}return r}findThread(e,n,r){let s=eq(T.id,n),o=r===void 0?s:r===null?and(s,isNull(T.workspace_id)):and(s,eq(T.workspace_id,r));return e.select().from(T).where(o).limit(1).get()}findRegenerationRun(e,n,r){let s=e.select().from(B).where(eq(B.id,n)).limit(1).get();if(s&&!(r!==void 0&&!this.findThread(e,s.thread_id,r)))return s}resolveWorkspaceId(e){if(H(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:T.workspace_id}).from(T).where(eq(T.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(H(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let s=this.findThread(r.db,e,n);return s?Or(s):null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read thread snapshot",s)}finally{r.close();}}updateSnapshot(e){vm(e);let n=Rr(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findThread(o,e.threadId,e.workspaceId);i||rt(`Thread ${e.threadId} not found`);let u=Or(i),d=e.title!==void 0,c=d&&e.title!==u.title,l=d&&i.title_locked!==1,p=e.priority!==void 0&&e.priority!==u.priority,f=e.state!==void 0&&e.state!==u.state,h=c||p||f;if(!h&&!l)return u;let m=i.metadata;(p||f)&&(m=rl(i.metadata,{priority:e.priority,state:e.state}));let k={};if(h&&(k.metadata=m,k.updated_at=r),c&&(k.title=e.title),d&&(k.title_locked=1),o.update(T).set(k).where(e.workspaceId===void 0?eq(T.id,e.threadId):e.workspaceId===null?and(eq(T.id,e.threadId),isNull(T.workspace_id)):and(eq(T.id,e.threadId),eq(T.workspace_id,e.workspaceId))).run(),!h){let w={...i,title_locked:1};return Or(w)}let E=Sr(o,i.id)+1;Ir(o,i.id)||(Ar(o,i,n,r,E),E+=1),c&&(sn(o,{threadId:i.id,seq:E,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.title,after:e.title}}),E+=1),p&&(sn(o,{threadId:i.id,seq:E,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.priority,after:e.priority}}),E+=1),f&&sn(o,{threadId:i.id,seq:E,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.state,after:e.state}});let x={...i,title:c?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return Or(x)},{behavior:"immediate"})}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to update thread snapshot",o)}finally{s.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(H(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({maxSeq:sql`COALESCE(MAX(${j.seq}), 0)`}).from(j).where(eq(j.thread_id,e)).get()?.maxSeq??0:null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read latest thread event sequence",s)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(H(e,"threadId"),H(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:a.id,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.started_at,completedAt:a.completed_at}).from(a).where(and(eq(a.thread_id,e),eq(a.workspace_id,n),inArray(a.status,[...nn]),or$1(isNull(a.parent_task_id),eq(a.parent_task_id,"")),sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(asc(a.started_at),asc(a.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read completed thread highlight turns",s)}finally{r.close();}}createHighlightRegenerationRun(e){H(e.threadId,"threadId"),H(e.workspaceId,"workspaceId"),H(e.requestId,"requestId"),H(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&H(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let o=this.findThread(s,e.threadId,e.workspaceId);o||rt(`Thread ${e.threadId} not found`);let i=s.select().from(B).where(and(eq(B.thread_id,o.id),eq(B.request_id,e.requestId))).orderBy(desc(B.requested_at),desc(B.id)).limit(1).get();if(i)return {run:i,created:!1};let u=s.select().from(B).where(and(eq(B.thread_id,o.id),inArray(B.status,Ds))).orderBy(asc(B.requested_at),asc(B.id)).limit(1).get();if(u)throw new Yi(u);let d=e.runId??wr("thr");s.insert(B).values({id:d,thread_id:o.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let c=s.select().from(B).where(eq(B.id,d)).get();if(!c)throw new g("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to create highlight regeneration run",s)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(H(e,"runId"),n!==void 0&&H(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read highlight regeneration run",s)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(H(e,"threadId"),H(n,"workspaceId"),H(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{return this.findThread(s.db,e,n)?s.db.select().from(B).where(and(eq(B.thread_id,e),eq(B.request_id,r))).orderBy(desc(B.requested_at),desc(B.id)).limit(1).get()??null:null}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to read highlight regeneration request",o)}finally{s.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){H(e,"runId"),n!==void 0&&H(n,"workspaceId");let r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findRegenerationRun(o,e,n);if(i||rt(`Highlight regeneration run ${e} not found`),Vi(i.status)||J(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;o.update(B).set({status:"running",started_at:r}).where(and(eq(B.id,i.id),eq(B.status,"queued"))).run();let u=o.select().from(B).where(eq(B.id,i.id)).get();if(!u)throw new g("DB_ERROR","Highlight regeneration run start did not return a row");return u},{behavior:"immediate"})}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to start highlight regeneration run",o)}finally{s.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){H(e.runId,"runId"),H(e.errorCode,"errorCode"),e.workspaceId!==void 0&&H(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let o=this.findRegenerationRun(s,e.runId,e.workspaceId);if(o||rt(`Highlight regeneration run ${e.runId} not found`),Vi(o.status)||J(`invalid highlight regeneration status: ${o.status}`),o.status==="completed"||o.status==="failed")return o;s.update(B).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(B.id,o.id),inArray(B.status,Ds))).run();let i=s.select().from(B).where(eq(B.id,o.id)).get();if(!i)throw new g("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to fail highlight regeneration run",s)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=wm){H(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>s.update(B).set({status:"failed",completed_at:n,error_code:e}).where(inArray(B.status,Ds)).run().changes,{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to recover interrupted highlight runs",s)}finally{r.close();}}completeHighlightRegenerationRun(e){H(e.runId,"runId"),H(e.threadId,"threadId"),H(e.workspaceId,"workspaceId"),H(e.detectorVersion,"detectorVersion");let n=Pm(e.candidates),r=Rr(e),s=this.openHandle(true),o=false;try{return s.db.transaction(i=>{let u=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!u||u.thread_id!==e.threadId)&&rt(`Highlight regeneration run ${e.runId} not found`),Vi(u.status)||J(`invalid highlight regeneration status: ${u.status}`),u.status==="failed")throw new g("CONFLICT","Highlight regeneration run has already failed");if(u.status==="completed")return {run:u,deletedCount:0,createdCount:0,previousAutoCount:u.previous_auto_count??0,newAutoCount:u.new_auto_count??0};o=!0;let d=this.findThread(i,e.threadId,e.workspaceId);d||rt(`Thread ${e.threadId} not found`),u.detector_version!==e.detectorVersion&&J("detectorVersion does not match the regeneration run");let c=i.select().from(U).where(eq(U.thread_id,d.id)).orderBy(asc(U.created_at),asc(U.id)).all(),l=new Set(n.map(I=>I.contentFingerprint)),p=c.filter(I=>I.source==="auto"&&I.status==="active"&&I.revision===0&&!l.has(I.content_fingerprint??"")),f=c.filter(I=>I.source==="auto"&&I.status==="active").length,h=new Set(c.filter(I=>!p.includes(I)&&I.content_fingerprint).map(I=>I.content_fingerprint)),m=n.filter(I=>!h.has(I.contentFingerprint)),k=new Date().toISOString(),E=Sr(i,d.id)+1;Ir(i,d.id)||(Ar(i,d,r,k,E),E+=1);for(let I of p)i.delete(U).where(eq(U.id,I.id)).run(),Mm(i,I,r,k,E,{runId:e.runId,reason:ym}),E+=1;let x=0,w=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let I of m){let z=wr("thl");i.insert(U).values({id:z,thread_id:d.id,source:"auto",kind:I.kind,status:"active",text:I.text,covers_from_task_id:I.coversFromTaskId,covers_to_task_id:I.coversToTaskId,revision:0,created_at:k,updated_at:k,agent_id:w,source_task_id:I.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:I.contentFingerprint,dismissed_at:null}).run();let he=i.select().from(U).where(eq(U.id,z)).get();if(!he)throw new g("DB_ERROR","Regenerated highlight insert did not return a row");Ps(i,he,r,k,"thread.highlight.created",E),E+=1,x+=1;}let O=i.select().from(U).where(eq(U.thread_id,d.id)).all().filter(I=>I.source==="auto"&&I.status==="active").length;sn(i,{threadId:d.id,seq:E,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:k,payload:{runId:u.id,detectorVersion:e.detectorVersion,previousAutoCount:f,newAutoCount:O,deletedCount:p.length,createdCount:x}}),i.update(B).set({status:"completed",started_at:u.started_at??k,completed_at:k,error_code:null,previous_auto_count:f,new_auto_count:O}).where(and(eq(B.id,u.id),inArray(B.status,Ds))).run();let b=i.select().from(B).where(eq(B.id,u.id)).get();if(!b)throw new g("DB_ERROR","Highlight regeneration completion did not return a row");return {run:b,deletedCount:p.length,createdCount:x,previousAutoCount:f,newAutoCount:O}},{behavior:"immediate"})}catch(i){if(o)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Em});}catch{}throw i instanceof g?i:new g("DB_ERROR","Failed to complete highlight regeneration",i)}finally{s.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let s=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;H(s.threadId,"threadId"),H(s.workspaceId,"workspaceId");let o=Nm(s);if(!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,s.threadId,s.workspaceId))return null;let u=i.db.select({maxSeq:sql`COALESCE(MAX(${j.seq}), 0)`}).from(j).where(eq(j.thread_id,s.threadId)).get()?.maxSeq??0,d;s.beforeSeq!==void 0?d=i.db.select().from(j).where(and(eq(j.thread_id,s.threadId),lt(j.seq,s.beforeSeq))).orderBy(desc(j.seq)).limit(o+1).all().reverse():s.afterSeq!==void 0?d=i.db.select().from(j).where(and(eq(j.thread_id,s.threadId),sql`${j.seq} > ${s.afterSeq}`)).orderBy(asc(j.seq)).limit(o+1).all():d=i.db.select().from(j).where(eq(j.thread_id,s.threadId)).orderBy(desc(j.seq)).limit(o+1).all().reverse();let c=d.length>o,l=s.afterSeq!==void 0?d.slice(0,o):c?d.slice(1):d,p=!1,f=l[0];return f&&(p=!!i.db.select({id:j.id}).from(j).where(and(eq(j.thread_id,s.threadId),lt(j.seq,f.seq))).limit(1).get()),{items:l,latestSeq:u,hasMoreOlder:p}}catch(u){throw u instanceof g?u:new g("DB_ERROR","Failed to list thread timeline",u)}finally{i.close();}}listEvents(e,n,r){return this.listTimeline(e,n,r)}getTimeline(e,n,r){return this.listTimeline(e,n,r)}createHighlight(e){let n=Cm(e),r=Rr(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);if(u||rt(`Thread ${e.threadId} not found`),n.source==="auto"){let f=i.select().from(U).where(and(eq(U.thread_id,e.threadId),eq(U.source_task_id,n.sourceTaskId),eq(U.detector_version,n.detectorVersion),eq(U.content_fingerprint,n.contentFingerprint))).orderBy(asc(U.created_at),asc(U.id)).limit(1).get();if(f)return f}let d=e.id??wr("thl"),c={id:d,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:s,updated_at:s,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(U).values(c).run();let l=i.select().from(U).where(eq(U.id,d)).get();if(!l)throw new g("DB_ERROR","Highlight insert did not return a row");let p=Sr(i,u.id)+1;return Ir(i,u.id)||(Ar(i,u,r,s,p),p+=1),Ps(i,l,r,s,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(i){throw i instanceof g?i:new g("DB_ERROR","Failed to create thread highlight",i)}finally{o.close();}}updateHighlight(e){H(e.threadId,"threadId"),H(e.workspaceId,"workspaceId"),H(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&J("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&J("highlight update requires at least one field"),e.kind!==void 0&&Zi(e.kind);let n=e.text===void 0?void 0:Qi(e.text),r=Rr(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);u||rt(`Thread ${e.threadId} not found`);let d=i.select().from(U).where(and(eq(U.id,e.highlightId),eq(U.thread_id,u.id))).limit(1).get();if(d||rt(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new br(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new br(u.id,d.id,e.expectedRevision,d.revision);let c=e.kind??d.kind,l=n??d.text,p=e.coversFromTaskId??d.covers_from_task_id,f=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||f.length===0)&&J("highlight projection is incomplete");let h=c!==d.kind||l!==d.text||p!==d.covers_from_task_id||f!==d.covers_to_task_id,m=r.actorType==="user"&&d.source==="auto"&&h?"manual":d.source;if(!(h||m!==d.source))return d;let E=d.revision+1;i.update(U).set({source:m,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:f,revision:E,updated_at:s}).where(and(eq(U.id,d.id),eq(U.revision,d.revision))).run();let x=i.select().from(U).where(eq(U.id,d.id)).get();if(!x)throw new g("DB_ERROR","Highlight update did not return a row");let w=Sr(i,u.id)+1;return Ir(i,u.id)||(Ar(i,u,r,s,w),w+=1),Ps(i,x,r,s,"thread.highlight.updated",w,d),x},{behavior:"immediate"})}catch(i){throw i instanceof g?i:new g("DB_ERROR","Failed to update thread highlight",i)}finally{o.close();}}dismissHighlight(e){H(e.threadId,"threadId"),H(e.workspaceId,"workspaceId"),H(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&J("expectedRevision must be a non-negative integer");let n=Rr(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findThread(o,e.threadId,e.workspaceId);i||rt(`Thread ${e.threadId} not found`);let u=o.select().from(U).where(and(eq(U.id,e.highlightId),eq(U.thread_id,i.id))).limit(1).get();if(u||rt(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new br(i.id,u.id,e.expectedRevision,u.revision);if(u.status==="dismissed")return u;let d=u.revision+1;o.update(U).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(and(eq(U.id,u.id),eq(U.revision,u.revision))).run();let c=o.select().from(U).where(eq(U.id,u.id)).get();if(!c)throw new g("DB_ERROR","Highlight dismissal did not return a row");let l=Sr(o,i.id)+1;return Ir(o,i.id)||(Ar(o,i,n,r,l),l+=1),Ps(o,c,n,r,"thread.highlight.deleted",l,u),c},{behavior:"immediate"})}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to dismiss thread highlight",o)}finally{s.close();}}listActiveHighlights(e,n,r={}){if(H(e,"threadId"),H(n,"workspaceId"),r.taskId!==void 0&&H(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&H(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&H(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{if(!this.findThread(s.db,e,n))return null;let i=s.db.select().from(U).where(and(eq(U.thread_id,e),eq(U.status,"active"))).orderBy(asc(U.created_at),asc(U.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let u=s.db.all(sql`
|
|
661
|
+
`),u},{behavior:"immediate"})}}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(y).set({last_message:n,updated_at:s}).where(eq(y.id,e)).run();}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};n.title!==void 0&&(o.title=n.title,o.title_locked=1),n.titleLocked!==void 0&&(o.title_locked=n.titleLocked?1:0),r.db.update(y).set(o).where(eq(y.id,e)).run();}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let o=n;if(!o||typeof o!="object"||Array.isArray(o))return new Fn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(d=>d!=="priority"&&d!=="state"))return new Fn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new Fn("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let d of [i.priority,i.state])if(d!=null&&(typeof d!="string"||d.length===0))return new Fn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let c=this.openHandle(true);try{let d=r?and(eq(y.id,e),eq(y.workspace_id,r)):eq(y.id,e);return c.db.transaction(u=>{let l=u.select({metadata:y.metadata}).from(y).where(d).get();if(!l)return null;let p=Bn(l.metadata),_=p.threadTitle,h=_&&typeof _=="object"&&!Array.isArray(_)?{..._}:{};i.priority===null?delete h.priority:i.priority!==void 0&&(h.priority=i.priority),i.state===null?delete h.state:i.state!==void 0&&(h.state=i.state),Object.keys(h).length>0?p.threadTitle=h:delete p.threadTitle;let m=Object.keys(p).length>0?JSON.stringify(p):null,k=new Date().toISOString();u.update(y).set({metadata:m,updated_at:k}).where(d).run();let E=u.select({metadata:y.metadata}).from(y).where(d).get();if(!E)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let P=bm(E.metadata);return {threadId:e,priority:P.priority,state:P.state}},{behavior:"immediate"})}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to patch thread-title metadata",d)}finally{c.close();}}togglePin(e,n){let r=this.openHandle(true);try{return r.db.transaction(o=>Dm(o,e,n),{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>Pm(o,e,n),{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?and(eq(y.id,e),eq(y.workspace_id,n)):eq(y.id,e),s=r.db.select({starred:y.starred}).from(y).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(y).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let i=this.openHandle(true);try{let c=n?and(eq(y.id,e),eq(y.workspace_id,n)):eq(y.id,e);return i.db.transaction(u=>{let l=u.select({metadata:y.metadata}).from(y).where(c).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},_=p.overdrive??{},h=o?.defaultTurns??_.defaultTurns??3,m=o?.updatedBy??"ui",k=new Date().toISOString(),E,P,w,L;switch(r){case "enable-count":{let N=o?.turns??h,b=o?.consumeCurrent?Math.max(N-1,0):N;E=b>0?"count":"off",P=b,w=!0,L="count";break}case "enable-latch":{E="latch",P=0,w=!0,L="latch";break}case "disable":{E="off",P=0,w=!1;break}default:{let N=_.state??"off",b=typeof _.remaining=="number"?_.remaining:0;if(N==="count"&&b>0){let I=b-1;I<=0?(E="off",P=0):(E="count",P=I),w=!0,L="count";}else N==="latch"?(E="latch",P=0,w=!0,L="latch"):(E="off",P=0,w=!1);break}}return p.overdrive={state:E,remaining:P,defaultTurns:h,updatedAt:k,updatedBy:m},u.update(y).set({metadata:JSON.stringify(p),updated_at:k}).where(c).run(),{applied:w,appliedMode:L,state:E,remaining:P}},{behavior:"immediate"})}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to resolve overdrive",c)}finally{i.close();}}};g();xt();zt();Jt();Ct();g();var oa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Lm(t){let e=randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let o=e[r];o<248&&(n+=oa[o%62]);}for(;n.length<t;)n+=oa[randomBytes(1)[0]%62];return n}function Dr(t){return `${t}_${Lm(8)}`}function ml(t,e){let{createHash:n}=gn("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=r[i];let s="";for(let i of o)s+=oa[i%62];return `${t}_${s}`}on();g();var Mm=["urgent","high","medium","low"],$m=["investigating","in-progress","in-review","on-hold","done"],kl="custom:";var Hm=new Set(Mm),Um=new Set($m);function sa(t){return typeof t=="string"&&Hm.has(t)}function ia(t){if(typeof t!="string")return false;if(Um.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(kl))return false;let e=t.slice(kl.length);return e.length>=1&&e.length<=20}function yl(t){if(!t)return null;try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function aa(t){let e=yl(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return sa(r.priority)&&(o.priority=r.priority),ia(r.state)&&(o.state=r.state),o}function Tl(t,e){let n=yl(t)??{},r={...aa(t)};return e.priority===null?delete r.priority:e.priority!==void 0&&(r.priority=e.priority),e.state===null?delete r.state:e.state!==void 0&&(r.state=e.state),r.priority===void 0&&r.state===void 0?delete n.threadTitle:n.threadTitle=r,Object.keys(n).length===0?null:JSON.stringify(n)}yr();var Gm="regeneration_replaced";var jm="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Km="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",ua=class extends f{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=o;}},qr=class extends ua{},la=class extends f{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},zm=new Set(fd),Jm=new Set(_d),Vm=new Set(gd),Xm=new Set(hd),Ym=50,El=100,Rl=280,Sl=40,Qm=new Set(md),zo=["queued","running"];function ca(t){return Qm.has(t)}function Q(t){throw new f("VALIDATION",t)}function ct(t){throw new f("NOT_FOUND",t)}function F(t,e){(typeof t!="string"||t.trim().length===0)&&Q(`${e} is required`);}function Lr(t={}){let e=t.actor??t,n=e.actorType??"system";return zm.has(n)||Q(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&Q("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Zm(t){F(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&F(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&Q("title must not be empty"),t.title.length>120&&Q("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!sa(t.priority)&&Q(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!ia(t.state)&&Q(`invalid state: ${String(t.state)}`);}function ek(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&Q("beforeSeq and afterSeq cannot be used together");for(let[n,r]of [["beforeSeq",t.beforeSeq],["afterSeq",t.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&Q(`${n} must be a non-negative integer`);let e=t.limit??Ym;return (!Number.isInteger(e)||e<1||e>El)&&Q(`limit must be between 1 and ${El}`),e}function pa(t){typeof t!="string"&&Q("text is required");let e=t.trim();return e.length===0&&Q("text must not be empty"),e.length>Rl&&Q(`text must be at most ${Rl} characters`),e}function Ot(t,e){return F(t??"",e),t}function _a(t){Xm.has(t)||Q(`invalid highlight kind: ${String(t)}`);}function tk(t){Vm.has(t)||Q(`invalid highlight source: ${String(t)}`);}function nk(t){F(t.threadId,"threadId"),F(t.workspaceId,"workspaceId");let e=t.source??"manual";tk(e),_a(t.kind);let n=pa(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&o&&r===o?r:void 0),p=Ot(l,"taskId");return (r!==p||o!==p)&&Q("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=Ot(r,"coversFromTaskId"),i=Ot(o,"coversToTaskId"),c=t.sourceTaskId??s,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),u=t.contentFingerprint??t.idempotencyKey??null;return Ot(c??void 0,"sourceTaskId"),Ot(d??void 0,"detectorVersion"),Ot(u??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:c,detectorVersion:d,contentFingerprint:u}}function rk(t,e){(!t||typeof t!="object")&&Q(`candidates[${e}] is required`),_a(t.kind);let n=pa(t.text),r=Ot(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Ot(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Ot(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||ml("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return F(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function ok(t){Array.isArray(t)||Q("candidates must be an array"),t.length>Sl&&Q(`candidates must contain at most ${Sl} items`);let e=new Map;for(let[n,r]of t.entries()){let o=rk(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function Ur(t){let e=aa(t.metadata);return {threadId:t.id,workspaceId:t.workspace_id,title:t.title,priority:e.priority??null,state:e.state??null,metadata:t.metadata,titleLocked:t.title_locked===1,updatedAt:t.updated_at}}function sk(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&Q("event payload must be a JSON object"),e}catch(e){throw new f("VALIDATION","event payload must be JSON serializable",e)}}function Mr(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${X.seq}), 0)`}).from(X).where(eq(X.thread_id,e)).get()?.maxSeq??0}function $r(t,e){return !!t.select({id:X.id}).from(X).where(eq(X.thread_id,e)).limit(1).get()}function fn(t,e){Jm.has(e.type)||Q(`invalid thread event type: ${String(e.type)}`);let n=Dr("the");t.insert(X).values({id:n,thread_id:e.threadId,seq:e.seq,type:e.type,actor_type:e.actorType,actor_id:e.actorId,task_id:e.taskId??null,highlight_id:e.highlightId??null,payload_json:sk(e.payload),created_at:e.createdAt}).run();let r=t.select().from(X).where(eq(X.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function Hr(t,e,n,r,o){let s=Ur(e);fn(t,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function Vo(t){return {highlightId:t.id,source:t.source,kind:t.kind,status:t.status,coversFromTaskId:t.covers_from_task_id,coversToTaskId:t.covers_to_task_id,revision:t.revision,...t.dismissed_at===null?{}:{dismissedAt:t.dismissed_at}}}function Jo(t,e,n,r,o,s,i){let c=o==="thread.highlight.created"?Vo(e):{before:i?Vo({...e,...i,id:e.id}):void 0,after:Vo(e)};return fn(t,{threadId:e.thread_id,seq:s,type:o,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:c})}function ik(t,e,n,r,o,s){return fn(t,{threadId:e.thread_id,seq:o,type:"thread.highlight.deleted",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:Vo(e),...s??{}}})}var Xo=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??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!existsSync(n))throw new f("NOT_FOUND","Database not found");if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}let r=q(n);if(e)try{We(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=eq(y.id,n),s=r===void 0?o:r===null?and(o,isNull(y.workspace_id)):and(o,eq(y.workspace_id,r));return e.select().from(y).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(K).where(eq(K.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(F(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:y.workspace_id}).from(y).where(eq(y.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(F(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?Ur(o):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Zm(e);let n=Lr(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||ct(`Thread ${e.threadId} not found`);let c=Ur(i),d=e.title!==void 0,u=d&&e.title!==c.title,l=d&&i.title_locked!==1,p=e.priority!==void 0&&e.priority!==c.priority,_=e.state!==void 0&&e.state!==c.state,h=u||p||_;if(!h&&!l)return c;let m=i.metadata;(p||_)&&(m=Tl(i.metadata,{priority:e.priority,state:e.state}));let k={};if(h&&(k.metadata=m,k.updated_at=r),u&&(k.title=e.title),d&&(k.title_locked=1),s.update(y).set(k).where(e.workspaceId===void 0?eq(y.id,e.threadId):e.workspaceId===null?and(eq(y.id,e.threadId),isNull(y.workspace_id)):and(eq(y.id,e.threadId),eq(y.workspace_id,e.workspaceId))).run(),!h){let w={...i,title_locked:1};return Ur(w)}let E=Mr(s,i.id)+1;$r(s,i.id)||(Hr(s,i,n,r,E),E+=1),u&&(fn(s,{threadId:i.id,seq:E,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.title,after:e.title}}),E+=1),p&&(fn(s,{threadId:i.id,seq:E,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.priority,after:e.priority}}),E+=1),_&&fn(s,{threadId:i.id,seq:E,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.state,after:e.state}});let P={...i,title:u?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return Ur(P)},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(F(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({maxSeq:sql`COALESCE(MAX(${X.seq}), 0)`}).from(X).where(eq(X.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(F(e,"threadId"),F(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:a.id,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.started_at,completedAt:a.completed_at}).from(a).where(and(eq(a.thread_id,e),eq(a.workspace_id,n),inArray(a.status,[...pn]),or$1(isNull(a.parent_task_id),eq(a.parent_task_id,"")),sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(asc(a.started_at),asc(a.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){F(e.threadId,"threadId"),F(e.workspaceId,"workspaceId"),F(e.requestId,"requestId"),F(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&F(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findThread(o,e.threadId,e.workspaceId);s||ct(`Thread ${e.threadId} not found`);let i=o.select().from(K).where(and(eq(K.thread_id,s.id),eq(K.request_id,e.requestId))).orderBy(desc(K.requested_at),desc(K.id)).limit(1).get();if(i)return {run:i,created:!1};let c=o.select().from(K).where(and(eq(K.thread_id,s.id),inArray(K.status,zo))).orderBy(asc(K.requested_at),asc(K.id)).limit(1).get();if(c)throw new la(c);let d=e.runId??Dr("thr");o.insert(K).values({id:d,thread_id:s.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let u=o.select().from(K).where(eq(K.id,d)).get();if(!u)throw new f("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:u,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to create highlight regeneration run",o)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(F(e,"runId"),n!==void 0&&F(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(F(e,"threadId"),F(n,"workspaceId"),F(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(K).where(and(eq(K.thread_id,e),eq(K.request_id,r))).orderBy(desc(K.requested_at),desc(K.id)).limit(1).get()??null:null}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read highlight regeneration request",s)}finally{o.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){F(e,"runId"),n!==void 0&&F(n,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findRegenerationRun(s,e,n);if(i||ct(`Highlight regeneration run ${e} not found`),ca(i.status)||Q(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(K).set({status:"running",started_at:r}).where(and(eq(K.id,i.id),eq(K.status,"queued"))).run();let c=s.select().from(K).where(eq(K.id,i.id)).get();if(!c)throw new f("DB_ERROR","Highlight regeneration run start did not return a row");return c},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){F(e.runId,"runId"),F(e.errorCode,"errorCode"),e.workspaceId!==void 0&&F(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findRegenerationRun(o,e.runId,e.workspaceId);if(s||ct(`Highlight regeneration run ${e.runId} not found`),ca(s.status)||Q(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(K).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(K.id,s.id),inArray(K.status,zo))).run();let i=o.select().from(K).where(eq(K.id,s.id)).get();if(!i)throw new f("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=jm){F(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(K).set({status:"failed",completed_at:n,error_code:e}).where(inArray(K.status,zo)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){F(e.runId,"runId"),F(e.threadId,"threadId"),F(e.workspaceId,"workspaceId"),F(e.detectorVersion,"detectorVersion");let n=ok(e.candidates),r=Lr(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let c=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!c||c.thread_id!==e.threadId)&&ct(`Highlight regeneration run ${e.runId} not found`),ca(c.status)||Q(`invalid highlight regeneration status: ${c.status}`),c.status==="failed")throw new f("CONFLICT","Highlight regeneration run has already failed");if(c.status==="completed")return {run:c,deletedCount:0,createdCount:0,previousAutoCount:c.previous_auto_count??0,newAutoCount:c.new_auto_count??0};s=!0;let d=this.findThread(i,e.threadId,e.workspaceId);d||ct(`Thread ${e.threadId} not found`),c.detector_version!==e.detectorVersion&&Q("detectorVersion does not match the regeneration run");let u=i.select().from(B).where(eq(B.thread_id,d.id)).orderBy(asc(B.created_at),asc(B.id)).all(),l=new Set(n.map(I=>I.contentFingerprint)),p=u.filter(I=>I.source==="auto"&&I.status==="active"&&I.revision===0&&!l.has(I.content_fingerprint??"")),_=u.filter(I=>I.source==="auto"&&I.status==="active").length,h=new Set(u.filter(I=>!p.includes(I)&&I.content_fingerprint).map(I=>I.content_fingerprint)),m=n.filter(I=>!h.has(I.contentFingerprint)),k=new Date().toISOString(),E=Mr(i,d.id)+1;$r(i,d.id)||(Hr(i,d,r,k,E),E+=1);for(let I of p)i.delete(B).where(eq(B.id,I.id)).run(),ik(i,I,r,k,E,{runId:e.runId,reason:Gm}),E+=1;let P=0,w=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let I of m){let z=Dr("thl");i.insert(B).values({id:z,thread_id:d.id,source:"auto",kind:I.kind,status:"active",text:I.text,covers_from_task_id:I.coversFromTaskId,covers_to_task_id:I.coversToTaskId,revision:0,created_at:k,updated_at:k,agent_id:w,source_task_id:I.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:I.contentFingerprint,dismissed_at:null}).run();let ne=i.select().from(B).where(eq(B.id,z)).get();if(!ne)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");Jo(i,ne,r,k,"thread.highlight.created",E),E+=1,P+=1;}let N=i.select().from(B).where(eq(B.thread_id,d.id)).all().filter(I=>I.source==="auto"&&I.status==="active").length;fn(i,{threadId:d.id,seq:E,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:k,payload:{runId:c.id,detectorVersion:e.detectorVersion,previousAutoCount:_,newAutoCount:N,deletedCount:p.length,createdCount:P}}),i.update(K).set({status:"completed",started_at:c.started_at??k,completed_at:k,error_code:null,previous_auto_count:_,new_auto_count:N}).where(and(eq(K.id,c.id),inArray(K.status,zo))).run();let b=i.select().from(K).where(eq(K.id,c.id)).get();if(!b)throw new f("DB_ERROR","Highlight regeneration completion did not return a row");return {run:b,deletedCount:p.length,createdCount:P,previousAutoCount:_,newAutoCount:N}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Km});}catch{}throw i instanceof f?i:new f("DB_ERROR","Failed to complete highlight regeneration",i)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;F(o.threadId,"threadId"),F(o.workspaceId,"workspaceId");let s=ek(o);if(!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let c=i.db.select({maxSeq:sql`COALESCE(MAX(${X.seq}), 0)`}).from(X).where(eq(X.thread_id,o.threadId)).get()?.maxSeq??0,d;o.beforeSeq!==void 0?d=i.db.select().from(X).where(and(eq(X.thread_id,o.threadId),lt(X.seq,o.beforeSeq))).orderBy(desc(X.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?d=i.db.select().from(X).where(and(eq(X.thread_id,o.threadId),sql`${X.seq} > ${o.afterSeq}`)).orderBy(asc(X.seq)).limit(s+1).all():d=i.db.select().from(X).where(eq(X.thread_id,o.threadId)).orderBy(desc(X.seq)).limit(s+1).all().reverse();let u=d.length>s,l=o.afterSeq!==void 0?d.slice(0,s):u?d.slice(1):d,p=!1,_=l[0];return _&&(p=!!i.db.select({id:X.id}).from(X).where(and(eq(X.thread_id,o.threadId),lt(X.seq,_.seq))).limit(1).get()),{items:l,latestSeq:c,hasMoreOlder:p}}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to list thread timeline",c)}finally{i.close();}}listEvents(e,n,r){return this.listTimeline(e,n,r)}getTimeline(e,n,r){return this.listTimeline(e,n,r)}createHighlight(e){let n=nk(e),r=Lr(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let c=this.findThread(i,e.threadId,e.workspaceId);if(c||ct(`Thread ${e.threadId} not found`),n.source==="auto"){let _=i.select().from(B).where(and(eq(B.thread_id,e.threadId),eq(B.source_task_id,n.sourceTaskId),eq(B.detector_version,n.detectorVersion),eq(B.content_fingerprint,n.contentFingerprint))).orderBy(asc(B.created_at),asc(B.id)).limit(1).get();if(_)return _}let d=e.id??Dr("thl"),u={id:d,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(B).values(u).run();let l=i.select().from(B).where(eq(B.id,d)).get();if(!l)throw new f("DB_ERROR","Highlight insert did not return a row");let p=Mr(i,c.id)+1;return $r(i,c.id)||(Hr(i,c,r,o,p),p+=1),Jo(i,l,r,o,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){F(e.threadId,"threadId"),F(e.workspaceId,"workspaceId"),F(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&Q("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&Q("highlight update requires at least one field"),e.kind!==void 0&&_a(e.kind);let n=e.text===void 0?void 0:pa(e.text),r=Lr(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let c=this.findThread(i,e.threadId,e.workspaceId);c||ct(`Thread ${e.threadId} not found`);let d=i.select().from(B).where(and(eq(B.id,e.highlightId),eq(B.thread_id,c.id))).limit(1).get();if(d||ct(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new qr(c.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new qr(c.id,d.id,e.expectedRevision,d.revision);let u=e.kind??d.kind,l=n??d.text,p=e.coversFromTaskId??d.covers_from_task_id,_=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||_.length===0)&&Q("highlight projection is incomplete");let h=u!==d.kind||l!==d.text||p!==d.covers_from_task_id||_!==d.covers_to_task_id,m=r.actorType==="user"&&d.source==="auto"&&h?"manual":d.source;if(!(h||m!==d.source))return d;let E=d.revision+1;i.update(B).set({source:m,kind:u,text:l,covers_from_task_id:p,covers_to_task_id:_,revision:E,updated_at:o}).where(and(eq(B.id,d.id),eq(B.revision,d.revision))).run();let P=i.select().from(B).where(eq(B.id,d.id)).get();if(!P)throw new f("DB_ERROR","Highlight update did not return a row");let w=Mr(i,c.id)+1;return $r(i,c.id)||(Hr(i,c,r,o,w),w+=1),Jo(i,P,r,o,"thread.highlight.updated",w,d),P},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){F(e.threadId,"threadId"),F(e.workspaceId,"workspaceId"),F(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&Q("expectedRevision must be a non-negative integer");let n=Lr(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||ct(`Thread ${e.threadId} not found`);let c=s.select().from(B).where(and(eq(B.id,e.highlightId),eq(B.thread_id,i.id))).limit(1).get();if(c||ct(`Highlight ${e.highlightId} not found`),c.revision!==e.expectedRevision)throw new qr(i.id,c.id,e.expectedRevision,c.revision);if(c.status==="dismissed")return c;let d=c.revision+1;s.update(B).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(and(eq(B.id,c.id),eq(B.revision,c.revision))).run();let u=s.select().from(B).where(eq(B.id,c.id)).get();if(!u)throw new f("DB_ERROR","Highlight dismissal did not return a row");let l=Mr(s,i.id)+1;return $r(s,i.id)||(Hr(s,i,n,r,l),l+=1),Jo(s,u,n,r,"thread.highlight.deleted",l,c),u},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(F(e,"threadId"),F(n,"workspaceId"),r.taskId!==void 0&&F(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&F(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&F(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,n))return null;let i=o.db.select().from(B).where(and(eq(B.thread_id,e),eq(B.status,"active"))).orderBy(asc(B.created_at),asc(B.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let c=o.db.all(sql`
|
|
649
662
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
650
663
|
ORDER BY started_at ASC, id ASC
|
|
651
|
-
`),d=new Map(
|
|
652
|
-
`).filter(
|
|
653
|
-
`).trim()}function
|
|
654
|
-
`):
|
|
655
|
-
`)[0]??"":"";if(e){let r=
|
|
664
|
+
`),d=new Map(c.map((_,h)=>[_.id,h])),u=r.taskId===void 0?void 0:d.get(r.taskId),l=r.coversFromTaskId===void 0?void 0:d.get(r.coversFromTaskId),p=r.coversToTaskId===void 0?void 0:d.get(r.coversToTaskId);return i.filter(_=>{let h=d.get(_.covers_from_task_id),m=d.get(_.covers_to_task_id);if(h===void 0||m===void 0)return !1;let k=Math.min(h,m),E=Math.max(h,m);return !(u!==void 0&&(u<k||u>E)||l!==void 0&&E<l||p!==void 0&&k>p)})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};g();xt();zt();Jt();Ct();on();ms();var oe=class extends f{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Al="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function gk(){let t=randomBytes(16),e="";for(let n of t)e+=Al[n%Al.length];return e.slice(0,12)}function Nl(){return `c_${gk()}`}function hk(t){return typeof t=="string"&&gs.includes(t)}function mk(t){return typeof t=="string"&&hs.includes(t)}function Kn(t){if(!hk(t))throw new oe("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Ol(t){if(!mk(t))throw new oe("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function vl(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new oe("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function zn(t){if(typeof t!="string"||t.trim().length===0)throw new oe("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Yo(t){if(typeof t!="string"||t.trim().length===0)throw new oe("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function Gt(t,e){return and(eq(M.code_group,t),or$1(isNull(M.workspace_id),eq(M.workspace_id,e)))}var Qo=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??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!existsSync(n))throw new f("NOT_FOUND","Database not found");e&&mkdirSync(dirname(n),{recursive:true});let r=q(n);if(e)try{We(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(Kn(e),zn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(M).where(and(Gt(e,n),eq(M.is_archived,0))).orderBy(asc(M.sort_order),asc(M.code)).all()}catch(o){throw new f("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(Kn(e),zn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(M).where(Gt(e,n)).orderBy(asc(M.sort_order),asc(M.code)).all()}catch(o){throw new f("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(Kn(n),zn(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new oe("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)Yo(o);if(new Set(e.codes).size!==e.codes.length)throw new oe("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new oe("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(M).where(Gt(n,e.workspaceId)).all(),i=s.filter(h=>h.is_archived===0),c=new Set(s.map(h=>h.code)),d=new Set(i.map(h=>h.code)),u=e.codes.find(h=>!c.has(h));if(u)throw new oe("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${u}`);if(e.codes.length!==i.length||e.codes.some(h=>!d.has(h)))throw new oe("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let l=new Map(i.map(h=>[h.code,h])),p=e.codes.map(h=>{let m=l.get(h);if(!m)throw new oe("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${h}`);return m}),_;for(let[h,m]of p.entries())m.sort_order!==h&&(_??=new Date().toISOString(),o.update(M).set({sort_order:h,updated_at:_}).where(and(eq(M.code_group,n),eq(M.code,m.code))).run());return o.select().from(M).where(Gt(n,e.workspaceId)).orderBy(asc(M.sort_order),asc(M.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(Kn(e),Yo(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(M).where(and(eq(M.code_group,e),eq(M.code,n))).limit(1).get()??null}catch(o){throw new f("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){zn(e.workspaceId);let n=vl(e.name);Ol(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:M.code}).from(M).where(and(Gt("THREAD_STATE",e.workspaceId),eq(M.is_archived,0),eq(M.code_name,n))).limit(1).get())throw new oe("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=o.select({maxSortOrder:sql`max(${M.sort_order})`}).from(M).where(Gt("THREAD_STATE",e.workspaceId)).get(),c=new Date().toISOString(),d=Nl();for(;o.select({code:M.code}).from(M).where(and(eq(M.code_group,"THREAD_STATE"),eq(M.code,d))).limit(1).get();)d=Nl();o.insert(M).values({code_group:"THREAD_STATE",code:d,code_name:n,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:c,updated_at:c}).run();let u=o.select().from(M).where(and(eq(M.code_group,"THREAD_STATE"),eq(M.code,d))).limit(1).get();if(!u)throw new f("DB_ERROR","Created common code could not be read back");return u},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(Kn(e.group),Yo(e.code),zn(e.workspaceId),e.name===void 0&&e.color===void 0)throw new oe("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:vl(e.name);e.color!==void 0&&Ol(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(M).where(and(eq(M.code_group,e.group),eq(M.code,e.code))).limit(1).get();if(!s)throw new oe("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(s,e.workspaceId),n===null&&s.is_builtin!==1)throw new oe("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let d=and(Gt(e.group,e.workspaceId),eq(M.is_archived,0));if(o.select({code:M.code}).from(M).where(and(d,eq(M.code_name,n),sql`${M.code} <> ${e.code}`)).limit(1).get())throw new oe("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`)}let i={updated_at:new Date().toISOString()};e.name!==void 0&&(i.code_name=n??null),e.color!==void 0&&(i.color=e.color),o.update(M).set(i).where(and(eq(M.code_group,e.group),eq(M.code,e.code))).run();let c=o.select().from(M).where(and(eq(M.code_group,e.group),eq(M.code,e.code))).limit(1).get();if(!c)throw new f("DB_ERROR","Updated common code could not be read back");return c},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(Kn(e),Yo(n),zn(r),typeof o!="boolean")throw new oe("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let c=i.select().from(M).where(and(eq(M.code_group,e),eq(M.code,n))).limit(1).get();if(!c)throw new oe("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(c.is_builtin===1)throw new oe("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(c,r),!o&&c.code_name!==null&&i.select({code:M.code}).from(M).where(and(Gt(e,r),eq(M.is_archived,0),eq(M.code_name,c.code_name),ne(M.code,n))).limit(1).get())throw new oe("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${c.code_name}`);i.update(M).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(and(eq(M.code_group,e),eq(M.code,n))).run();let d=i.select().from(M).where(and(eq(M.code_group,e),eq(M.code,n))).limit(1).get();if(!d)throw new f("DB_ERROR","Archived common code could not be read back");return d},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to archive common code",i)}finally{s.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new oe("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};In();yr();g();var ut={threadContext:"crewx_thread_context",apps:"apps",appsGuidance:"apps_guidance",availableApps:"available_apps",crewxUiState:"crewx_ui_state"};function Tk(t){return t.replace(new RegExp(`<${ut.threadContext}\\b[^>]*>[\\s\\S]*?<\\/${ut.threadContext}>`,"g"),"").replace(new RegExp(`<${ut.apps}\\b[^>]*>[\\s\\S]*?<\\/${ut.apps}>`,"g"),"").replace(new RegExp(`<${ut.appsGuidance}\\b[^>]*>[\\s\\S]*?<\\/${ut.appsGuidance}>`,"g"),"").replace(new RegExp(`<${ut.availableApps}\\b[^>]*>[\\s\\S]*?<\\/${ut.availableApps}>`,"g"),"").replace(new RegExp(`<${ut.crewxUiState}\\b[^>]*>[\\s\\S]*?<\\/${ut.crewxUiState}>`,"g"),"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
665
|
+
`).filter(o=>!(o.startsWith("Loaded ")&&o.includes("layouts from")||o.includes("[dotenv@")||o.includes("[Nest]")&&o.includes("DEBUG")||o.startsWith("Registered custom layout:")||o.startsWith("Updated custom layout:"))).join(`
|
|
666
|
+
`).trim()}function wk(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.provider;return typeof n=="string"?n:void 0}catch{return}}function Ek(t,e,n){if(!t||e&&kt(t,n))return "";let r=t;try{let o=JSON.parse(r);Array.isArray(o)?r=o.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
|
|
667
|
+
`):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=Tk(r);}return r}var Rk=new Set(["success","failed","stopped","running"]),Sk=new Set(["failed","stopped"]),Ik={user_stop:"stopped by the user before it finished",runner_lost:"end of run not observed \u2014 it may have done part of the work or may still be running",launch_failed:"the runner never started this run"},Zo=200;function Cl(t){if(t.length<=Zo)return t;let e=t.charCodeAt(Zo-1),n=e>=55296&&e<=56319?Zo-1:Zo;return t.slice(0,n)}function Ak(t){let e=ot(t),n=typeof t.error=="string"?t.error.split(`
|
|
668
|
+
`)[0]??"":"";if(e){let r=Ik[e];return Cl(n?`${r}; ${n}`:r)}return n?Cl(n):void 0}var es=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Ko({dbPath:this.dbPath})}getThreadHistoryRepo(){return new Xo({dbPath:this.dbPath})}updateThread(e,n){this.getThreadRepo().updateThread(e,{title:n.title});}async ensureThread(e,n,r,o){let s=this.getThreadRepo(),i=s.findThreadById(e);if(i){if(i.platform!==n)throw new Error(`Thread '${e}' already exists with platform '${i.platform}' \u2014 cannot change to '${n}' (platform is immutable)`);return s.ensureThread(e,n,r,o),{created:false}}return s.ensureThread(e,n,r,o),{created:true}}async fetchHistory(e,n){let r=n?.limit??100,o=this.getThreadRepo(),s=o.findThreadById(e),i=o.findTopLevelTasks(e,void 0,r,n?.agentId||void 0),c=new Set(["queued","cancelled"]),d=n?.currentTraceId;i=i.filter(h=>(!h.status||!c.has(h.status))&&(!d||h.trace_id!==d&&h.id!==d));let u=o.findInterceptedRequests(i.map(h=>h.id));u.size>0&&(i=i.map(h=>u.has(h.id)?{...h,prompt:u.get(h.id)}:h));let l=s?.platform??"cli",p=this.rowsToMessages(i),_=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,s?.workspace_id??null);return {threadId:e,platform:l,messages:p,..._?{highlights:_}:{},metadata:{title:s?.title??void 0,firstMessage:s?.first_message??void 0,lastMessage:s?.last_message??void 0,messageCount:s?.message_count??0,updatedAt:s?.updated_at?new Date(s.updated_at).getTime():void 0}}}async fetchThreadState(e){try{let n=this.getThreadHistoryRepo().getSnapshot(e);if(!n)return;let r=new Qo({dbPath:this.dbPath}),o=(s,i)=>{try{return r.resolve(s,i)?.code_name||i}catch{return i}};return {...n.title?{title:n.title}:{},...n.priority?{priority:{code:n.priority,name:o("THREAD_PRIORITY",n.priority)}}:{},...n.state?{state:{code:n.state,name:o("THREAD_STATE",n.state)}}:{}}}catch{return}}async fetchHighlights(e){let n=this.getThreadRepo().findThreadById(e);return this.readActiveHighlights(e,n?.workspace_id??null)}async saveUserMessage(e,n,r,o){let{firstMessage:s}=this.getThreadRepo().saveUserMessage(e,n);return {id:e,firstMessage:s}}async saveAssistantMessage(e,n,r,o){return this.getThreadRepo().saveAssistantMessage(e,n),{id:e}}close(){}readActiveHighlights(e,n){if(!n)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,n)??[]).filter(o=>typeof o.text=="string"&&o.text.length>0).map(o=>({id:o.id,text:o.text,kind:o.kind,source:o.source,coversFromTaskId:o.covers_from_task_id,coversToTaskId:o.covers_to_task_id,createdAt:o.created_at}))}catch{return}}rowsToMessages(e){let n=[];for(let r of e){r.prompt&&n.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let o={status:r.status??"",error:r.error,metadata:r.metadata},s=r.status?qe(o):void 0,i=wk(r.metadata),c=Ek(r.result,s!==void 0&&Sk.has(s),i);if(c||s!==void 0&&Rk.has(s)){let d={agent_id:r.agent_id,task_id:r.id};if(s&&s!=="success"){d.status=s;let u=Ak(o);u&&(d.reason=u);}n.push({id:`${r.id}-assistant`,text:c,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:d});}}return n}};var fa=class extends vt{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new es(e?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(e,n,r,o){}async afterAssistantMessage(e,n,r){}attach(e){this.unsubStart=e.on("task:start",async n=>{if(!n.threadId)return;let r=n.platform??"cli";try{let o=await this._provider.ensureThread(n.threadId,r,n.workspaceId,{createdByTaskId:n.traceId}),s=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,s.id,o.created||s.firstMessage,n);}catch{}}),this.unsubEnd=e.on("task:end",async n=>{if(!n.result)return;let r=n.metadata?.threadId;if(!r)return;let o=n.agentRef?.replace(/^@/,"")??"";try{let{id:s}=await this._provider.saveAssistantMessage(r,n.result,o);await this.afterAssistantMessage(r,s,n);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{fa as ConversationPlugin,ns as FileLoggerPlugin,ta as SqliteTracingPlugin};
|