@crewx/sdk 0.9.0-rc.179 → 0.9.0-rc.180
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/app-files/args.d.ts +12 -0
- package/dist/app/app-files/errors.d.ts +6 -0
- package/dist/app/app-files/index.d.ts +34 -0
- package/dist/app/app-files/lock.d.ts +26 -0
- package/dist/app/app-files/root.d.ts +22 -0
- package/dist/app/app-files/store.d.ts +47 -0
- package/dist/app/app-files/write.child.d.ts +1 -0
- package/dist/app/index.d.ts +2 -0
- package/dist/app/index.js +13 -12
- package/dist/app-ui/index.d.ts +17 -3
- package/dist/app-ui/index.js +1 -1
- package/dist/esm/app/index.js +13 -12
- package/dist/esm/index.js +274 -274
- package/dist/esm/plugins/index.js +108 -108
- package/dist/esm/publish/index.js +2 -2
- package/dist/esm/repository/index.js +159 -159
- package/dist/esm/skills/index.js +2 -2
- package/dist/index.js +271 -271
- package/dist/migrations/0046_acoustic_karnak.sql +49 -0
- package/dist/migrations/0047_doc_sync_connect_requests.sql +18 -0
- package/dist/migrations/meta/0046_snapshot.json +4733 -0
- package/dist/migrations/meta/0047_snapshot.json +4832 -0
- package/dist/migrations/meta/_journal.json +14 -0
- package/dist/plugins/index.js +108 -108
- package/dist/publish/index.js +2 -2
- package/dist/repository/index.d.ts +2 -0
- package/dist/repository/index.js +156 -156
- package/dist/schema/doc-sync-connect-requests.d.ts +140 -0
- package/dist/schema/doc-sync-links.d.ts +481 -0
- package/dist/schema/index.d.ts +2 -0
- package/dist/skills/index.js +2 -2
- package/dist/ui-plugin/app-manifest.d.ts +1 -1
- package/dist/ui-plugin/types.d.ts +1 -0
- package/package.json +1 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as _e from'path';import _e__default,{join,dirname,resolve}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,lstatSync,readFileSync,statSync,realpathSync}from'fs';import mi,{homedir}from'os';import {createHash,randomBytes,randomUUID}from'crypto';import {sqliteTable,text,integer,index,check,primaryKey,real,uniqueIndex,unique}from'drizzle-orm/sqlite-core';import {sql,and,eq,inArray,or,isNull,ne as ne$1,desc,lt as lt$1,asc,like,gte,isNotNull,notLike,getTableColumns}from'drizzle-orm';import {spawnSync,spawn}from'child_process';var su=Object.defineProperty;var Kt=(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 ou=(t,e)=>{for(var n in e)su(t,n,{get:e[n],enumerable:true});};var du,cu,A,g=x(()=>{du=()=>fileURLToPath(import.meta.url),cu=()=>_e__default.dirname(du()),A=cu();});var f,pt=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 gi(t){if(t===":memory:")return t;let e=resolve(t),n=e,r=[];for(;!existsSync(n);){let o=dirname(n);if(o===n)return e;r.unshift(n.slice(o.length+1)),n=o;}let s=realpathSync(n);for(let o of r)s=join(s,o);return resolve(s)}function yu(t,e){let n=gi(t),r=gi(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function At(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&wu.some(e=>yu(t,join(mi.homedir(),".crewx",e))))throw new Error(`${Tu}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var Tu,wu,Ee,ft=x(()=>{g();Tu="[crewx] Refusing to open the real CrewX database from a test process";wu=["crewx.db","logs.db"];Ee=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(mi.homedir(),".crewx","crewx.db");return At(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 $(t,e={}){let n=At(t),r=Kt("better-sqlite3"),{drizzle:s}=Kt("drizzle-orm/better-sqlite3"),o=e.readOnly?new r(n,{readonly:true,fileMustExist:true}):new r(n);return e.readOnly||(o.exec("PRAGMA journal_mode = WAL"),o.exec(`PRAGMA journal_size_limit = ${Ru}`),o.exec("PRAGMA busy_timeout = 5000"),o.exec("PRAGMA foreign_keys = ON"),o.exec("PRAGMA analysis_limit = 400")),{db:s(o),sqlite:o,runRaw:(i,c=[])=>o.prepare(i).run(...c),close:()=>o.close()}}var Ru,Ot=x(()=>{g();ft();Ru=32*1024*1024;});function Vt(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Iu(t,e){if(e>0||!Vt(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(s=>s.name));for(let[s,o]of Object.entries(Su))r.has(s)||t.run(`ALTER TABLE tasks ADD COLUMN ${s} ${o}`);}function Ou(t,e,n){if(!Vt(t,"__drizzle_migrations")||!Vt(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),s=new Set(r.map(i=>i.hash)),o=JSON.parse(readFileSync(_e__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let c=Au[i.tag];if(!c)continue;let d=_e__default.join(e,`${i.tag}.sql`);if(!existsSync(d))continue;let u=readFileSync(d,"utf-8"),l=createHash("sha256").update(u).digest("hex");if(s.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 yi(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 s=e.match(/^DROP\s+INDEX\s+IF\s+EXISTS\s+[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(s)return {kind:"drop-index",name:s[1]}}function wi(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function Nu(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(o=>o.name===n)}function bu(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function _r(t,e){return e.kind==="add-column"?Nu(t,e.table,e.column):bu(t,e.name)}function Ei(t,e,n){let r=t;for(let s of wi(e)){let o=yi(s);o?.kind==="add-column"&&_r(r,o)||o?.kind==="create-index"&&_r(r,o)||o?.kind==="drop-index"&&!_r(r,o)||r.run(n.raw(s));}}function xu(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),s=new Set(r.map(i=>i.hash)),o=JSON.parse(readFileSync(_e__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let c=_e__default.join(e,`${i.tag}.sql`);if(!existsSync(c))continue;let d=readFileSync(c,"utf-8"),u=createHash("sha256").update(d).digest("hex");if(s.has(u))continue;let p=wi(d).map(yi);if(p.some(h=>!h))continue;let _=p;_.some(h=>h.kind==="add-column")&&_.some(h=>_r(t,h))&&(t.transaction(h=>{Ei(h,d,n),h.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${i.when})`);},{behavior:"immediate"}),s.add(u),console.error(`[crewx] Reconciled additive migration ${i.tag} from existing schema objects.`));}}function vu(t,e){let{sql:n}=Kt("drizzle-orm"),r=JSON.parse(readFileSync(_e__default.join(e,"meta/_journal.json"),"utf-8")),o=["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(_e__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(o[0].hash))for(let d of o.slice(1))c.has(d.hash)||(Ei(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 Lu(t,e,n,r){let o=JSON.parse(readFileSync(_e__default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===Cu);if(!o)return;let i=_e__default.join(e,`${o.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(!Vt(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 Mu(t,e,n,r){let o=JSON.parse(readFileSync(_e__default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===Du);if(!o)return;let i=_e__default.join(e,`${o.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(!Vt(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=Vt(t,Ti)?`AND NOT EXISTS (
|
|
7
7
|
SELECT 1
|
|
8
|
-
FROM ${
|
|
8
|
+
FROM ${Ti} 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,49 +15,49 @@ import*as pe from'path';import pe__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 = '${Pu}'
|
|
19
19
|
)
|
|
20
|
-
${
|
|
20
|
+
${u}`);return {hash:c,markedPointers:l?.count??0}}function $u(t){let{migrate:e}=Kt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=Kt("drizzle-orm"),r=[_e__default.join(A,"../migrations"),_e__default.join(A,"migrations"),_e__default.join(A,"../../../../drizzle/migrations"),_e__default.join(process.cwd(),"drizzle/migrations")],s=r.find(p=>existsSync(_e__default.join(p,"meta/_journal.json")));if(!s)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),_c(t,i),o?.cnt&&(yc(t,s),wc(t,s,n),mc(t,s,n));let u=Ic(t,s,n,!!o?.cnt),d=Ac(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(g=>g.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(g=>g.hash===d.hash)&&console.error(`[crewx] Thread creator pointer migration (${d.markedPointers} pointer(s) marked unverified).`);}function xe(t,e){li.has(e)||(Oc(t),li.add(e));}var li,gc,hc,Ec,Rc,Sc,pi,St=v(()=>{_();li=new Set,gc={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"};hc={"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"}};Ec="0027_task_stop_scope_cleanup",Rc="0033_thread_creator_boundary_guard",Sc="trg_threads_creator_late_fill_guard",pi="thread_creator_unverified";});var te,dr=v(()=>{_();te=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,fh,Cc,ne,Gt=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:fh,...Cc}=getTableColumns(a),ne=Cc;});var st,Ti=v(()=>{_();Gt();st=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 Xe,yi=v(()=>{_();Gt();Xe=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 Uc,Fc,k,En=v(()=>{_();dr();Uc="json_extract(metadata, '$.threadTitle.state')",Fc="json_extract(metadata, '$.threadTitle.priority')",k=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>te.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(Uc)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(Fc))}));});var Si=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 jc,Ai=v(()=>{_();Gt();jc=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(()=>jc.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 Oi=v(()=>{_();Gt();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 Ni=v(()=>{_();En();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>k.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 vi=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 Ci=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 Li=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 Mi=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 Hi=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 Fi=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 qi=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 Wi=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 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),Iu(t,i),o?.cnt&&(vu(t,s),xu(t,s,n),Ou(t,s,n));let c=Lu(t,s,n,!!o?.cnt),d=Mu(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).`);}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 De(t,e){ki.has(e)||($u(t),ki.add(e));}var ki,Su,Au,Cu,Du,Pu,Ti,Nt=x(()=>{g();ki=new Set,Su={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"};Au={"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"}};Cu="0027_task_stop_scope_cleanup",Du="0033_thread_creator_boundary_guard",Pu="trg_threads_creator_late_fill_guard",Ti="thread_creator_unverified";});var te,gr=x(()=>{g();te=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,Nh,Bu,ne,Xt=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:Nh,...Bu}=getTableColumns(a),ne=Bu;});var dt,Ai=x(()=>{g();Xt();dt=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 et,Ni=x(()=>{g();Xt();et=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 Vu,Xu,k,bn=x(()=>{g();gr();Vu="json_extract(metadata, '$.threadTitle.state')",Xu="json_extract(metadata, '$.threadTitle.priority')",k=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>te.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(Vu)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(Xu))}));});var vi=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 tl,Di=x(()=>{g();Xt();tl=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(()=>tl.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 Pi=x(()=>{g();Xt();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 Mi=x(()=>{g();bn();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>k.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 Hi=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 Ui=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 Bi=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 Wi=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 ji=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 Ki=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 Ji=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 Xi=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 Yi=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 zi=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 Ji,Vi=v(()=>{_();Ji=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(()=>Ji.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(()=>Ji.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 Es,Rs,C,Ss=v(()=>{_();Es=["THREAD_STATE","THREAD_PRIORITY"],Rs=["gray","blue","violet","green","amber","orange","red","pink"],C=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 Xi,Yi,Qi,Zi,ea,j,q,U,ta=v(()=>{_();En();Xi=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Yi=["user","agent","system"],Qi=["auto","manual"],Zi=["decision","judgment","issue","result","pivot"],ea=["queued","running","completed","failed"],j=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>k.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)})),q=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>k.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(()=>k.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 ra=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 Ie,sa=v(()=>{_();Ie=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 aa,da=v(()=>{_();En();dr();sqliteTable("sidebar_states",{workspace_id:text("workspace_id").primaryKey().references(()=>te.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)`)})),aa=sqliteTable("sidebar_groups",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull().references(()=>te.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(()=>te.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),group_id:text("group_id").references(()=>aa.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(()=>te.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),group_id:text("group_id").references(()=>aa.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(()=>te.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),read_through_at:text("read_through_at").notNull()},t=>({pk:primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var ua=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 ca=v(()=>{_();sqliteTable("run_column_backfill",{name:text("name").primaryKey(),cursor:integer("cursor"),anchor_id:text("anchor_id"),completed_at:text("completed_at")});});var vt=v(()=>{_();dr();Gt();Ti();yi();En();Si();Ai();Oi();Ni();vi();Ci();Li();Mi();Hi();Fi();qi();Wi();Gi();zi();Vi();Ss();ta();ra();sa();da();ua();ca();});function bn(t){return typeof t=="string"&&pt.includes(t)}function la(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 pt,Tr=v(()=>{_();pt=["workflow_card","workflow_ui_instance","workflow_run"];});var zt,xs,pa,vs=v(()=>{_();zt={"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":{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":{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-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.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.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}},xs=new Set(["gpt-5.3-codex-spark"]),pa=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-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","glm-5.1","glm-5.2","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-oss-120b","grok-4.5","grok-4.6","grok-4.7"]);});function Cs(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 vl(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Nn;let e=Cs(t),n=xl[e];if(n)return wr[n]??zt[n]??Nn;if(wr[e])return wr[e];if(zt[e])return zt[e];if(xs.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Nn;if(pa.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Nn;let r={...zt,...wr};for(let s of Object.keys(r))if(e.includes(s))return r[s];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Nn}function Cl(t,e,n,r=0,s){let o=vl(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 fa(t,e,n,r,s,o){return t&&t>0?t:!e&&!n?0:Cl(e??0,n??0,s,r??0)}var xl,Nn,wr,yr=v(()=>{_();vs();vs();xl={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"},Nn={input:0,cachedInput:0,output:0},wr={};});function ma(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"||!Pl.includes(r))return null;let s=n.schedule_id;return typeof s=="string"&&s!==""?s:null}var Pl,ka=v(()=>{_();Pl=["cron","cron_manual"];});function Ds(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function Ta(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Er(t){return Number.isSafeInteger(t)&&t>0}function Ul(t,e){try{let n=spawnSync(t,e,{encoding:"utf8",timeout:Ps,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:Ds(n)}}}function Fl(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:Ds(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 ${Ps}ms`)});},Ps);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 Ls(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Fl(t,e)}function ql(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Bl(){return new Promise(t=>{setImmediate(t);})}function ft(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return Ta(n)==="ESRCH"?"not_found":Ta(n)==="EPERM"?"alive":"unknown"}}function Wl(t,e){let n=ft(-t,e),r=ft(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function ya(t,e,n,r){let s=Math.max(0,n),o=Math.max(1,r.pollIntervalMs??$l),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 Bl();;){let l=Wl(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([c,ql(Math.min(o,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function wa(t,e,n,r,s){let o=await ya(t,e,s.hardConfirmMs??Hl,{...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 Ea(t,e,n={}){if(!Er(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 Ls(s,o,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let u=i.stdout.trim();if(!u)return "not_found";let d=r==="win32"?u.toLowerCase():u;return e.filter(l=>l.trim().length>0).some(l=>{let p=r==="win32"?l.toLowerCase():l;return d.includes(p)})?"owned":"not_owned"}function Kl(t){let e=Gl.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 Jl(t){let e=t.trim(),n=zl.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 Ra(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 Sa(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=Jl(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let s=jl.exec(r),o=s?Kl(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 Ia(t,e={}){if(!Er(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=Ra(t,n),o=e.runCommand??Ul,i;try{i=o(r,s);}catch{return {status:"unknown"}}return Sa(i,n,Date.now())}async function Aa(t,e={}){if(!Er(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=Ra(t,n),o;try{o=await Ls(r,s,e);}catch{return {status:"unknown"}}return Sa(o,n,Date.now())}async function _t(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",s=g=>({status:"failed",pid:t,method:r,error:g});if(!Er(t))return s("Invalid process ID");let o=e.kill??process.kill,i=ft(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 g;try{g=await Ls("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){g={status:null,stdout:"",stderr:"",error:Ds(m)};}let h=ft(t,o);return h==="not_found"?g.status===0&&!g.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(g){u=g;}if(d==="SIGKILL")return wa(t,o,u,r,e);if(await ya(t,o,e.graceMs??Ml,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(g){l=g;}let p=await wa(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 Ps,gt,Ml,$l,Hl,Rr,Gl,jl,zl,Sr=v(()=>{_();Ps=3e3,gt="SIGINT",Ml=2e3,$l=25,Hl=100;Rr=3e3,Gl=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,jl=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,zl=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function va(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 Na(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,s)=>va(r,s))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Ca(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 xa(t){return {taskId:t.id,source:Ca(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function ep(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var Ir,Pa=v(()=>{_();ut();Rt();St();dt();vt();Ir=class extends Te{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?Et(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 f("NOT_FOUND","Database not found");let r=$(n);if(e)try{xe(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 f("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)=>va(o,i));if(r.length===0){let o=this.getLogState(e);if(!o)throw new f("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=Ca(u);if(d==="blob"){let g=Na(e,u.logs);if(i.update(a).set({logs:JSON.stringify([...g,...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: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(Xe).values(r.map((g,h)=>({task_id:e,seq:c+h,timestamp:g.timestamp,level:g.level,message:g.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:u.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("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?xa(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 ep(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=xa(o);if(i.source==="blob"){let l=Na(e,o.logs).map((p,g)=>({...p,seq:g+1}));return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let u=s.select({seq:Xe.seq,timestamp:Xe.timestamp,level:Xe.level,message:Xe.message}).from(Xe).where(eq(Xe.task_id,e)).orderBy(n===void 0?asc(Xe.seq):desc(Xe.seq)),c=(n===void 0?u.all():u.limit(n).all()).map(({seq:l,timestamp:p,level:g,message:h})=>({seq:l,timestamp:p,level:g,message:h}));return n!==void 0&&c.reverse(),{...i,entries:c}},{behavior:"deferred"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read task logs",s)}finally{r.close();}}};});var op,Ar,La=v(()=>{_();ut();Rt();St();dt();vt();op=50,Ar=class extends Te{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 xe(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(Ie).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[Ie.workspace_id,Ie.actor_id,Ie.agent_id],set:{last_accepted_at:sql`MAX(${Ie.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:Ie.agent_id,lastAcceptedAt:Ie.last_accepted_at}).from(Ie).where(and(eq(Ie.workspace_id,e),eq(Ie.actor_id,n))).orderBy(desc(Ie.last_accepted_at),asc(Ie.agent_id)).limit(op).all()}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to find recent agent sends",s)}finally{r?.close();}}};});var Ma=v(()=>{_();});var Z,Ct=v(()=>{_();Z=class extends Error{constructor(n,r,s){super(n);this.providerStr=r;this.name="ProviderError",this.code=s?.code??"UNKNOWN",this.kind=s?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=s?.retryAfterMs;}providerStr;code;kind;retryAfterMs;stdout};});var Pt,Ms=v(()=>{_();Ct();Pt=class extends Z{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function Ha(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 ${he}]`),e=ap(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${he}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,he),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,he),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,he),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,he),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,he),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,he),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,he),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,he),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,he),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${he}${r}${he}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${he}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,$a),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,$a),e=e.replace(/[\r\n]{3,}/g,`
|
|
32
|
+
)`)}));});var Zi=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 ta,na=x(()=>{g();ta=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(()=>ta.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(()=>ta.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 bs,xs,C,vs=x(()=>{g();bs=["THREAD_STATE","THREAD_PRIORITY"],xs=["gray","blue","violet","green","amber","orange","red","pink"],C=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 ra,sa,oa,ia,aa,j,q,U,da=x(()=>{g();bn();ra=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],sa=["user","agent","system"],oa=["auto","manual"],ia=["decision","judgment","issue","result","pivot"],aa=["queued","running","completed","failed"],j=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>k.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)})),q=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>k.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(()=>k.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 ua=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 Ne,la=x(()=>{g();Ne=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 _a,ga=x(()=>{g();bn();gr();sqliteTable("sidebar_states",{workspace_id:text("workspace_id").primaryKey().references(()=>te.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)`)})),_a=sqliteTable("sidebar_groups",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull().references(()=>te.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(()=>te.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),group_id:text("group_id").references(()=>_a.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(()=>te.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),group_id:text("group_id").references(()=>_a.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(()=>te.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),read_through_at:text("read_through_at").notNull()},t=>({pk:primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var ha=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 ma=x(()=>{g();sqliteTable("run_column_backfill",{name:text("name").primaryKey(),cursor:integer("cursor"),anchor_id:text("anchor_id"),completed_at:text("completed_at")});});var ka=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 ya=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(),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 $t=x(()=>{g();gr();Xt();Ai();Ni();bn();vi();Di();Pi();Mi();Hi();Ui();Bi();Wi();ji();Ki();Ji();Xi();Yi();Zi();na();vs();da();ua();la();ga();ha();ma();ka();ya();});function Ln(t){return typeof t=="string"&&ht.includes(t)}function wa(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 ht,Ar=x(()=>{g();ht=["workflow_card","workflow_ui_instance","workflow_run"];});var Zt,$s,Ea,Hs=x(()=>{g();Zt={"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":{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":{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-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.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.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}},$s=new Set(["gpt-5.3-codex-spark"]),Ea=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-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","glm-5.1","glm-5.2","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-oss-120b","grok-4.5","grok-4.6","grok-4.7"]);});function Us(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 zl(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Mn;let e=Us(t),n=jl[e];if(n)return Or[n]??Zt[n]??Mn;if(Or[e])return Or[e];if(Zt[e])return Zt[e];if($s.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Mn;if(Ea.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Mn;let r={...Zt,...Or};for(let s of Object.keys(r))if(e.includes(s))return r[s];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Mn}function Kl(t,e,n,r=0,s){let o=zl(n),i=Math.min(r,t),d=(t-i)*o.input/1e6,u=i*o.cachedInput/1e6,l=e*o.output/1e6;return d+u+l}function Ra(t,e,n,r,s,o){return t&&t>0?t:!e&&!n?0:Kl(e??0,n??0,s,r??0)}var jl,Mn,Or,Nr=x(()=>{g();Hs();Hs();jl={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"},Mn={input:0,cachedInput:0,output:0},Or={};});function Oa(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"||!Jl.includes(r))return null;let s=n.schedule_id;return typeof s=="string"&&s!==""?s:null}var Jl,Na=x(()=>{g();Jl=["cron","cron_manual"];});function qs(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function ba(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function br(t){return Number.isSafeInteger(t)&&t>0}function ep(t,e){try{let n=spawnSync(t,e,{encoding:"utf8",timeout:Fs,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:qs(n)}}}function tp(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(u){n({status:null,stdout:"",stderr:"",error:qs(u)});return}let s="",o="",i=false,c,d=setTimeout(()=>{try{r.kill();}catch{}c({status:null,stdout:s,stderr:o,error:new Error(`Command timed out after ${Fs}ms`)});},Fs);c=u=>{i||(i=true,clearTimeout(d),n(u));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",u=>{s+=String(u);}),r.stderr?.on("data",u=>{o+=String(u);}),r.once("error",u=>{c({status:null,stdout:s,stderr:o,error:u});}),r.once("close",u=>{c({status:u,stdout:s,stderr:o});});})}async function Bs(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):tp(t,e)}function np(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function rp(){return new Promise(t=>{setImmediate(t);})}function mt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return ba(n)==="ESRCH"?"not_found":ba(n)==="EPERM"?"alive":"unknown"}}function sp(t,e){let n=mt(-t,e),r=mt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function va(t,e,n,r){let s=Math.max(0,n),o=Math.max(1,r.pollIntervalMs??Ql),i=Date.now()+s,c,d=s===0,u=r.sleep?Promise.resolve().then(()=>r.sleep(s)).then(()=>{},()=>{}):new Promise(l=>{c=setTimeout(l,s);});u.then(()=>{d=true;});try{for(await rp();;){let l=sp(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([u,np(Math.min(o,p))]);}}finally{c!==void 0&&clearTimeout(c);}}async function xa(t,e,n,r,s){let o=await va(t,e,s.hardConfirmMs??Zl,{...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 Ca(t,e,n={}){if(!br(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 Bs(s,o,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let c=i.stdout.trim();if(!c)return "not_found";let d=r==="win32"?c.toLowerCase():c;return e.filter(l=>l.trim().length>0).some(l=>{let p=r==="win32"?l.toLowerCase():l;return d.includes(p)})?"owned":"not_owned"}function dp(t){let e=op.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 cp(t){let e=t.trim(),n=ap.exec(e);if(n){let[,s,o,i,c,d,u,l,p]=n;return Date.UTC(Number(s),Number(o)-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 Da(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 Pa(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=cp(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let s=ip.exec(r),o=s?dp(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 La(t,e={}){if(!br(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=Da(t,n),o=e.runCommand??ep,i;try{i=o(r,s);}catch{return {status:"unknown"}}return Pa(i,n,Date.now())}async function Ma(t,e={}){if(!br(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=Da(t,n),o;try{o=await Bs(r,s,e);}catch{return {status:"unknown"}}return Pa(o,n,Date.now())}async function Tt(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",s=_=>({status:"failed",pid:t,method:r,error:_});if(!br(t))return s("Invalid process ID");let o=e.kill??process.kill,i=mt(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 _;try{_=await Bs("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){_={status:null,stdout:"",stderr:"",error:qs(m)};}let h=mt(t,o);return h==="not_found"?_.status===0&&!_.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 c,d=e.signal??"SIGKILL";try{o(-t,d);}catch(_){c=_;}if(d==="SIGKILL")return xa(t,o,c,r,e);if(await va(t,o,e.graceMs??Yl,e)==="not_found")return c?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{o(-t,"SIGKILL");}catch(_){l=_;}let p=await xa(t,o,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?c?p:{status:"terminated",pid:t,method:r}:s(p.error??"Process termination failed")}var Fs,kt,Yl,Ql,Zl,xr,op,ip,ap,vr=x(()=>{g();Fs=3e3,kt="SIGINT",Yl=2e3,Ql=25,Zl=100;xr=3e3,op=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,ip=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,ap=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function qa(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 Ua(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,s)=>qa(r,s))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Ba(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 Fa(t){return {taskId:t.id,source:Ba(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function gp(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var Cr,Wa=x(()=>{g();ft();Ot();Nt();pt();$t();Cr=class extends Ee{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?At(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 f("NOT_FOUND","Database not found");let r=$(n);if(e)try{De(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 f("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)=>qa(o,i));if(r.length===0){let o=this.getLogState(e);if(!o)throw new f("NOT_FOUND",`Task not found: ${e}`);return o}let s=this.openHandle(true);try{return s.db.transaction(i=>{let c=this.requireStateRowInTransaction(i,e),d=Ba(c);if(d==="blob"){let _=Ua(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(et).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(o){throw o instanceof f?o:new f("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?Fa(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 gp(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=Fa(o);if(i.source==="blob"){let l=Ua(e,o.logs).map((p,_)=>({...p,seq:_+1}));return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let c=s.select({seq:et.seq,timestamp:et.timestamp,level:et.level,message:et.message}).from(et).where(eq(et.task_id,e)).orderBy(n===void 0?asc(et.seq):desc(et.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(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read task logs",s)}finally{r.close();}}};});var yp,Dr,ja=x(()=>{g();ft();Ot();Nt();pt();$t();yp=50,Dr=class extends Ee{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 De(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(Ne).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[Ne.workspace_id,Ne.actor_id,Ne.agent_id],set:{last_accepted_at:sql`MAX(${Ne.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:Ne.agent_id,lastAcceptedAt:Ne.last_accepted_at}).from(Ne).where(and(eq(Ne.workspace_id,e),eq(Ne.actor_id,n))).orderBy(desc(Ne.last_accepted_at),asc(Ne.agent_id)).limit(yp).all()}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to find recent agent sends",s)}finally{r?.close();}}};});var za=x(()=>{g();});var Z,Ht=x(()=>{g();Z=class extends Error{constructor(n,r,s){super(n);this.providerStr=r;this.name="ProviderError",this.code=s?.code??"UNKNOWN",this.kind=s?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=s?.retryAfterMs;}providerStr;code;kind;retryAfterMs;stdout};});var Ut,Ws=x(()=>{g();Ht();Ut=class extends Z{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function Ja(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 ${Te}]`),e=Ep(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${Te}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,Te),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,Te),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,Te),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,Te),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,Te),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,Te),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,Te),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,Te),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Te),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${Te}${r}${Te}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${Te}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,Ka),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,Ka),e=e.replace(/[\r\n]{3,}/g,`
|
|
33
33
|
|
|
34
|
-
`).trim(),
|
|
34
|
+
`).trim(),wp(e,1024)||void 0}function wp(t,e){let n=new TextEncoder;if(n.encode(t).byteLength<=e)return t;let r="",s=0;for(let o of t){let i=n.encode(o).byteLength;if(s+i>e)break;r+=o,s+=i;}return r}function Ep(t){let e=/\b(?:request|response|http)?\s*body\s*[:=]\s*/gim,n="",r=0,s;for(;(s=e.exec(t))!==null;){if(s.index<r)continue;let o=s.index+s[0].length,i=Rp(t,o),c=i>=0?i:t.indexOf(`
|
|
35
35
|
`,o)>=0?t.indexOf(`
|
|
36
|
-
`,o):t.length;n+=t.slice(r,s.index),n+=`[HTTP BODY ${
|
|
37
|
-
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>
|
|
36
|
+
`,o):t.length;n+=t.slice(r,s.index),n+=`[HTTP BODY ${Te}]`,r=c;}return n+t.slice(r)}function Rp(t,e){let n=t[e];if(n==='"'||n==="'")return Sp(t,e,n);if(n!=="{"&&n!=="[")return -1;let r=[],s,o=false;for(let i=e;i<t.length;i+=1){let c=t[i];if(s){o?o=false:c==="\\"?o=true:c===s&&(s=void 0);continue}if(c==='"'||c==="'"){s=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 Sp(t,e,n){let r=false;for(let s=e+1;s<t.length;s+=1){let o=t[s];if(r)r=false;else if(o==="\\")r=true;else if(o===n)return s+1}return -1}var Te,Ka,Va=x(()=>{g();Te="[REDACTED]",Ka="[PATH]";});function js(t){if(!Pr(t)||t.type!=="item.started"||!Ya(t)||!Xa(t))return false;let e=t.item;return !Pr(e)||!Ya(e)||!Xa(e)||!Gs(e.id)?false:e.type==="web_search"?e.query===""&&Pr(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=>Pr(n)&&Gs(n.path)&&Gs(n.kind)):false}function Pr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Qa(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Gs(t){return typeof t=="string"&&t.trim().length>0}function Xa(t){return !Qa(t,"status")||t.status==="in_progress"}function Ya(t){for(let e of ["error","errors","isError","is_error"])if(Qa(t,e))return false;return true}var zs=x(()=>{g();});function Ip(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let s=r.type;if(typeof s!="string")return false;let o=e?Dp[e]:void 0;return o?o(r,s):Object.values(ed).some(i=>i(r,s))}function st(t,e){let n=t.split(`
|
|
37
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>Ip(r,e))}function be(t){return typeof t=="object"&&t!==null}function Za(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 Ap(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:Za(t,e)}function Op(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 Np(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||be(t.part):e==="text"||e==="tool_use"?be(t.part):e==="result"?typeof t.result=="string":false}function bp(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||be(t.part)||e==="result"&&typeof t.result=="string")}function xp(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?be(t.data):e==="result"?typeof t.result=="string":false}function vp(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 Cp(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 ed,Dp,en=x(()=>{g();zs();ed={claude:Za,codex:Op,opencode:Np,copilot:xp,gemini:vp},Dp={...ed,claude:Ap,opencode:bp,grok:Cp,antigravity:()=>false};});function ot(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function it(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 tn=x(()=>{g();});function Mp(t){let e=$p(t),n=e.map((o,i)=>({line:o,index:i})).filter(({line:o})=>Up(o.value)),r=Hp(e);return {result:n.length===1&&n[0].index===r?Fp(n[0].line.value):null,resultPreview:Wp(e,n),hasReservedLine:n.length>0}}function qe(t,e){let n=Mp(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function $p(t){let e=[],n=0;for(let r=0;r<t.length;r++){let s=t[r];if(s!==`
|
|
38
38
|
`&&s!=="\r")continue;let o=s==="\r"&&t[r+1]===`
|
|
39
39
|
`?`\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 Rp(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Sp(t){return t.trimStart().startsWith(Tp)}function Ip(t){let e=t.trim();if(!e.startsWith(ja)||!e.endsWith("]]"))return null;let n=e.slice(ja.length,-2);if(!n)return null;try{return Ap(JSON.parse(n))}catch{return null}}function Ap(t){return Op(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Op(t){if(!Np(t)||Object.keys(t).some(r=>!wp.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?za(t.taskId)&&za(t.agentId):t.isError===true}function bp(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 za(t){return typeof t=="string"&&t.trim().length>0}function Np(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var ja,Tp,wp,Vt=v(()=>{_();ja="[[crewx:delegation-result ",Tp="[[crewx:delegation-result",wp=new Set(["schema","taskId","agentId","isError"]);});function He(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 Xt=v(()=>{_();});var Ka,br,Fs,Nr=v(()=>{_();Ka=["none","minimal","low","medium","high","xhigh","max","ultra"],br={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"]},Fs={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-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-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:[],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.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-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-6-thinking",name:"Claude Opus 4.6 Thinking",contextWindowTokens:1e6,tier:"flagship"},{id:"gpt-oss-120b",name:"GPT-OSS 120B",contextWindowTokens:128e3,tier:"balanced"}],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.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-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(Fs).map(([t,e])=>[t,e.models]));});function qs(t){return vp[t]??t}function Pp(t){return Cp.get(t)??t}function Bs(t){if(!t)return {};let e=Lp.get(t);return e?{...e}:{model:t}}function Ws(t,e){return t==="antigravity"||t==="cli/antigravity"?Bs(e):e===void 0?{}:{model:Pp(e)}}var xp,vp,Cp,Dp,Lp,vn=v(()=>{_();xp=[{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]"}],vp={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Cp=new Map(xp.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Dp=[{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"}],Lp=new Map(Dp.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function $p(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function ht(t){return xr(t).models}function xr(t){return Mp[t]??Fs[t]??$p()}function Cn(t,e){let n=xr(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Ws(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Ja(t){return xr(t).modelOverrides}function Va(){return ht("claude")}function Xa(){return ht("codex")}function Ya(){return ht("copilot")}function Qa(){return ht("antigravity")}var Mp,Dt=v(()=>{_();Nr();yr();vn();Mp={};});function Za(t){return Hp[t]??t}var Hp,ed=v(()=>{_();Dt();vn();Hp={auto:"default"};});function vr(t,e){return (br[t]??[]).includes(e)}function mt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Up.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function td(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 nd(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 rd(t){return !t||!vr("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function sd(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Za(t);return e.has(n)?["--permission-mode",n]:[]}function od(t){return t?vr("claude",t)?["--effort",t]:[]:[]}function id(t){return t==="default"?[]:t&&Fp.has(t)?["--permission-mode",t]:[]}function ad(t){return t===true?["--always-approve"]:[]}function dd(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 ud(t){return t?vr("grok",t)?["--effort",t]:[]:[]}function cd(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 ld(t){return t?vr("antigravity",t)?["--effort",t]:[]:[]}var Up,Fp,Pn=v(()=>{_();ed();vn();Nr();Up=new Set(Ka);Fp=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function qp(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 Bp(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 Wp(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),o=n.cache,i=o?Number(o.read??0):0;return {inputTokens:r+i,outputTokens:s,cachedInputTokens:i}}function pd(t){let e=new Map,n;for(let o of t.split(`
|
|
41
|
-
`))if(o.trim())try{let i=JSON.parse(o);if(i.type!=="assistant")continue;let
|
|
42
|
-
`))if(r.trim())try{let s=JSON.parse(r),o=
|
|
43
|
-
`).filter(s=>s.trim()),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="assistant"&&Array.isArray(o.message?.content))for(let i of o.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function
|
|
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=
|
|
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 Hp(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Up(t){return t.trimStart().startsWith(Pp)}function Fp(t){let e=t.trim();if(!e.startsWith(td)||!e.endsWith("]]"))return null;let n=e.slice(td.length,-2);if(!n)return null;try{return qp(JSON.parse(n))}catch{return null}}function qp(t){return Bp(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Bp(t){if(!Gp(t)||Object.keys(t).some(r=>!Lp.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?nd(t.taskId)&&nd(t.agentId):t.isError===true}function Wp(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 nd(t){return typeof t=="string"&&t.trim().length>0}function Gp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var td,Pp,Lp,nn=x(()=>{g();td="[[crewx:delegation-result ",Pp="[[crewx:delegation-result",Lp=new Set(["schema","taskId","agentId","isError"]);});function Be(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 rn=x(()=>{g();});var rd,Lr,Ks,Mr=x(()=>{g();rd=["none","minimal","low","medium","high","xhigh","max","ultra"],Lr={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"]},Ks={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-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-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:[],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.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-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-6-thinking",name:"Claude Opus 4.6 Thinking",contextWindowTokens:1e6,tier:"flagship"},{id:"gpt-oss-120b",name:"GPT-OSS 120B",contextWindowTokens:128e3,tier:"balanced"}],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.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-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(Ks).map(([t,e])=>[t,e.models]));});function Js(t){return zp[t]??t}function Jp(t){return Kp.get(t)??t}function Vs(t){if(!t)return {};let e=Xp.get(t);return e?{...e}:{model:t}}function Xs(t,e){return t==="antigravity"||t==="cli/antigravity"?Vs(e):e===void 0?{}:{model:Jp(e)}}var jp,zp,Kp,Vp,Xp,Hn=x(()=>{g();jp=[{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]"}],zp={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Kp=new Map(jp.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Vp=[{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"}],Xp=new Map(Vp.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Qp(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function yt(t){return $r(t).models}function $r(t){return Yp[t]??Ks[t]??Qp()}function Un(t,e){let n=$r(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Xs(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function sd(t){return $r(t).modelOverrides}function od(){return yt("claude")}function id(){return yt("codex")}function ad(){return yt("copilot")}function dd(){return yt("antigravity")}var Yp,Ft=x(()=>{g();Mr();Nr();Hn();Yp={};});function cd(t){return Zp[t]??t}var Zp,ud=x(()=>{g();Ft();Hn();Zp={auto:"default"};});function Hr(t,e){return (Lr[t]??[]).includes(e)}function wt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return ef.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function ld(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 pd(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 fd(t){return !t||!Hr("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function _d(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=cd(t);return e.has(n)?["--permission-mode",n]:[]}function gd(t){return t?Hr("claude",t)?["--effort",t]:[]:[]}function hd(t){return t==="default"?[]:t&&tf.has(t)?["--permission-mode",t]:[]}function md(t){return t===true?["--always-approve"]:[]}function kd(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 Td(t){return t?Hr("grok",t)?["--effort",t]:[]:[]}function yd(t){if(!t)return [];switch(Js(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function wd(t){return t?Hr("antigravity",t)?["--effort",t]:[]:[]}var ef,tf,Fn=x(()=>{g();ud();Hn();Mr();ef=new Set(rd);tf=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function nf(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 rf(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,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:s,cachedInputTokens:d}}function sf(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),o=n.cache,i=o?Number(o.read??0):0;return {inputTokens:r+i,outputTokens:s,cachedInputTokens:i}}function Ed(t){let e=new Map,n;for(let o of t.split(`
|
|
41
|
+
`))if(o.trim())try{let i=JSON.parse(o);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,s=0;for(let o of e.values())r+=o.inputTokens,s+=o.cachedInputTokens;return {inputTokens:r,cachedInputTokens:s,model:n}}function sn(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
|
|
42
|
+
`))if(r.trim())try{let s=JSON.parse(r),o=sf(s);if(o){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=o.inputTokens,n.outputTokens+=o.outputTokens,n.cachedInputTokens+=o.cachedInputTokens;continue}let i=nf(s)??rf(s);i&&(e=i);}catch{}return n||(e??void 0)}var qn=x(()=>{g();});function We(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 qt=x(()=>{g();});var Ur,Rd=x(()=>{g();Ur=Object.freeze({CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"});});function Sd(t){let e=t.split(`
|
|
43
|
+
`).filter(s=>s.trim()),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="assistant"&&Array.isArray(o.message?.content))for(let i of o.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Id(t){let e=t.split(`
|
|
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 on(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function xd(t){let e=on(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=lf(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(pf(n))return `Claude rate limit: ${n}`}}function df(t){for(let e of t.split(`
|
|
45
|
+
`)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=on(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 cf(t){let e=on(t);if(e?.type!=="rate_limit_event")return;let n=on(on(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=Ad(n.five_hour),s=Ad(n.seven_day);if(!(!r&&!s))return {...r?{five_hour:r}:{},...s?{seven_day:s}:{}}}function Ad(t){let e=on(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function Od(t){if(t?.is_error===true)return Ja(t.result)}function uf(t){let e=xd(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",s=typeof t.terminal_reason=="string"?t.terminal_reason:"unknown";return `Claude ended without an answer (subtype=${r}, terminal_reason=${s})`}function lf(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
46
46
|
|
|
47
|
-
`):""}function
|
|
48
|
-
`):i=JSON.stringify(o),{timestamp:t,type:"tool_result",toolUseId:s
|
|
49
|
-
`);for(let r of e)if(r.trim())try{let s=JSON.parse(r);if(s.type==="result"){let o=s.usage,i=o?{inputTokens:Number(o.input_tokens??0)+Number(o.cache_read_input_tokens??0),outputTokens:Number(o.output_tokens??0),cachedInputTokens:Number(o.cache_read_input_tokens??0),costUsd:Number(s.total_cost_usd??0)}:null,
|
|
50
|
-
`).filter(s=>s.trim()),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="assistant.message"&&typeof o.data?.content=="string"){let i=o.data.content;i.trim()&&n.push(i.trim());}o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var
|
|
51
|
-
`).map(s=>s.trim()).filter(Boolean),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="item.completed"&&(o.item?.type==="message"||o.item?.type==="agent_message")&&typeof o.item?.text=="string"){let i=o.item.text;i.trim()&&n.push(i.trim());}o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function
|
|
52
|
-
`),u=typeof e.error=="string"?e.error:kt(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||u,isError:e.status==="failed"||e.status==="error"||e.is_error===true||e.error!=null,...n?{toolUseId:n}:{}}}if(r==="tool_use"){let s=String(e.name||e.tool_name||""),o=e.input,i=He(o);return s==="Bash"&&tt(i)?nt(t,i):{timestamp:t,type:"tool_use",toolName:s,toolInput:i}}if(r==="tool_result"){let s=!!e.is_error,o=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...$e(o,s)}}if(r==="web_search"){let s=e.action,o;if(s?.type==="search"){let i=s.queries;o=String(s.query||"")||(i?.length?i.join(", "):"")||String(e.query||"");}else o=e.query?"open: "+String(e.query):"";return !o&&!(kt(s)&&s.type==="other"&&e.query==="")?null:{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:o}}if(r==="file_change"){let s=e.changes;if(!Array.isArray(s)||s.length===0)return null;let o=s.map(u=>String(u.path||"")).filter(Boolean);if(o.length===0)return null;let i=o.length===1?o[0]:`${o.slice(0,2).join(", ")}${o.length>2?` (+${o.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:i}}return null}function df(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||""),s=e.input,o=He(s);return r==="Bash"&&tt(o)?nt(t,o):{timestamp:t,type:"tool_use",toolName:r,toolInput:o}}return null}var ef,tf,Ks,Js=v(()=>{_();Ct();Kt();Dn();Jt();Xt();Us();Vt();Pn();Dt();Lt();ef=new Set(["turn.started","turn.completed","item.updated"]),tf="cli/codex";Ks={command:"codex",meta:{displayName:"Codex",models:Xa(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:s}=mt(e.model),o=e.effort??s,i=e.resumeSessionId?nd(e.mode):td(e.mode),u=rd(o),d=r?["-m",r]:[],c=rf(e.additionalArgs??[]),p=c.includes("--json")||c.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...p,...i,...u,...d,...c,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...p,...i,...u,...d,...c],stdinMessage:t}},extractText(t){let e=sf(t);if(e)throw new Z(e,tf);let n=Ed(t);if(n)return n;let r=t.trim();return et(r,"codex")?"":r},extractPartialText(t){return Ed(t)},parseResultMeta(t){let e=Yt(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(),s=[],o;try{JSON.parse(t),o=[t];}catch{o=nf(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,u]of o.entries()){let d;try{d=JSON.parse(u);}catch{continue}if(!kt(d))continue;let c=d.type;if(!c)continue;let l=Ue(d,r);if(Sd(d)){let g=Id(d);s.push({timestamp:l,type:"error",content:g,errorMessage:g});continue}if(!c.startsWith("item.")&&!c.startsWith("turn.")&&!c.startsWith("thread.")||Hs(d))continue;c==="thread.started"&&n&&n.state.delete("codex.pending");let p=d.item;if(p){if(c==="item.started"){s.push(...of(l,p,Rd(p,c,n,i)));continue}if(c==="item.completed"){let g=af(l,p,Rd(p,c,n,i));g&&s.push(g);continue}}}return s},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?ef.has(r):!1}catch{return false}}};});function lf(t){return t?cf[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Dr(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function xd(t){let e=[],n=0,r=false,s=false,o=0;for(let u=0;u<t.length;u++){let d=t[u];if(s){s=false;continue}if(d==="\\"&&r){s=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let c=t.slice(o,u+1).trim();c&&e.push(c),o=u+1;}}}let i=t.slice(o).trim();return i&&e.push(i),e}function en(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pf(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let s=r.trim();if(!s)continue;try{let i=JSON.parse(s);en(i)?e.push(i):n=!0;continue}catch{}let o=xd(s);o.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of o)try{let u=JSON.parse(i);en(u)?e.push(u):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Mt(t){if(typeof t!="string")return;let e=t.split(/\r?\n/).map(n=>n.trim()).find(n=>n&&!/^at\s+/.test(n));if(e)return e.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").replace(/(?:[A-Za-z]:[\\/]|\/)(?:[^\s"'`()\[\]{}]+[\\/])*[^\s"'`()\[\]{}]+/g,"[path]").slice(0,Nd).trim()}function vd(t){let e=en(t.error)?t.error:void 0,n=e&&en(e.data)?e.data:void 0,r=Mt(e?.name),s=Mt(n?.message)??Mt(e?.message)??Mt(t.message)??Mt(t.errorMessage)??Mt(t.error),o=Mt(t.ref),i=r&&s&&r!==s?`${r}: ${s}`:r??s??bd;return (o?`${i} (ref: ${o})`:i).slice(0,Nd)}function Ad(t){let e=pf(t),n=[],r=null,s=0,o=[],i,u=false;for(let d of e.events){let c=typeof d.type=="string"?d.type:void 0;if(c){if(c==="text"){let l=en(d.part)?d.part:void 0,p=typeof l?.text=="string"?l.text:void 0;p?.trim()&&n.push(p.trim());continue}if(c==="result"){typeof d.result=="string"&&(r=d.result);continue}if(c==="tool_use"){s++;continue}if(c==="error"){o.push(vd(d));continue}if(c==="step_finish"){u=true;let l=en(d.part)?d.part:void 0;i=typeof l?.reason=="string"?l.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:s,errorMessages:o,terminalReason:i,hasTerminal:u}}function Cd(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Lr(){return new Z("OpenCode returned no assistant output.",Zt,{code:"EMPTY_OUTPUT",kind:"transient"})}function ff(){return new Z("OpenCode emitted malformed JSON output.",Zt,{code:"PROVIDER_CRASHED",kind:"transient"})}function Od(t,e){switch(Cd(t)){case "length":return new Z("OpenCode stopped because the context window was exceeded.",Zt,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new Z("OpenCode stopped because the content filter blocked the response.",Zt,{code:"UNKNOWN",kind:"permanent"});case "error":return new Z(e?`OpenCode error: ${e}`:`${bd} while generating a response.`,Zt,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var uf,Zt,bd,Nd,cf,Vs,Xs=v(()=>{_();Ct();Dn();Xt();Lt();uf=new Set(["step_start","step_finish"]),Zt="cli/opencode",bd="OpenCode provider error",Nd=240,cf={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};Vs={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,s=r!==void 0?[...r]:["run"];Dr(s,"--format")||s.push("--format","json"),e.resumeSessionId&&!s.includes("-s")&&!s.includes("--session")&&s.push("-s",e.resumeSessionId);let{agent:o,autoApprove:i}=lf(e.mode);Dr(s,"--agent")||o!==void 0&&s.push("--agent",o),i&&!Dr(s,"--auto")&&s.push("--auto"),e.effort!==void 0&&!Dr(s,"--variant")&&s.push("--variant",e.effort),e.model&&s.push("--model",e.model);let u;return !n&&!i&&!e.env?.OPENCODE_PERMISSION&&(u={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:s,stdinMessage:t,env:u}},extractText(t){let e=Ad(t),n=e.errorMessages[0];if(n){let i=Od("error",n);if(i)throw i}let r=Od(e.terminalReason??"",void 0);if(r)throw r;let s=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(s!==void 0){if(!e.hasTerminal)throw Lr();return s}if(e.resultText?.trim()){if(!e.hasTerminal)throw Lr();return e.resultText}if(e.malformed)throw ff();if(!e.hasTerminal)throw Lr();let o=Cd(e.terminalReason);if((o==="stop"||o==="tool-calls")&&e.toolUseCount>0)return "";throw Lr()},interpretExit(t,e,n=""){if(t===0)return null;let s=Ad(n).errorMessages[0];return s?new Z(`OpenCode error: ${s}`,Zt,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=Yt(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=xd(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=Ue(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||""),g=c.state,h=String(g?.status||""),m=g?.input,E=He(m);if(r.push({timestamp:u,type:"tool_use",toolName:l,toolUseId:p,toolInput:E}),h==="completed"&&g?.output!==void 0){let S=g.output,P=typeof S=="string"?S:JSON.stringify(S);r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:P,isError:false});}else h==="error"&&r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(d==="error"){let c=vd(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?uf.has(r):!1}catch{return false}}};});function Ln(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function gf(t,e){if(!(t?ht(Ys).some(o=>o.id===t):false)||!t)return e;let r=Cn(Ys,t),s=Ja(Ys)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:s&&r.includes(s)?s:void 0:s}var Ys,Qs,Zs=v(()=>{_();Ct();vn();Dt();Pn();Ys="antigravity";Qs={command:"agy",meta:{displayName:"Antigravity",models:Qa(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:s}=mt(e.model),o=Bs(r),i=o.model,u=e.effort??s??o.effort,d=gf(i,u),c=e.additionalArgs??[],l=i&&!Ln(c,"--model")?["--model",i]:[],p=Ln(c,"--effort")?[]:ld(d),g=Ln(c,"--mode")||Ln(c,"--dangerously-skip-permissions")?[]:cd(e.mode),h=Ln(c,"--print")?[]:["--print",t];return {args:[...l,...p,...g,...c,...h]}},extractText(t){let e=t.trim();if(!e)throw new Z("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"});return e},parseResultMeta(t){return {usage:null,model:null}},parseEvent(t,e){return []}};});var Pd=v(()=>{_();Jt();Xt();Vt();Lt();});function tn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function nn(t){return tn(t)?t:void 0}function ye(t){return typeof t=="string"?t:void 0}function Ht(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Tf(t){let e=[],n=-1,r=0,s=false,o=false;for(let i=0;i<t.length;i+=1){let u=t[i];if(n===-1){(u==="{"||u==="[")&&(n=i,r=1);continue}if(o){o=false;continue}if(u==="\\"&&s){o=true;continue}if(u==='"'){s=!s;continue}s||(u==="{"||u==="["?r+=1:(u==="}"||u==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function Mn(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return tn(n)?[n]:[]}catch{return Tf(e).flatMap(n=>{try{let r=JSON.parse(n);return tn(r)?[r]:[]}catch{return []}})}}function Hd(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function $t(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map($t).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
53
|
-
`):void 0}if(
|
|
54
|
-
`)||
|
|
55
|
-
`;
|
|
56
|
-
`).flatMap(
|
|
57
|
-
`),s=r.length>
|
|
58
|
-
`).flatMap(
|
|
59
|
-
`).flatMap(
|
|
60
|
-
`)??"";if(!n.trim())return;let r=Wd(t.provider);if(!r)return;let s;try{s=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let o=Of(s?.model,t.model),i=s?.usage;if(!i)return {stdout:n,adapter:r};let u=$r(i.inputTokens),d=$r(i.outputTokens),c=$r(i.cachedInputTokens),l=fa($r(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}}:{stdout:n,adapter:r}}var no=v(()=>{_();Gd();yr();});function so(t){let e=new Set;for(let n of t)for(let r of bf.get(n)??[n])e.add(r);return [...e]}function oo(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"&&Nf.has(n)?n:void 0}catch{return}}function Fe(t){let e=oo(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(ro.stopped.test(t.error))return "user_stop";if(ro.runnerLost.test(t.error))return "runner_lost"}}function Oe(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=oo(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&ro.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function xf(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function $n(t){let e=Oe(t);return t.status==="runner_lost"&&oo(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...xf(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}var Ut,bf,ro,Nf,Hn=v(()=>{_();Ut=["success","completed","done","failed","error","stopped","runner_lost"],bf=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);ro={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},Nf=new Set(["user_stop","runner_lost","launch_failed"]);});function io(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 Fn(){return io("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function sn(){return io("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function Fr(){return io("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function rn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Ur(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 vf(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 jd(t,e){return !!t.stop_requested_at&&rn(t.stop_requested_epoch)===rn(e)}function zd(t,e){let n=rn(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let s=vf(t.getTask(e.taskId));return !s||s.status!=="running"||rn(s.run_epoch)!==n?{accepted:false,row:s}:{accepted:true,row:s}}function Xd(t,e){let n=Un.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),Un.delete(t),true)}function qn(t,e){let n=Un.get(t);return !n||e!==void 0&&n.runEpoch!==rn(e)?false:Xd(t,n)}function Yd(t,e){let n=rn(e.runEpoch);qn(e.taskId);let r=true,s=null;try{let c=zd(t,{...e,runEpoch:n});r=c.accepted,s=c.row;}catch(c){Ur(c);}if(!r)return false;let o=Fn(),i=Math.min(o,1e3),u=setInterval(()=>{let c=Un.get(e.taskId);if(!(!c||c.timer!==u))try{c.heartbeatElapsedMs+=i;let l=c.heartbeatElapsedMs>=o,p=zd(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){Xd(e.taskId,c);return}l&&(c.heartbeatElapsedMs%=o,c.lastHeartbeatAt=Date.now()),p.row&&jd(p.row,n)&&!c.stopRequested&&(c.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(Ur));}catch(l){Ur(l);}},i),d={timer:u,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return Un.set(e.taskId,d),typeof u=="object"&&u!==null&&"unref"in u&&u.unref(),s&&jd(s,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(s)).catch(Ur)),true}var Kd,Jd,Vd,Un,Bn=v(()=>{_();Kd=1e4,Jd=3e4,Vd=18e5;Un=new Map;});function qr(t,e=Date.now(),n=lo){let r=t?Date.parse(t):Number.NaN,s=typeof e=="number"?e:Date.parse(e),o=go(n,lo,0);return Number.isFinite(r)&&Number.isFinite(s)&&s-r>o?"forced":"cooperative"}function mo(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=nu(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 ko(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??Ea,u=e.processControl?.readProcessIdentityAsync??Aa,d;try{d=await i(t.pid,e.ownershipMarkers??Pf,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)>Rr)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 To(t,e={}){let n=await ko(t,e);return n.verdict==="owned"?"owned":n.verdict==="reused"?"not_owned":n.ownership}function go(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function nu(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function Ff(t){if(!t)return;let e=nu(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function be(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=Ff(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function wo(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 V(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 co(t,e){return V(t,Lf,e)}function qf(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=sn():false}function Bf(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Wf(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return be(r,n)}async function Gf(t,e,n,r){let s=Date.now()+n;for(;;){let o=Wf(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 tu(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 x=t.stopPendingTask(e,void 0,void 0,{...s,at:r}),I=t.getTask(e);if(x||!I||I.status!=="running")return be(I);if(o=t.requestTaskStop({id:e,requestedAt:r,...s}),!o.accepted&&o.status!=="running"||!o.accepted&&!o.alreadyRequestedAt)return be(t.getTask(e))}else if(!(o.status==="running"&&o.alreadyRequestedAt))return be(i)}let u=o.runEpoch,d=go(n.graceMs,lo,0),c=go(n.pollMs,Cf,1),l=await Gf(t,e,d,c);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return be(p);let g=mo(p),h=g.map(x=>x.pid),m=h[0];if(!m){let x=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),I=t.getTask(e);return x||I?.status!=="running"?be(I):V(I,"Failed to finalize task stop")}let E=Bf(n);if(!qf(p,Date.now())){for(let x of g)if(await To(x,{ownershipMarkers:n.ownershipMarkers,processControl:n.processControl,processControlOptions:E})!=="owned")return wo(p)}let S=n.processControl?.terminateProcessTree??_t;for(let x of h){let I;try{I=await S(x,{...E,signal:gt});}catch(b){I={status:"failed",pid:x,method:E.platform==="win32"?"taskkill":"process-group",error:b instanceof Error?b.message:String(b)};}if(I.status==="failed")return V(t.getTask(e),I.error??"Failed to terminate process tree")}let P=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),w=t.getTask(e);return P||w?.status!=="running"?be(w,m):V(w,"Task changed before stop was finalized")}function _o(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function ho(t){return Number.isSafeInteger(t)&&t>=0}function Wn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function jf(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function zf(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Kf(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 Jf(t){switch(t){case "epoch_mismatch":return po;case "workspace_mismatch":return fo;default:return}}async function ru(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return co(n,_o(e.targetPid)?e.targetPid:void 0);if(!ho(e.sourceRunEpoch)||!ho(e.settleRunEpoch)||Wn(n.run_epoch)!==e.settleRunEpoch)return V(n,ao,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return V(n,uo,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 V(n,Mf,e.targetPid)}let o=t.getTask(e.taskId);if(!o||o.status!=="running")return co(o,e.targetPid);if(s.runEpoch!==e.settleRunEpoch||Wn(o.run_epoch)!==e.settleRunEpoch)return V(o,ao,e.targetPid);if(e.workspaceId!==void 0&&o.workspace_id!==e.workspaceId)return V(o,uo,e.targetPid);if(!_o(e.targetPid))return V(o,Df);let i=jf(e);if(await To({pid:e.targetPid,startedAt:o.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:i})!=="owned")return wo(o,e.targetPid);let d=t.getTask(e.taskId);if(!d||d.status!=="running")return co(d,e.targetPid);if(Wn(d.run_epoch)!==e.settleRunEpoch)return V(d,ao,e.targetPid);if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId)return V(d,uo,e.targetPid);let c=e.processControl?.terminateProcessTree??_t,l;try{l=await c(e.targetPid,{...i,signal:gt});}catch{return V(t.getTask(e.taskId),Qd,e.targetPid)}if(l.status==="failed")return V(t.getTask(e.taskId),Qd,e.targetPid);let p;try{p=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return V(t.getTask(e.taskId),Zd,e.targetPid)}return p?be(t.getTask(e.taskId),e.targetPid):V(t.getTask(e.taskId),Zd,e.targetPid)}async function su(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return be(n);if(!ho(e.expectedRunEpoch)||Wn(n.run_epoch)!==e.expectedRunEpoch)return V(n,po);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return V(n,fo);let r=n.pid;if(!_o(r))return V(n,$f);let s=zf(e);if(await To({pid:r,startedAt:n.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:s})!=="owned")return wo(n,r,Hf);let i=e.processControl?.terminateProcessTree??_t,u;try{u=await i(r,{...s,signal:gt});}catch{return V(t.getTask(e.taskId),eu,r)}if(u.status==="failed")return V(t.getTask(e.taskId),eu,r);let d=t.getTask(e.taskId);if(!d||d.status!=="running")return be(d,r);if(Wn(d.run_epoch)!==e.expectedRunEpoch)return V(d,po,r);if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId)return V(d,fo,r);let c;try{c=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return V(t.getTask(e.taskId),Uf,r)}let l=Jf(c);return l?V(t.getTask(e.taskId),l,r):c!=="settled"?be(t.getTask(e.taskId),r):Kf(t.getTask(e.taskId),r)}function ou(t,e,n={}){if(typeof t=="string"){let r=t,s=e??{};return Promise.resolve().then(()=>(Eo(),iu)).then(({TaskRepository:o})=>tu(new o,r,s))}return tu(t,e,n)}var lo,Cf,Pf,Df,ao,uo,Lf,Qd,Zd,Mf,po,fo,$f,Hf,eu,Uf,yo=v(()=>{_();Sr();Bn();lo=5e3,Cf=250;Pf=["crewx","claude","codex","opencode","grok","node"];Df="INSTRUCTION_STOP_TARGET_PID_MISSING",ao="INSTRUCTION_STOP_EPOCH_MISMATCH",uo="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Lf="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",Qd="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",Zd="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Mf="INSTRUCTION_STOP_REQUEST_FAILED",po="HOST_SHUTDOWN_EPOCH_MISMATCH",fo="HOST_SHUTDOWN_WORKSPACE_MISMATCH",$f="HOST_SHUTDOWN_TARGET_PID_MISSING",Hf="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",eu="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",Uf="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var iu={};Vu(iu,{CANONICAL_USER_STOP_ERROR:()=>Co,DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>gu,HOST_SHUTDOWN_TERMINAL_ERROR:()=>lu,PENDING_ADOPT_GRACE_MS:()=>fu,PID_NULL_REAP_GRACE_MS:()=>Lo,RATED_TASK_EXCERPT_MAX_CHARS:()=>Mo,RATED_TASK_LIST_MAX_LIMIT:()=>hu,TASK_HEARTBEAT_HARD_STALE_MS:()=>Vd,TASK_HEARTBEAT_INTERVAL_MS:()=>Kd,TASK_HEARTBEAT_STALE_MS:()=>Jd,TASK_RATINGS:()=>_u,TaskRatingError:()=>Jn,TaskRepository:()=>Kn,WORKFLOW_ANCHOR_TASK_KINDS:()=>pt,buildRatedTasksCountQuery:()=>ku,buildRatedTasksQuery:()=>mu,countRatedTasks:()=>pg,hasRecordedUsage:()=>Do,isWorkflowAnchorTaskKind:()=>bn,listRatedTasks:()=>lg,mergeTerminalReason:()=>Po,resolveTaskHeartbeatHardStaleMs:()=>Fr,resolveTaskHeartbeatIntervalMs:()=>Fn,resolveTaskHeartbeatStaleMs:()=>sn,setTaskRating:()=>cg});function Be(t){return $n(t)}function So(t){return $n(t)}function Io(){return or(...pt.map(t=>like(a.metadata,`%"kind":"${t}"%`)))}function au(){return and(...pt.map(t=>notLike(a.metadata,`%"kind":"${t}"%`)))}function Oo(t=a.model,e=a.metadata){let n=sql`
|
|
47
|
+
`):""}function pf(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function bd(t){return t.replace(/\s+/g," ").trim()}function ff(t,e){let n=t?.description;if(typeof n!="string")return;let r=bd(n);if(!r||r===bd(e))return;if(r.length<=Nd)return r;let s=r.slice(0,Nd-1);return /[\uD800-\uDBFF]$/.test(s)&&(s=s.slice(0,-1)),`${s}\u2026`}function _f(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||""),s=e.id,o=e.input,i=Be(o);if(r==="Bash"&&ot(i))return it(t,i,s);let c=ff(o,i);return {timestamp:t,type:"tool_use",toolUseId:s,toolName:r,toolInput:i,...c?{toolTitle:c}:{}}}if(n==="tool_result"){let r=!!e.is_error,s=e.tool_use_id,o=e.output??e.content??"",i;return typeof o=="string"?i=o:Array.isArray(o)?i=o.filter(c=>c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
|
|
48
|
+
`):i=JSON.stringify(o),{timestamp:t,type:"tool_result",toolUseId:s,...qe(i,r)}}return null}var of,af,Fr,Nd,Ys=x(()=>{g();Ws();Ht();Va();en();tn();nn();rn();Fn();Ft();qn();qt();Rd();of=new Set(["tool_progress"]),af="cli/claude";Fr={command:"claude",meta:{displayName:"Claude",models:od(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:s}=wt(e.model),o=e.effort??s,i=_d(e.mode),c=gd(o),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:Ur}:{args:["--output-format","stream-json","--verbose",...u,...i,...c,...d,...p],stdinMessage:t,env:Ur}}return {args:["-p","--output-format","stream-json","--verbose",...u,...i,...c,...d],stdinMessage:t,env:Ur}},extractText(t){let e=Id(t);if(e?.is_error===true){let s=Fr.extractFailure(JSON.stringify(e));if(s)throw s;let o=typeof e.subtype=="string"?e.subtype:"unknown",i=typeof e.terminal_reason=="string"?e.terminal_reason:"unknown";throw new Z(Od(e)??`Claude ended without an answer (subtype=${o}, terminal_reason=${i})`,af,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=Sd(t);if(n)return n;let r=t.trim();return st(r,"claude")?"":r},extractPartialText(t){return Sd(t)},extractFailure(t){try{let e=JSON.parse(t),n=xd(e);if(n)return new Ut(n)}catch{}return null},interpretExit(t,e,n){let r=df(n??"");if(r)return new Z(`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 s=Od(Id(n??""));return s?new Z(s,"cli/claude"):null},observeRateLimit(t){try{let e=JSON.parse(t);return cf(e)}catch{return}},parseResultMeta(t){let e=t.split(`
|
|
49
|
+
`);for(let r of e)if(r.trim())try{let s=JSON.parse(r);if(s.type==="result"){let o=s.usage,i=o?{inputTokens:Number(o.input_tokens??0)+Number(o.cache_read_input_tokens??0),outputTokens:Number(o.output_tokens??0),cachedInputTokens:Number(o.cache_read_input_tokens??0),costUsd:Number(s.total_cost_usd??0)}:null,c=s.modelUsage,d=c?Object.keys(c)[0]??null:null;return {usage:i,model:d}}}catch{}let n=Ed(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 s=We(n,e??new Date().toISOString()),o=uf(n);if(o)return [{timestamp:s,type:"error",content:o,errorMessage:o}];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:s,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 _=_f(s,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?of.has(r):!1}catch{return false}}};Nd=200;});function vd(t){let e=t.split(`
|
|
50
|
+
`).filter(s=>s.trim()),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="assistant.message"&&typeof o.data?.content=="string"){let i=o.data.content;i.trim()&&n.push(i.trim());}o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var gf,Qs,Zs=x(()=>{g();en();qn();tn();rn();nn();Ft();Mr();qt();gf=new Set(["interactive","plan","autopilot"]);Qs={command:"copilot",meta:{displayName:"Copilot",models:ad()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&gf.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Lr.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=vd(t);if(e)return e;let n=t.trim();return st(n,"copilot")?"":n},extractPartialText(t){return vd(t)},parseResultMeta(t){let e=sn(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 s=n.data;if(!s)return [];let o=We(n,e??new Date().toISOString()),i=s.toolCallId;if(r==="tool.execution_start"){let c=String(s.toolName||""),d=s.arguments,u=Be(d);return (c==="bash"||c==="Bash")&&ot(u)?[it(o,u,i)]:[{timestamp:o,type:"tool_use",toolName:c,toolInput:u,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let c=s.error;if(c)return [{timestamp:o,type:"tool_result",...i&&{toolUseId:i},...qe(String(c.message||""),true)}];let d=s.result,u=String(d?.content||"");return [{timestamp:o,type:"tool_result",...i&&{toolUseId:i},...qe(u,false)}]}if(r==="assistant.message"){let c=String(s.content||"");return c?[{timestamp:o,type:"text",content:c}]:[]}return []}};});function kf(t){let e=[],n=0,r=false,s=false,o=0;for(let c=0;c<t.length;c++){let d=t[c];if(s){s=false;continue}if(d==="\\"&&r){s=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let u=t.slice(o,c+1).trim();u&&e.push(u),o=c+1;}}}let i=t.slice(o).trim();return i&&e.push(i),e}function Tf(t){return t[0]==="exec"?t.slice(1):t}function Cd(t){let e=t.split(`
|
|
51
|
+
`).map(s=>s.trim()).filter(Boolean),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="item.completed"&&(o.item?.type==="message"||o.item?.type==="agent_message")&&typeof o.item?.text=="string"){let i=o.item.text;i.trim()&&n.push(i.trim());}o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Et(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Pd(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Et(t.error)}function Ld(t){let e=Et(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 yf(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(Et(n)&&Pd(n))return Ld(n)}}function Dd(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 s=n.state.get("codex.pending");s||(s=new Map,n.state.set("codex.pending",s));let o=JSON.stringify([t.type,t.id]);if(e==="item.started"){let d=`codex:${JSON.stringify(t.id)}#${n.rowIndex}:${r}`,u=s.get(o)??[];return u.push(d),s.set(o,u),d}let i=s.get(o),c=i?.pop();return i?.length||s.delete(o),c}function wf(t,e,n){let r=e.type;if(r==="command_execution"){let s=String(e.command||"");return ot(s)?[it(t,s,n)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:s,...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:Be(e.arguments),...n?{toolUseId:n}:{}}]:[]}function Ef(t,e,n){let r=e.type;if(r==="message"||r==="text"){let s=e.content;if(Array.isArray(s))for(let o of s){let i=Rf(t,o);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 s=typeof e.text=="string"?e.text.trim():"";return s?{timestamp:t,type:"thinking",content:s}:null}if(r==="command_execution"){let s=String(e.aggregated_output||e.output||""),o=!!e.is_error;return {timestamp:t,type:"tool_result",...qe(s,o),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let s=Et(e.result)?e.result:void 0,i=(Array.isArray(s?.content)?s.content:[]).filter(d=>Et(d)&&d.type==="text"&&typeof d.text=="string").map(d=>d.text).join(`
|
|
52
|
+
`),c=typeof e.error=="string"?e.error:Et(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 s=String(e.name||e.tool_name||""),o=e.input,i=Be(o);return s==="Bash"&&ot(i)?it(t,i):{timestamp:t,type:"tool_use",toolName:s,toolInput:i}}if(r==="tool_result"){let s=!!e.is_error,o=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...qe(o,s)}}if(r==="web_search"){let s=e.action,o;if(s?.type==="search"){let i=s.queries;o=String(s.query||"")||(i?.length?i.join(", "):"")||String(e.query||"");}else o=e.query?"open: "+String(e.query):"";return !o&&!(Et(s)&&s.type==="other"&&e.query==="")?null:{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:o}}if(r==="file_change"){let s=e.changes;if(!Array.isArray(s)||s.length===0)return null;let o=s.map(c=>String(c.path||"")).filter(Boolean);if(o.length===0)return null;let i=o.length===1?o[0]:`${o.slice(0,2).join(", ")}${o.length>2?` (+${o.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:i}}return null}function Rf(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||""),s=e.input,o=Be(s);return r==="Bash"&&ot(o)?it(t,o):{timestamp:t,type:"tool_use",toolName:r,toolInput:o}}return null}var hf,mf,eo,to=x(()=>{g();Ht();en();qn();tn();rn();zs();nn();Fn();Ft();qt();hf=new Set(["turn.started","turn.completed","item.updated"]),mf="cli/codex";eo={command:"codex",meta:{displayName:"Codex",models:id(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:s}=wt(e.model),o=e.effort??s,i=e.resumeSessionId?pd(e.mode):ld(e.mode),c=fd(o),d=r?["-m",r]:[],u=Tf(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=yf(t);if(e)throw new Z(e,mf);let n=Cd(t);if(n)return n;let r=t.trim();return st(r,"codex")?"":r},extractPartialText(t){return Cd(t)},parseResultMeta(t){let e=sn(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(),s=[],o;try{JSON.parse(t),o=[t];}catch{o=kf(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,c]of o.entries()){let d;try{d=JSON.parse(c);}catch{continue}if(!Et(d))continue;let u=d.type;if(!u)continue;let l=We(d,r);if(Pd(d)){let _=Ld(d);s.push({timestamp:l,type:"error",content:_,errorMessage:_});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||js(d))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let p=d.item;if(p){if(u==="item.started"){s.push(...wf(l,p,Dd(p,u,n,i)));continue}if(u==="item.completed"){let _=Ef(l,p,Dd(p,u,n,i));_&&s.push(_);continue}}}return s},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?hf.has(r):!1}catch{return false}}};});function Af(t){return t?If[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function qr(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Fd(t){let e=[],n=0,r=false,s=false,o=0;for(let c=0;c<t.length;c++){let d=t[c];if(s){s=false;continue}if(d==="\\"&&r){s=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let u=t.slice(o,c+1).trim();u&&e.push(u),o=c+1;}}}let i=t.slice(o).trim();return i&&e.push(i),e}function dn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Of(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let s=r.trim();if(!s)continue;try{let i=JSON.parse(s);dn(i)?e.push(i):n=!0;continue}catch{}let o=Fd(s);o.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of o)try{let c=JSON.parse(i);dn(c)?e.push(c):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Bt(t){if(typeof t!="string")return;let e=t.split(/\r?\n/).map(n=>n.trim()).find(n=>n&&!/^at\s+/.test(n));if(e)return e.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").replace(/(?:[A-Za-z]:[\\/]|\/)(?:[^\s"'`()\[\]{}]+[\\/])*[^\s"'`()\[\]{}]+/g,"[path]").slice(0,Ud).trim()}function qd(t){let e=dn(t.error)?t.error:void 0,n=e&&dn(e.data)?e.data:void 0,r=Bt(e?.name),s=Bt(n?.message)??Bt(e?.message)??Bt(t.message)??Bt(t.errorMessage)??Bt(t.error),o=Bt(t.ref),i=r&&s&&r!==s?`${r}: ${s}`:r??s??Hd;return (o?`${i} (ref: ${o})`:i).slice(0,Ud)}function Md(t){let e=Of(t),n=[],r=null,s=0,o=[],i,c=false;for(let d of e.events){let u=typeof d.type=="string"?d.type:void 0;if(u){if(u==="text"){let l=dn(d.part)?d.part:void 0,p=typeof l?.text=="string"?l.text:void 0;p?.trim()&&n.push(p.trim());continue}if(u==="result"){typeof d.result=="string"&&(r=d.result);continue}if(u==="tool_use"){s++;continue}if(u==="error"){o.push(qd(d));continue}if(u==="step_finish"){c=true;let l=dn(d.part)?d.part:void 0;i=typeof l?.reason=="string"?l.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:s,errorMessages:o,terminalReason:i,hasTerminal:c}}function Bd(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Br(){return new Z("OpenCode returned no assistant output.",an,{code:"EMPTY_OUTPUT",kind:"transient"})}function Nf(){return new Z("OpenCode emitted malformed JSON output.",an,{code:"PROVIDER_CRASHED",kind:"transient"})}function $d(t,e){switch(Bd(t)){case "length":return new Z("OpenCode stopped because the context window was exceeded.",an,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new Z("OpenCode stopped because the content filter blocked the response.",an,{code:"UNKNOWN",kind:"permanent"});case "error":return new Z(e?`OpenCode error: ${e}`:`${Hd} while generating a response.`,an,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var Sf,an,Hd,Ud,If,no,ro=x(()=>{g();Ht();qn();rn();qt();Sf=new Set(["step_start","step_finish"]),an="cli/opencode",Hd="OpenCode provider error",Ud=240,If={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};no={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,s=r!==void 0?[...r]:["run"];qr(s,"--format")||s.push("--format","json"),e.resumeSessionId&&!s.includes("-s")&&!s.includes("--session")&&s.push("-s",e.resumeSessionId);let{agent:o,autoApprove:i}=Af(e.mode);qr(s,"--agent")||o!==void 0&&s.push("--agent",o),i&&!qr(s,"--auto")&&s.push("--auto"),e.effort!==void 0&&!qr(s,"--variant")&&s.push("--variant",e.effort),e.model&&s.push("--model",e.model);let c;return !n&&!i&&!e.env?.OPENCODE_PERMISSION&&(c={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:s,stdinMessage:t,env:c}},extractText(t){let e=Md(t),n=e.errorMessages[0];if(n){let i=$d("error",n);if(i)throw i}let r=$d(e.terminalReason??"",void 0);if(r)throw r;let s=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(s!==void 0){if(!e.hasTerminal)throw Br();return s}if(e.resultText?.trim()){if(!e.hasTerminal)throw Br();return e.resultText}if(e.malformed)throw Nf();if(!e.hasTerminal)throw Br();let o=Bd(e.terminalReason);if((o==="stop"||o==="tool-calls")&&e.toolUseCount>0)return "";throw Br()},interpretExit(t,e,n=""){if(t===0)return null;let s=Md(n).errorMessages[0];return s?new Z(`OpenCode error: ${s}`,an,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=sn(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=Fd(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 c=We(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.state,h=String(_?.status||""),m=_?.input,E=Be(m);if(r.push({timestamp:c,type:"tool_use",toolName:l,toolUseId:p,toolInput:E}),h==="completed"&&_?.output!==void 0){let S=_.output,D=typeof S=="string"?S:JSON.stringify(S);r.push({timestamp:c,type:"tool_result",toolUseId:p,resultPreview:D,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=qd(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?Sf.has(r):!1}catch{return false}}};});function Bn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function bf(t,e){if(!(t?yt(so).some(o=>o.id===t):false)||!t)return e;let r=Un(so,t),s=sd(so)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:s&&r.includes(s)?s:void 0:s}var so,oo,io=x(()=>{g();Ht();Hn();Ft();Fn();so="antigravity";oo={command:"agy",meta:{displayName:"Antigravity",models:dd(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:s}=wt(e.model),o=Vs(r),i=o.model,c=e.effort??s??o.effort,d=bf(i,c),u=e.additionalArgs??[],l=i&&!Bn(u,"--model")?["--model",i]:[],p=Bn(u,"--effort")?[]:wd(d),_=Bn(u,"--mode")||Bn(u,"--dangerously-skip-permissions")?[]:yd(e.mode),h=Bn(u,"--print")?[]:["--print",t];return {args:[...l,...p,..._,...u,...h]}},extractText(t){let e=t.trim();if(!e)throw new Z("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"});return e},parseResultMeta(t){return {usage:null,model:null}},parseEvent(t,e){return []}};});var Wd=x(()=>{g();tn();rn();nn();qt();});function cn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function un(t){return cn(t)?t:void 0}function Se(t){return typeof t=="string"?t:void 0}function Gt(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Pf(t){let e=[],n=-1,r=0,s=false,o=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(o){o=false;continue}if(c==="\\"&&s){o=true;continue}if(c==='"'){s=!s;continue}s||(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 Wn(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return cn(n)?[n]:[]}catch{return Pf(e).flatMap(n=>{try{let r=JSON.parse(n);return cn(r)?[r]:[]}catch{return []}})}}function Jd(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function Wt(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(Wt).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
53
|
+
`):void 0}if(cn(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=Wt(t[e]);if(n!==void 0)return n}}}function Lf(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)),s=i=>{let c=JSON.stringify(i,(d,u)=>e(u)?`<bytes:${u.length}>`:u);return c===void 0?String(i):c},o=t.rawOutput;if(o!=null){let i=un(o);if(!i)return n(Wt(o))??s(o);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=un(i.Result);c=n(i.output)??n(l?.output)??n(Wt(o));}let d=e(i.stderr)&&i.stderr.length>0?r(i.stderr):void 0;if(d!==void 0)if(c){let l=c.endsWith(`
|
|
54
|
+
`)||c.endsWith("\r")?"":`
|
|
55
|
+
`;c=`${c}${l}${d}`;}else c=n(d);if(c)return c;let u=n(i.summary)??n(Wt(t.content))??n(i.output_for_prompt);return u!==void 0?u:s(o)}if(t.content!==null&&t.content!==void 0)return Wt(t.content)??s(t.content);if(t.result!==null&&t.result!==void 0)return Wt(t.result)??s(t.result)}function Vd(t){let e=un(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?Xd(n):"Grok CLI reported an error."}function Xd(t){return (t.replace(Df,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Kd(t){return Cf.test(t)}function Mf(t){let e=un(t.modelUsage);return e?Object.keys(e)[0]??null:null}function $f(t){let e=un(t.usage);if(!e)return null;let n=Gt(e.cache_read_input_tokens);return {inputTokens:Gt(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Gt(e.output_tokens),costUsd:Gt(t.total_cost_usd)}}function Hf(t){let e=0,n=0,r=0,s=false,o=new Set;for(let i of t.split(`
|
|
56
|
+
`).flatMap(Wn)){if(i.type!=="usage")continue;let c=un(i.usage);if(!c)continue;let d=Se(i.signature);if(d&&d.length>0){let l=`signature:${d}`;if(o.has(l))continue;o.add(l);}let u=Gt(c.cache_read_input_tokens);e+=Gt(c.input_tokens)+u,n+=u,r+=Gt(c.output_tokens),s=true;}return s?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function Uf(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let o of e.entries.slice(0,Gd)){if(!cn(o))continue;let i=Se(o.content)?.trim();if(!i)continue;let c=Se(o.status)?.trim(),d=Se(o.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>Gd&&n.push(zd);let r=n.join(`
|
|
57
|
+
`),s=r.length>jd?`${r.slice(0,jd-1)}${zd}`:r;return [{timestamp:t,type:"info",content:s}]}function Ff(t,e){let n=Se(e.type);if(n==="thought"){let r=Se(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=Se(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return Uf(t,e);if(n==="tool_call"){let r=Se(e.toolCallId),s=Se(e.toolName)??Se(e.title),o=e.rawInput===void 0?void 0:Jd(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:s,toolInput:o}]}if(n==="tool_call_update"){let r=Se(e.status);if(r!=="completed"&&r!=="failed"&&r!=="error")return [];let s=Lf(e),o=r!=="completed"||e.isError===true;return [{timestamp:t,type:"tool_result",toolUseId:Se(e.toolCallId),toolName:Se(e.toolName)??Se(e.title),...s!==void 0?qe(s,o):{isError:o}}]}if(n==="error"){let r=Vd(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}function qf(t){return process.platform==="win32"?{flags:["--single",t]}:{flags:["--prompt-file","/dev/stdin"],stdinMessage:t}}var Wr,vf,Cf,Df,Gd,jd,zd,ao,co=x(()=>{g();Ht();Ws();Ft();nn();Fn();qt();Wr="cli/grok",vf=new Set(["available_commands","usage","end"]),Cf=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,Df=/\u001b\[[0-?]*[ -/]*[@-~]/g,Gd=20,jd=4e3,zd="\u2026";ao={command:"grok",createSessionId:()=>randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=wt(e.model),s=e.effort??r,o=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],c=n?yt("grok").some(N=>N.id===n):false,d=n&&c?Un("grok",n):[],u=!s||d.length===0||d.includes(s)?s:void 0,l=Td(u),p=e.additionalArgs??[],_=N=>p.some(R=>R===N||R.startsWith(`${N}=`)),h=e.providerOptions,m=h?.alwaysApprove,E=h?.sandbox,S=_("--permission-mode")?[]:hd(e.mode),D=_("--always-approve")?[]:md(m),y=_("--sandbox")?[]:kd(E),v=_("--verbatim")?[]:["--verbatim"],I=qf(t);return {args:["--no-auto-update",...o,...I.flags,...v,"--output-format","streaming-json","--no-alt-screen",...i,...l,...S,...D,...y,...p],stdinMessage:I.stdinMessage}},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
58
|
+
`).flatMap(Wn))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 Wn(t))if(e.type==="error"){let n=Vd(e);return Kd(Jd(e))?new Ut(n,Wr):new Z(n,Wr)}return null},interpretExit(t,e){if(t===0)return null;let n=Xd(e)||`Grok CLI exited with code ${t}.`;return Kd(e)?new Ut(n,Wr):new Z(n,Wr)},parseResultMeta(t){let n=t.split(`
|
|
59
|
+
`).flatMap(Wn).find(r=>r.type==="end");return n?{usage:$f(n),model:Mf(n)}:{usage:Hf(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return Wn(t).flatMap(r=>Ff(We(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return cn(n)&&typeof n.type=="string"?vf.has(n.type):!1}catch{return false}}};});var Yd,Qd=x(()=>{g();Ys();Zs();to();ro();io();Wd();co();Ys();Zs();to();ro();io();co();tn();Yd={codex:eo,claude:Fr,opencode:no,antigravity:oo,copilot:Qs,grok:ao};});function Zd(t){if(t.startsWith("cli/"))return Yd[t.slice(4)]}var ec=x(()=>{g();za();Qd();});function Gr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Bf(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function jr(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(`
|
|
60
|
+
`)??"";if(!n.trim())return;let r=Zd(t.provider);if(!r)return;let s;try{s=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let o=Bf(s?.model,t.model),i=s?.usage;if(!i)return {stdout:n,adapter:r};let c=Gr(i.inputTokens),d=Gr(i.outputTokens),u=Gr(i.cachedInputTokens),l=Ra(Gr(i.costUsd),c,d,u,o);return c!==0||d!==0||u!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:c,outputTokens:d,cachedInputTokens:u,costUsd:l,model:o}}:{stdout:n,adapter:r}}var uo=x(()=>{g();ec();Nr();});function po(t){let e=new Set;for(let n of t)for(let r of Wf.get(n)??[n])e.add(r);return [...e]}function fo(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"&&Gf.has(n)?n:void 0}catch{return}}function Ge(t){let e=fo(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(lo.stopped.test(t.error))return "user_stop";if(lo.runnerLost.test(t.error))return "runner_lost"}}function xe(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=fo(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&lo.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function jf(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function Gn(t){let e=xe(t);return t.status==="runner_lost"&&fo(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...jf(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}var jt,Wf,lo,Gf,jn=x(()=>{g();jt=["success","completed","done","failed","error","stopped","runner_lost"],Wf=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);lo={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},Gf=new Set(["user_stop","runner_lost","launch_failed"]);});function _o(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 Kn(){return _o("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function pn(){return _o("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function Kr(){return _o("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function ln(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function zr(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 zf(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 tc(t,e){return !!t.stop_requested_at&&ln(t.stop_requested_epoch)===ln(e)}function nc(t,e){let n=ln(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let s=zf(t.getTask(e.taskId));return !s||s.status!=="running"||ln(s.run_epoch)!==n?{accepted:false,row:s}:{accepted:true,row:s}}function ic(t,e){let n=zn.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),zn.delete(t),true)}function Jn(t,e){let n=zn.get(t);return !n||e!==void 0&&n.runEpoch!==ln(e)?false:ic(t,n)}function ac(t,e){let n=ln(e.runEpoch);Jn(e.taskId);let r=true,s=null;try{let u=nc(t,{...e,runEpoch:n});r=u.accepted,s=u.row;}catch(u){zr(u);}if(!r)return false;let o=Kn(),i=Math.min(o,1e3),c=setInterval(()=>{let u=zn.get(e.taskId);if(!(!u||u.timer!==c))try{u.heartbeatElapsedMs+=i;let l=u.heartbeatElapsedMs>=o,p=nc(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){ic(e.taskId,u);return}l&&(u.heartbeatElapsedMs%=o,u.lastHeartbeatAt=Date.now()),p.row&&tc(p.row,n)&&!u.stopRequested&&(u.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(zr));}catch(l){zr(l);}},i),d={timer:c,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return zn.set(e.taskId,d),typeof c=="object"&&c!==null&&"unref"in c&&c.unref(),s&&tc(s,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(s)).catch(zr)),true}var rc,sc,oc,zn,Vn=x(()=>{g();rc=1e4,sc=3e4,oc=18e5;zn=new Map;});function Jr(t,e=Date.now(),n=ko){let r=t?Date.parse(t):Number.NaN,s=typeof e=="number"?e:Date.parse(e),o=wo(n,ko,0);return Number.isFinite(r)&&Number.isFinite(s)&&s-r>o?"forced":"cooperative"}function So(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=pc(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 Io(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??Ca,c=e.processControl?.readProcessIdentityAsync??Ma,d;try{d=await i(t.pid,e.ownershipMarkers??Jf,o);}catch{d="unknown";}let u;try{u=await c(t.pid,o);}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)>xr)return {verdict:"reused",reason:`started ${l}, not the recorded ${t.startedAt}`}}else return s!==void 0&&u.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"}:u.groupId!==null&&u.groupId!==t.pid?{verdict:"unproven",ownership:"not_owned",reason:"pid does not lead its process group"}:{verdict:"owned"}}async function Ao(t,e={}){let n=await Io(t,e);return n.verdict==="owned"?"owned":n.verdict==="reused"?"not_owned":n.ownership}function wo(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function pc(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function t_(t){if(!t)return;let e=pc(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function ve(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=t_(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function Oo(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 V(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 mo(t,e){return V(t,Xf,e)}function n_(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=pn():false}function r_(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function s_(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return ve(r,n)}async function o_(t,e,n,r){let s=Date.now()+n;for(;;){let o=s_(t,e);if(o)return o;let i=s-Date.now();if(i<=0)return;await new Promise(c=>{setTimeout(c,Math.min(r,i));});}}async function lc(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 v=t.stopPendingTask(e,void 0,void 0,{...s,at:r}),I=t.getTask(e);if(v||!I||I.status!=="running")return ve(I);if(o=t.requestTaskStop({id:e,requestedAt:r,...s}),!o.accepted&&o.status!=="running"||!o.accepted&&!o.alreadyRequestedAt)return ve(t.getTask(e))}else if(!(o.status==="running"&&o.alreadyRequestedAt))return ve(i)}let c=o.runEpoch,d=wo(n.graceMs,ko,0),u=wo(n.pollMs,Kf,1),l=await o_(t,e,d,u);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return ve(p);let _=So(p),h=_.map(v=>v.pid),m=h[0];if(!m){let v=t.finalizeTaskStop({id:e,runEpoch:c,method:"forced"}),I=t.getTask(e);return v||I?.status!=="running"?ve(I):V(I,"Failed to finalize task stop")}let E=r_(n);if(!n_(p,Date.now())){for(let v of _)if(await Ao(v,{ownershipMarkers:n.ownershipMarkers,processControl:n.processControl,processControlOptions:E})!=="owned")return Oo(p)}let S=n.processControl?.terminateProcessTree??Tt;for(let v of h){let I;try{I=await S(v,{...E,signal:kt});}catch(N){I={status:"failed",pid:v,method:E.platform==="win32"?"taskkill":"process-group",error:N instanceof Error?N.message:String(N)};}if(I.status==="failed")return V(t.getTask(e),I.error??"Failed to terminate process tree")}let D=t.finalizeTaskStop({id:e,runEpoch:c,method:"forced"}),y=t.getTask(e);return D||y?.status!=="running"?ve(y,m):V(y,"Task changed before stop was finalized")}function Eo(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Ro(t){return Number.isSafeInteger(t)&&t>=0}function Xn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function i_(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function a_(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function d_(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 c_(t){switch(t){case "epoch_mismatch":return To;case "workspace_mismatch":return yo;default:return}}async function fc(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return mo(n,Eo(e.targetPid)?e.targetPid:void 0);if(!Ro(e.sourceRunEpoch)||!Ro(e.settleRunEpoch)||Xn(n.run_epoch)!==e.settleRunEpoch)return V(n,go,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return V(n,ho,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 V(n,Yf,e.targetPid)}let o=t.getTask(e.taskId);if(!o||o.status!=="running")return mo(o,e.targetPid);if(s.runEpoch!==e.settleRunEpoch||Xn(o.run_epoch)!==e.settleRunEpoch)return V(o,go,e.targetPid);if(e.workspaceId!==void 0&&o.workspace_id!==e.workspaceId)return V(o,ho,e.targetPid);if(!Eo(e.targetPid))return V(o,Vf);let i=i_(e);if(await Ao({pid:e.targetPid,startedAt:o.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:i})!=="owned")return Oo(o,e.targetPid);let d=t.getTask(e.taskId);if(!d||d.status!=="running")return mo(d,e.targetPid);if(Xn(d.run_epoch)!==e.settleRunEpoch)return V(d,go,e.targetPid);if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId)return V(d,ho,e.targetPid);let u=e.processControl?.terminateProcessTree??Tt,l;try{l=await u(e.targetPid,{...i,signal:kt});}catch{return V(t.getTask(e.taskId),dc,e.targetPid)}if(l.status==="failed")return V(t.getTask(e.taskId),dc,e.targetPid);let p;try{p=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return V(t.getTask(e.taskId),cc,e.targetPid)}return p?ve(t.getTask(e.taskId),e.targetPid):V(t.getTask(e.taskId),cc,e.targetPid)}async function _c(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return ve(n);if(!Ro(e.expectedRunEpoch)||Xn(n.run_epoch)!==e.expectedRunEpoch)return V(n,To);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return V(n,yo);let r=n.pid;if(!Eo(r))return V(n,Qf);let s=a_(e);if(await Ao({pid:r,startedAt:n.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:s})!=="owned")return Oo(n,r,Zf);let i=e.processControl?.terminateProcessTree??Tt,c;try{c=await i(r,{...s,signal:kt});}catch{return V(t.getTask(e.taskId),uc,r)}if(c.status==="failed")return V(t.getTask(e.taskId),uc,r);let d=t.getTask(e.taskId);if(!d||d.status!=="running")return ve(d,r);if(Xn(d.run_epoch)!==e.expectedRunEpoch)return V(d,To,r);if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId)return V(d,yo,r);let u;try{u=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return V(t.getTask(e.taskId),e_,r)}let l=c_(u);return l?V(t.getTask(e.taskId),l,r):u!=="settled"?ve(t.getTask(e.taskId),r):d_(t.getTask(e.taskId),r)}function gc(t,e,n={}){if(typeof t=="string"){let r=t,s=e??{};return Promise.resolve().then(()=>(bo(),hc)).then(({TaskRepository:o})=>lc(new o,r,s))}return lc(t,e,n)}var ko,Kf,Jf,Vf,go,ho,Xf,dc,cc,Yf,To,yo,Qf,Zf,uc,e_,No=x(()=>{g();vr();Vn();ko=5e3,Kf=250;Jf=["crewx","claude","codex","opencode","grok","node"];Vf="INSTRUCTION_STOP_TARGET_PID_MISSING",go="INSTRUCTION_STOP_EPOCH_MISMATCH",ho="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Xf="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",dc="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",cc="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Yf="INSTRUCTION_STOP_REQUEST_FAILED",To="HOST_SHUTDOWN_EPOCH_MISMATCH",yo="HOST_SHUTDOWN_WORKSPACE_MISMATCH",Qf="HOST_SHUTDOWN_TARGET_PID_MISSING",Zf="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",uc="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",e_="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var hc={};ou(hc,{CANONICAL_USER_STOP_ERROR:()=>Uo,DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>Sc,HOST_SHUTDOWN_TERMINAL_ERROR:()=>wc,PENDING_ADOPT_GRACE_MS:()=>Rc,PID_NULL_REAP_GRACE_MS:()=>Bo,RATED_TASK_EXCERPT_MAX_CHARS:()=>Wo,RATED_TASK_LIST_MAX_LIMIT:()=>Ac,TASK_HEARTBEAT_HARD_STALE_MS:()=>oc,TASK_HEARTBEAT_INTERVAL_MS:()=>rc,TASK_HEARTBEAT_STALE_MS:()=>sc,TASK_RATINGS:()=>Ic,TaskRatingError:()=>tr,TaskRepository:()=>er,WORKFLOW_ANCHOR_TASK_KINDS:()=>ht,buildRatedTasksCountQuery:()=>Nc,buildRatedTasksQuery:()=>Oc,countRatedTasks:()=>O_,hasRecordedUsage:()=>qo,isWorkflowAnchorTaskKind:()=>Ln,listRatedTasks:()=>A_,mergeTerminalReason:()=>Fo,resolveTaskHeartbeatHardStaleMs:()=>Kr,resolveTaskHeartbeatIntervalMs:()=>Kn,resolveTaskHeartbeatStaleMs:()=>pn,setTaskRating:()=>I_});function ze(t){return Gn(t)}function vo(t){return Gn(t)}function Co(){return or(...ht.map(t=>like(a.metadata,`%"kind":"${t}"%`)))}function mc(){return and(...ht.map(t=>notLike(a.metadata,`%"kind":"${t}"%`)))}function Po(t=a.model,e=a.metadata){let n=sql`
|
|
61
61
|
CASE
|
|
62
62
|
WHEN ${t} LIKE 'claude-%' OR ${t} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
63
63
|
WHEN ${t} LIKE 'gpt-%' OR ${t} LIKE 'codex-%' THEN 'codex'
|
|
@@ -86,7 +86,7 @@ ${r.join(`
|
|
|
86
86
|
WHEN trim(${i}) = '' THEN 'unknown'
|
|
87
87
|
ELSE ${i}
|
|
88
88
|
END
|
|
89
|
-
`}function
|
|
89
|
+
`}function m_(t){let e={status:t.status,metadata:t.metadata},n=xe(e);return n==="stopped"||n==="failed"&&Ge(e)==="runner_lost"}function Zn(t){return sql`${t} NOT IN (${sql.join(k_.map(e=>sql`${e}`),sql`, `)})`}function Vr(t){let e=sql`
|
|
90
90
|
CASE
|
|
91
91
|
WHEN json_valid(${t}) = 1
|
|
92
92
|
THEN json_extract(${t}, '$.usageAccounting')
|
|
@@ -96,7 +96,7 @@ ${r.join(`
|
|
|
96
96
|
COALESCE(SUM(
|
|
97
97
|
CASE WHEN ${e} = 'unavailable' THEN 1 ELSE 0 END
|
|
98
98
|
), 0)
|
|
99
|
-
`}function
|
|
99
|
+
`}function hn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function se(t){if(!t)return {};try{let e=JSON.parse(t);return hn(e)?{...e}:{}}catch{return {}}}function es(t){return t==null||t===""}function Xr(t,e){return es(t)&&!es(e)?e:t}function T_(t,e){let n=se(t);if(!e)return n;for(let[r,s]of Object.entries(e))es(n[r])&&!es(s)&&(n[r]=s);return n}function Yr(t,e){let n=t.origin&&Ec.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 y_(t){let e=se(t).stopRequest;if(hn(e)&&!(typeof e.origin!="string"||!Ec.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function kc(){return or(isNull(a.stop_requested_at),ne$1(sql`COALESCE(${a.stop_requested_epoch}, 0)`,sql`COALESCE(${a.run_epoch}, 0)`))}function Fo(t,e){let n=se(t??null);return n.terminalReason=e,JSON.stringify(n)}function Mo(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==Uo&&(n[h_]=e),{error:Uo,metadata:n}}function le(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function qo(t){return le(t.input_tokens)!==0||le(t.output_tokens)!==0||le(t.cached_input_tokens)!==0||le(t.cost_usd)!==0}function G(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Tc(t){return {inputTokens:le(t.inputTokens??0),outputTokens:le(t.outputTokens??0),cachedInputTokens:le(t.cachedInputTokens??0),costUsd:le(t.costUsd??0)}}function w_(t){if(hn(t))return {inputTokens:le(t.inputTokens),outputTokens:le(t.outputTokens),cachedInputTokens:le(t.cachedInputTokens),costUsd:le(t.costUsd)}}function E_(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=w_(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function Qr(t,e,n){let r=Date.parse(t),s=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(s)?s-r:n??null}function $o(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return null;let n=La(t,e);return n.status==="found"?new Date(n.startedAtMs).toISOString():null}function mn(t,e){if(typeof t!="string"||t.length===0)throw new f("VALIDATION",`${e} is required`);return t}function Go(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 I_(t,e){let n=mn(e.workspaceId,"workspaceId"),r=mn(e.taskId,"taskId"),s=e.rating;if(s!==null&&!Ic.includes(s))throw new f("VALIDATION","rating must be 'up', 'down' or null");let o=e.now===void 0?new Date().toISOString():Go(e.now,"now");try{return t.transaction(i=>{let c=and(eq(a.id,r),eq(a.workspace_id,n),inArray(a.status,[...jt])),d=i.update(a).set({rating:s,rated_at:s===null?null:o}).where(and(c,sql`${a.rating} IS NOT ${s}`)).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 tr("TASK_NOT_FOUND",r);if(!S_.has(u.status))throw new tr("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 Oc(t){let e=sql`
|
|
100
100
|
SELECT id, rated_at FROM tasks
|
|
101
101
|
WHERE workspace_id = ${t.workspaceId}
|
|
102
102
|
AND rating IS NOT NULL
|
|
@@ -106,41 +106,41 @@ ${r.join(`
|
|
|
106
106
|
LIMIT ${t.limit}
|
|
107
107
|
`;return sql`
|
|
108
108
|
SELECT t.id AS taskId, t.agent_id AS agentId, t.thread_id AS threadId, t.status AS status,
|
|
109
|
-
substr(t.error, 1, ${
|
|
109
|
+
substr(t.error, 1, ${R_}) AS errorHead,
|
|
110
110
|
CASE WHEN json_valid(t.metadata) THEN json_extract(t.metadata, '$.terminalReason') END AS terminalReason,
|
|
111
111
|
t.rating AS rating, t.rated_at AS ratedAt,
|
|
112
|
-
NULLIF(substr(t.prompt, 1, ${
|
|
113
|
-
NULLIF(substr(t.result, 1, ${
|
|
112
|
+
NULLIF(substr(t.prompt, 1, ${Wo}), '') AS promptExcerpt,
|
|
113
|
+
NULLIF(substr(t.result, 1, ${Wo}), '') AS resultExcerpt
|
|
114
114
|
FROM (${e}) AS page
|
|
115
115
|
JOIN tasks t ON t.id = page.id
|
|
116
116
|
ORDER BY page.rated_at DESC, page.id DESC
|
|
117
|
-
`}function
|
|
117
|
+
`}function A_(t,e){let n=mn(e.workspaceId,"workspaceId");if(e.agentId!==void 0&&mn(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),Ac),s=e.sinceIso===void 0?void 0:Go(e.sinceIso,"sinceIso");try{return t.all(Oc({workspaceId:n,agentId:e.agentId,sinceIso:s,limit:r})).map(i=>({taskId:i.taskId,agentId:i.agentId,threadId:i.threadId,status:xe({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(o){throw o instanceof f?o:new f("DB_ERROR","Failed to list rated tasks",o)}}function Nc(t){return sql`
|
|
118
118
|
SELECT COUNT(*) AS total FROM tasks
|
|
119
119
|
WHERE workspace_id = ${t.workspaceId}
|
|
120
120
|
AND rating IS NOT NULL
|
|
121
121
|
${t.agentId!==void 0?sql`AND agent_id = ${t.agentId}`:sql``}
|
|
122
122
|
${t.sinceIso!==void 0?sql`AND rated_at >= ${t.sinceIso}`:sql``}
|
|
123
|
-
`}function pg(t,e){let n=cn(e.workspaceId,"workspaceId");e.agentId!==void 0&&cn(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:$o(e.sinceIso,"sinceIso");try{return t.all(ku({workspaceId:n,agentId:e.agentId,sinceIso:r}))[0]?.total??0}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to count rated tasks",s)}}var Ao,on,Zf,an,dn,eg,bo,jn,We,Co,lu,tg,rg,pu,Lo,fu,gu,Kn,_u,Mo,hu,dg,Jn,ug,Eo=v(()=>{_();ut();Rt();St();dt();vt();Tr();yr();ka();Sr();Pa();La();no();Hn();Bn();yo();Bn();Tr();Ao=40,on="2026-05-09",Zf="0.8.9-rc.13",an=10,dn=parseInt(Zf.split("rc.")[1]);eg=new Set(["workflow","mcp"]),bo="usageByEpoch",jn="lateUsage",We="usageAccounting",Co="Stopped by user",lu="Stopped by app shutdown",tg="terminalErrorOriginal";rg=["pending","running"];pu=new Set(["http","cli","instruction","workflow","internal"]);Lo=600*1e3,fu=600*1e3,gu=300*1e3;Kn=class extends Te{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 Ir({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?Et(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 f("NOT_FOUND","Database not found");let r=$(n);if(e)try{xe(r.db,n);}catch(s){throw r.close(),s}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=G(e.runEpoch),s=r===0?or(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 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(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=G(o.run_epoch);if(o.status!=="running"){r={accepted:!1,status:o.status,runEpoch:i};return}let u=o.stop_requested_at!==null&&G(o.stop_requested_epoch)===i,d=u?o.stop_requested_at:e.requestedAt,c=re(o.metadata),l=u?og(o.metadata)??Gr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):Gr({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"),du())).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:G(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:G(m.run_epoch),...m.stop_requested_at&&G(m.stop_requested_epoch)===G(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:o.status,runEpoch:i};let g=new Set([e.id]),h=(m,E)=>{if(E>=8)return;let S=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 P of S)g.has(P.id)||(g.add(P.id),s.update(a).set({stop_requested_at:d,stop_requested_epoch:sql`${a.run_epoch}`,metadata:JSON.stringify({...re(P.metadata),stopRequest:l})}).where(and(eq(a.id,P.id),eq(a.status,"running"),du())).run(),h(P.id,E+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(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=G(o.run_epoch),u=G(e.sourceRunEpoch),d=G(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(eq(a.run_epoch,0),isNull(a.run_epoch)):eq(a.run_epoch,d),l=or(isNull(a.stop_requested_at),isNull(a.stop_requested_epoch),ne$1(a.stop_requested_epoch,u)),p=Gr({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),g=S=>s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:u,metadata:JSON.stringify({...re(o.metadata),stopRequest:p})}).where(and(eq(a.id,e.id),eq(a.status,"running"),c,S,l)).run();if((e.workspaceId===void 0?g():e.workspaceId===null?g(isNull(a.workspace_id)):g(eq(a.workspace_id,e.workspaceId))).changes>0){r={accepted:!0,status:o.status,runEpoch:d};return}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:G(m?.run_epoch)};return}let E=G(m.run_epoch);r={accepted:!1,status:m.status,runEpoch:E,...m.stop_requested_at&&G(m.stop_requested_epoch)===u?{alreadyRequestedAt:m.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(),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"||G(i.run_epoch)!==G(e.runEpoch))return;let u=i.stop_requested_at!==null&&G(i.stop_requested_epoch)===G(e.runEpoch),d=re(i.metadata),c=u?No(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??jr(i.started_at,r,void 0),g=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"),g)).run().changes>0;},{behavior:"immediate"}),s}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(),s=G(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(G(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={...re(u.metadata),terminalReason:"runner_lost"},g=u.duration_ms??jr(u.started_at,r,void 0);o=i.update(a).set({status:"failed",error:lu,completed_at:r,duration_ms:g,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 f?r:new f("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return ou(this,e,n)}async stopTaskGenerationForInstruction(e){return ru({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:xo(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:la(e.metadata),schedule_id:ma(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(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(Ku=>Ku.name)),l=c.has("cwd"),p=c.has("user_id"),g=c.has("actor_kind"),h=c.has("actor_id"),m=c.has("log_storage"),E=l?", cwd":"",S=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":"",x=m?", ?":"",I=p?", user_id":"",b=p?", ?":"",R=g?", actor_kind":"",B=g?", ?":"",ke=h?", actor_id":"",Tn=h?", ?":"",or=m?`,
|
|
123
|
+
`}function O_(t,e){let n=mn(e.workspaceId,"workspaceId");e.agentId!==void 0&&mn(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:Go(e.sinceIso,"sinceIso");try{return t.all(Nc({workspaceId:n,agentId:e.agentId,sinceIso:r}))[0]?.total??0}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to count rated tasks",s)}}var Do,fn,__,_n,gn,g_,Lo,Qn,Ke,Uo,wc,h_,k_,Ec,Bo,Rc,Sc,er,Ic,Wo,Ac,R_,tr,S_,bo=x(()=>{g();ft();Ot();Nt();pt();$t();Ar();Nr();Na();vr();Wa();ja();uo();jn();Vn();No();Vn();Ar();Do=40,fn="2026-05-09",__="0.8.9-rc.13",_n=10,gn=parseInt(__.split("rc.")[1]);g_=new Set(["workflow","mcp"]),Lo="usageByEpoch",Qn="lateUsage",Ke="usageAccounting",Uo="Stopped by user",wc="Stopped by app shutdown",h_="terminalErrorOriginal";k_=["pending","running"];Ec=new Set(["http","cli","instruction","workflow","internal"]);Bo=600*1e3,Rc=600*1e3,Sc=300*1e3;er=class extends Ee{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 Cr({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?At(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 f("NOT_FOUND","Database not found");let r=$(n);if(e)try{De(r.db,n);}catch(s){throw r.close(),s}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=G(e.runEpoch),s=r===0?or(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 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(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=G(o.run_epoch);if(o.status!=="running"){r={accepted:!1,status:o.status,runEpoch:i};return}let c=o.stop_requested_at!==null&&G(o.stop_requested_epoch)===i,d=c?o.stop_requested_at:e.requestedAt,u=se(o.metadata),l=c?y_(o.metadata)??Yr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):Yr({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({...u,stopRequest:l})}).where(and(eq(a.id,e.id),eq(a.status,"running"),kc())).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:G(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:G(m.run_epoch),...m.stop_requested_at&&G(m.stop_requested_epoch)===G(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:o.status,runEpoch:i};let _=new Set([e.id]),h=(m,E)=>{if(E>=8)return;let S=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 D of S)_.has(D.id)||(_.add(D.id),s.update(a).set({stop_requested_at:d,stop_requested_epoch:sql`${a.run_epoch}`,metadata:JSON.stringify({...se(D.metadata),stopRequest:l})}).where(and(eq(a.id,D.id),eq(a.status,"running"),kc())).run(),h(D.id,E+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(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=G(o.run_epoch),c=G(e.sourceRunEpoch),d=G(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 u=d===0?or(eq(a.run_epoch,0),isNull(a.run_epoch)):eq(a.run_epoch,d),l=or(isNull(a.stop_requested_at),isNull(a.stop_requested_epoch),ne$1(a.stop_requested_epoch,c)),p=Yr({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),_=S=>s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:c,metadata:JSON.stringify({...se(o.metadata),stopRequest:p})}).where(and(eq(a.id,e.id),eq(a.status,"running"),u,S,l)).run();if((e.workspaceId===void 0?_():e.workspaceId===null?_(isNull(a.workspace_id)):_(eq(a.workspace_id,e.workspaceId))).changes>0){r={accepted:!0,status:o.status,runEpoch:d};return}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:G(m?.run_epoch)};return}let E=G(m.run_epoch);r={accepted:!1,status:m.status,runEpoch:E,...m.stop_requested_at&&G(m.stop_requested_epoch)===c?{alreadyRequestedAt:m.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(),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"||G(i.run_epoch)!==G(e.runEpoch))return;let c=i.stop_requested_at!==null&&G(i.stop_requested_epoch)===G(e.runEpoch),d=se(i.metadata),u=c?Mo(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??Qr(i.started_at,r,void 0),_=i.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,i.run_epoch);s=o.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"}),s}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(),s=G(e.expectedRunEpoch),o="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"){o="not_running";return}if(G(c.run_epoch)!==s){o="epoch_mismatch";return}if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId){o="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={...se(c.metadata),terminalReason:"runner_lost"},_=c.duration_ms??Qr(c.started_at,r,void 0);o=i.update(a).set({status:"failed",error:wc,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"}),o}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 gc(this,e,n)}async stopTaskGenerationForInstruction(e){return fc({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:$o(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:wa(e.metadata),schedule_id:Oa(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(eq(a.status,"running"),and(eq(a.status,"pending"),isNull(a.pid)))}).run();};try{i(o);}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(ru=>ru.name)),l=u.has("cwd"),p=u.has("user_id"),_=u.has("actor_kind"),h=u.has("actor_id"),m=u.has("log_storage"),E=l?", cwd":"",S=l?", ?":"",D=l?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",y=m?", log_storage":"",v=m?", ?":"",I=p?", user_id":"",N=p?", ?":"",R=_?", actor_kind":"",B=_?", ?":"",we=h?", actor_id":"",An=h?", ?":"",pr=m?`,
|
|
124
124
|
log_storage = CASE WHEN tasks.status = 'pending' THEN excluded.log_storage ELSE tasks.log_storage END`:"";n.runRaw(`INSERT INTO tasks (
|
|
125
125
|
id, agent_id, prompt, mode, status, started_at, pid,
|
|
126
126
|
parent_task_id, caller_agent_id, trace_id, command, metadata,
|
|
127
127
|
workspace_id${E}, project_id, platform, crewx_version, thread_id,
|
|
128
|
-
model, rendered_prompt, coding_agent_command${I}${R}${
|
|
129
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${S}${
|
|
128
|
+
model, rendered_prompt, coding_agent_command${I}${R}${we}${y}
|
|
129
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${S}${N}${B}${An}${v})
|
|
130
130
|
ON CONFLICT(id) DO UPDATE SET
|
|
131
131
|
status = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN 'running' ELSE tasks.status END,
|
|
132
132
|
pid = COALESCE(excluded.pid, tasks.pid),
|
|
133
133
|
command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.command ELSE tasks.command END,
|
|
134
134
|
metadata = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.metadata ELSE tasks.metadata END,
|
|
135
|
-
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${
|
|
135
|
+
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${D},
|
|
136
136
|
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,
|
|
137
137
|
crewx_version = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.crewx_version ELSE tasks.crewx_version END,
|
|
138
138
|
model = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.model ELSE tasks.model END,
|
|
139
139
|
rendered_prompt = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.rendered_prompt ELSE tasks.rendered_prompt END,
|
|
140
|
-
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${
|
|
141
|
-
WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[o.id,o.agent_id,o.prompt,o.mode,o.status,o.started_at,o.pid,o.parent_task_id,o.caller_agent_id,o.trace_id,o.command,o.metadata,o.workspace_id,...l?[o.cwd]:[],o.project_id,o.platform,o.crewx_version,o.thread_id,o.model,o.rendered_prompt,o.coding_agent_command,...p?[o.user_id]:[],...
|
|
142
|
-
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 s=this.openHandle(true);try{return s.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(o){throw o instanceof f?o:new f("DB_ERROR","Failed to fail pending task",o)}finally{s.close();}}stopPendingTask(e,n,r=new Date().toISOString(),s={}){let o=this.openHandle(true);try{let i=!1;return o.db.transaction(
|
|
143
|
-
`);}}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=re(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 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(ne).from(a).where(eq(a.status,"running")).orderBy(desc(a.started_at)).all().map(Be)}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(ne).from(a).where(inArray(a.status,["pending","running"])).orderBy(desc(a.started_at)).all().map(Be)}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(ne).from(a).orderBy(desc(a.started_at)).limit(100).all().map(Be)}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=G(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||G(u.run_epoch)!==n)return;o=i.insert(st).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 f?o:new f("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=G(s.run_epoch),i=r.db.select({run_epoch:st.run_epoch,key_wrap_skipped:st.key_wrap_skipped}).from(st).where(eq(st.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 f?s:new f("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(st).where(and(eq(st.task_id,e),eq(st.run_epoch,G(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 f("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(ne).from(a).where(eq(a.id,e)).limit(1).get();return r?Be(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(eq(a.status,"running"),eq(a.status,"pending"))).all(),s=this.clock(),o=Math.max(1,Math.trunc(e.tickIntervalMs??gu)),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=sn(),l=Fr(),p=new Date(s-fu).toISOString(),g=new Date(s).toISOString(),h=new Set,m=[],E=0,S=(w,x)=>{let I=re(Po(w.metadata,"runner_lost")),b=typeof I.provider=="string"?I.provider:void 0,R;try{R=Hr({taskLogRepository:this.taskLogRepository,taskId:w.id,provider:b,model:w.model})?.usage;}catch{}let B={status:"failed",error:x,completed_at:g};R?(B.input_tokens=R.inputTokens,B.output_tokens=R.outputTokens,B.cached_input_tokens=R.cachedInputTokens,B.cost_usd=R.costUsd,w.model===null&&R.model!==null&&(B.model=R.model),I[We]="recorded"):!Do(w)&&I[We]!=="recorded"&&(I[We]="unavailable"),B.metadata=JSON.stringify(I);let ke=w.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,w.run_epoch),Tn=w.heartbeat_at===null?isNull(a.heartbeat_at):eq(a.heartbeat_at,w.heartbeat_at),or=n.db.update(a).set(B).where(and(eq(a.id,w.id),eq(a.status,"running"),ke,Tn)).run();return or.changes>0&&E++,or.changes>0};for(let w of r){if(w.status==="pending"){if(w.pid!==null||w.started_at>=p)continue;let R=Po(w.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:g,metadata:R}).where(and(eq(a.id,w.id),eq(a.status,"pending"),isNull(a.pid),lt(a.started_at,p))).run().changes>0&&E++;continue}if(eg.has(w.platform??"cli"))continue;if(w.pid===null){let R=`${w.id}:${w.run_epoch??0}`;h.add(R);let B=this.pidNullObservedSince.get(R);if(B===void 0){this.pidNullObservedSince.set(R,s);continue}s-B>=Lo&&S(w,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(R);continue}if(w.heartbeat_at===null){ft(w.pid,this.processControl.kill)==="not_found"&&S(w,"Reaped: process not found (orphaned task)");continue}let x=Date.parse(w.heartbeat_at),I=Number.isFinite(x)?s-x:Number.POSITIVE_INFINITY;if(I<=c)continue;let b=mo(w).filter(R=>ft(R.pid,this.processControl.kill)!=="not_found");b.length===0?S(w,"Reaped: process not found (orphaned task)"):I>l&&d&&m.push({row:w,targets:b});}let P=new Map;for(let w of m){let{row:x,targets:I}=w,b=n.db.select({status:a.status,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at}).from(a).where(eq(a.id,x.id)).get();if(!b||b.status!=="running"||G(b.run_epoch)!==G(x.run_epoch)||b.heartbeat_at!==x.heartbeat_at)continue;let R=await this.judgeRecordedTargets(x,I);if(R.unproven!==void 0){console.warn("[crewx] reaper left running task",{taskId:x.id,reason:R.unproven});continue}if(R.owned.length>0){let B=await this.terminateRecordedProcesses(R.owned,P);if(B!==void 0){console.warn("[crewx] reaper left running task",{taskId:x.id,reason:B});continue}}S(x,"Reaped: heartbeat stale beyond hard limit (orphaned task)")&&R.reused.length>0&&console.warn("[crewx] reaper reaped task whose recorded pid was reused",{taskId:x.id,reason:R.reused.join("; ")});}for(let w of Array.from(this.pidNullObservedSince.keys()))h.has(w)||this.pidNullObservedSince.delete(w);return E}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+Fn()+Rr:void 0,o=[],i=[];for(let u of n){let d=await ko(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 _t(r.pid,{...this.processControl,signal:gt})).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(ft(r.pid,this.processControl.kill)!=="not_found")return `pid ${r.pid} still alive after termination`}}reapRunningWorkflowTasks(e=Lo){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(isNull(a.metadata),au())),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=re(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(ne).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(ne).from(a).where(c).orderBy(desc(a.started_at)).limit(1).get()??void 0;}if(d)return Be(d)}catch(i){throw new f("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(ne).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(Be(l)));}catch(d){throw new f("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`
|
|
140
|
+
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${pr}
|
|
141
|
+
WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[o.id,o.agent_id,o.prompt,o.mode,o.status,o.started_at,o.pid,o.parent_task_id,o.caller_agent_id,o.trace_id,o.command,o.metadata,o.workspace_id,...l?[o.cwd]:[],o.project_id,o.platform,o.crewx_version,o.thread_id,o.model,o.rendered_prompt,o.coding_agent_command,...p?[o.user_id]:[],..._?[o.actor_kind]:[],...h?[o.actor_id]:[],...m?[o.log_storage]:[]]);}r&&!s&&new Dr({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"||G(r.run_epoch)!==G(e.runEpoch))return !1;let s=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:$o(e.pid,this.processControl)}).where(and(eq(a.id,e.id),eq(a.status,"running"),s)).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"||G(r.run_epoch)!==G(e.runEpoch))return !1;let s=T_(r.metadata,e.runtime?.metadata);if(s.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0){s.providerPid=e.providerPid;let c=$o(e.providerPid,this.processControl);c!==null?s.providerPidStartedAt=c:delete s.providerPidStartedAt;}let o=r.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,r.run_epoch),i=n.db.update(a).set({metadata:JSON.stringify(s),model:Xr(r.model,e.runtime?.model),rendered_prompt:Xr(r.rendered_prompt,e.runtime?.renderedPrompt),security_key:Xr(r.security_key,e.runtime?.securityKey),coding_agent_command:Xr(r.coding_agent_command,e.runtime?.codingAgentCommand)}).where(and(eq(a.id,e.id),eq(a.status,"running"),o)).run();return i.changes>0&&G(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"),o,sql`${a.stop_requested_at} IS NOT NULL
|
|
142
|
+
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 s=this.openHandle(true);try{return s.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(o){throw o instanceof f?o:new f("DB_ERROR","Failed to fail pending task",o)}finally{s.close();}}stopPendingTask(e,n,r=new Date().toISOString(),s={}){let o=this.openHandle(true);try{let i=!1;return o.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=Mo(se(d.metadata),n),l={...u.metadata,stopMethod:"cooperative",stopRequest:Yr(s,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{o.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select(ne).from(a).where(eq(a.project_id,e)).orderBy(desc(a.started_at)).all().map(ze)}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,s;try{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,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=G(i.run_epoch),d=G(e.runEpoch),u=i.status==="running"&&c===d,l=i.stop_requested_at!==null&&G(i.stop_requested_epoch)===c,p=u&&l,_=i.status==="stopped"&&c===d&&l,h=se(i.metadata),m=hn(h[Qn])?h[Qn]:{},E=String(d),S=m_(i),D=S&&c===d&&!qo(i)&&!Object.prototype.hasOwnProperty.call(m,E),y=S&&c===d&&!Object.prototype.hasOwnProperty.call(m,E),v=c>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||c!==d,I={},N;if(i.status!=="running"&&(r=i.status,s=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),v&&(i.status==="running"||y)){N=se(i.metadata);let R=hn(N[Lo])?{...N[Lo]}:{};R[String(d)]=Tc(e),N[Lo]=R;let B=E_(R),we=B.inputTokens!==0||B.outputTokens!==0||B.cachedInputTokens!==0||B.costUsd!==0;we&&h[Ke]==="unavailable"?N[Ke]="recorded":i.status!=="running"&&!we&&h[Ke]===void 0&&(N[Ke]="unavailable"),I.metadata=JSON.stringify(N),I.input_tokens=B.inputTokens,I.output_tokens=B.outputTokens,I.cached_input_tokens=B.cachedInputTokens,I.cost_usd=B.costUsd;}else if(u||D)if(u)I.input_tokens=le(e.inputTokens??0),I.output_tokens=le(e.outputTokens??0),I.cached_input_tokens=le(e.cachedInputTokens??0),I.cost_usd=le(e.costUsd??0);else {let R=Tc(e),B=R.inputTokens!==0||R.outputTokens!==0||R.cachedInputTokens!==0||R.costUsd!==0;B&&(I.input_tokens=R.inputTokens,I.output_tokens=R.outputTokens,I.cached_input_tokens=R.cachedInputTokens,I.cost_usd=R.costUsd),N={...h};let we=hn(h[Qn])?{...h[Qn]}:{};we[E]={at:e.completedAt},N[Qn]=we,N[Ke]===void 0?N[Ke]=B?"recorded":"unavailable":B&&N[Ke]==="unavailable"&&(N[Ke]="recorded"),I.metadata=JSON.stringify(N);}if((u||D)&&e.model!==void 0&&e.model!==null&&(!D||i.model===null)&&(I.model=e.model),p){N??=se(i.metadata);let R=Mo(N,e.error);N={...R.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:Jr(i.stop_requested_at,e.completedAt)},I.status="stopped",I.result=e.result??i.result,I.error=R.error,I.completed_at=e.completedAt,I.duration_ms=i.duration_ms??e.durationMs??Qr(i.started_at,e.completedAt,void 0),I.exit_code=e.exitCode??i.exit_code,I.metadata=JSON.stringify(N);}else if(u)e.partialResultRecovered===!0&&(N??=se(i.metadata),N.partialResultRecovered=!0,I.metadata=JSON.stringify(N)),I.status=e.status,I.result=e.result??null,I.error=e.error??null,I.completed_at=e.completedAt,I.duration_ms=c>0?Qr(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,I.exit_code=e.exitCode??null;else if(_){let R=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(I.result=e.result,R=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(I.exit_code=e.exitCode),e.partialResultRecovered===!0&&(N??=se(i.metadata),N.partialResultRecovered=!0,I.metadata=JSON.stringify(N)),R&&(r=void 0,s=void 0);}Object.keys(I).length>0&&o.update(a).set(I).where(eq(a.id,e.id)).run();},{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to finish task",o)}finally{n.close();}if(r!==void 0){try{this.taskLogRepository.appendLog(e.id,{timestamp:e.completedAt,level:"late-result",message:s??`task:end status=${e.status}`});}catch(o){console.error(`[crewx] failed to preserve late task result for ${e.id}: ${o instanceof Error?o.message:String(o)}`);}process.stderr.write(`Task ${e.id} was already finalized (${r}); late result kept in task log
|
|
143
|
+
`);}}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=se(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 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(ne).from(a).where(eq(a.status,"running")).orderBy(desc(a.started_at)).all().map(ze)}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(ne).from(a).where(inArray(a.status,["pending","running"])).orderBy(desc(a.started_at)).all().map(ze)}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(ne).from(a).orderBy(desc(a.started_at)).limit(100).all().map(ze)}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=G(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 c=i.select({run_epoch:a.run_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!c||G(c.run_epoch)!==n)return;o=i.insert(dt).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 f?o:new f("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=G(s.run_epoch),i=r.db.select({run_epoch:dt.run_epoch,key_wrap_skipped:dt.key_wrap_skipped}).from(dt).where(eq(dt.task_id,e)).all(),c=new Map(i.map(u=>[u.run_epoch,u])),d=[];for(let u=1;u<=o;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(s){throw s instanceof f?s:new f("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(dt).where(and(eq(dt.task_id,e),eq(dt.run_epoch,G(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 f("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(ne).from(a).where(eq(a.id,e)).limit(1).get();return r?ze(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(eq(a.status,"running"),eq(a.status,"pending"))).all(),s=this.clock(),o=Math.max(1,Math.trunc(e.tickIntervalMs??Sc)),i=this.lastReaperTickAt,c=i===void 0?Number.POSITIVE_INFINITY:s-i,d=i!==void 0&&c>=0&&c<=o*2;this.lastReaperTickAt=s;let u=pn(),l=Kr(),p=new Date(s-Rc).toISOString(),_=new Date(s).toISOString(),h=new Set,m=[],E=0,S=(y,v)=>{let I=se(Fo(y.metadata,"runner_lost")),N=typeof I.provider=="string"?I.provider:void 0,R;try{R=jr({taskLogRepository:this.taskLogRepository,taskId:y.id,provider:N,model:y.model})?.usage;}catch{}let B={status:"failed",error:v,completed_at:_};R?(B.input_tokens=R.inputTokens,B.output_tokens=R.outputTokens,B.cached_input_tokens=R.cachedInputTokens,B.cost_usd=R.costUsd,y.model===null&&R.model!==null&&(B.model=R.model),I[Ke]="recorded"):!qo(y)&&I[Ke]!=="recorded"&&(I[Ke]="unavailable"),B.metadata=JSON.stringify(I);let we=y.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,y.run_epoch),An=y.heartbeat_at===null?isNull(a.heartbeat_at):eq(a.heartbeat_at,y.heartbeat_at),pr=n.db.update(a).set(B).where(and(eq(a.id,y.id),eq(a.status,"running"),we,An)).run();return pr.changes>0&&E++,pr.changes>0};for(let y of r){if(y.status==="pending"){if(y.pid!==null||y.started_at>=p)continue;let R=Fo(y.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:_,metadata:R}).where(and(eq(a.id,y.id),eq(a.status,"pending"),isNull(a.pid),lt$1(a.started_at,p))).run().changes>0&&E++;continue}if(g_.has(y.platform??"cli"))continue;if(y.pid===null){let R=`${y.id}:${y.run_epoch??0}`;h.add(R);let B=this.pidNullObservedSince.get(R);if(B===void 0){this.pidNullObservedSince.set(R,s);continue}s-B>=Bo&&S(y,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(R);continue}if(y.heartbeat_at===null){mt(y.pid,this.processControl.kill)==="not_found"&&S(y,"Reaped: process not found (orphaned task)");continue}let v=Date.parse(y.heartbeat_at),I=Number.isFinite(v)?s-v:Number.POSITIVE_INFINITY;if(I<=u)continue;let N=So(y).filter(R=>mt(R.pid,this.processControl.kill)!=="not_found");N.length===0?S(y,"Reaped: process not found (orphaned task)"):I>l&&d&&m.push({row:y,targets:N});}let D=new Map;for(let y of m){let{row:v,targets:I}=y,N=n.db.select({status:a.status,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at}).from(a).where(eq(a.id,v.id)).get();if(!N||N.status!=="running"||G(N.run_epoch)!==G(v.run_epoch)||N.heartbeat_at!==v.heartbeat_at)continue;let R=await this.judgeRecordedTargets(v,I);if(R.unproven!==void 0){console.warn("[crewx] reaper left running task",{taskId:v.id,reason:R.unproven});continue}if(R.owned.length>0){let B=await this.terminateRecordedProcesses(R.owned,D);if(B!==void 0){console.warn("[crewx] reaper left running task",{taskId:v.id,reason:B});continue}}S(v,"Reaped: heartbeat stale beyond hard limit (orphaned task)")&&R.reused.length>0&&console.warn("[crewx] reaper reaped task whose recorded pid was reused",{taskId:v.id,reason:R.reused.join("; ")});}for(let y of Array.from(this.pidNullObservedSince.keys()))h.has(y)||this.pidNullObservedSince.delete(y);return E}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+Kn()+xr:void 0,o=[],i=[];for(let c of n){let d=await Io(c,{processControlOptions:this.processControl,legacyStartBoundaryMs:s});if(d.verdict==="owned")o.push(c);else if(d.verdict==="reused")i.push(`pid ${c.pid} reused (${d.reason})`);else return {owned:o,reused:i,unproven:`pid ${c.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 Tt(r.pid,{...this.processControl,signal:kt})).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(mt(r.pid,this.processControl.kill)!=="not_found")return `pid ${r.pid} still alive after termination`}}reapRunningWorkflowTasks(e=Bo){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$1(a.started_at,r),or(isNull(a.metadata),mc())),o=n.db.select({id:a.id,metadata:a.metadata}).from(a).where(s).all(),i=new Date().toISOString(),c=0;for(let d of o){let u=se(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 s of r){if(!existsSync(s))continue;let o=$(s);try{let i=n?eq(a.workspace_id,n):void 0,c=i?and(eq(a.id,e),i):eq(a.id,e),d=o.db.select(ne).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=o.db.select(ne).from(a).where(u).orderBy(desc(a.started_at)).limit(1).get()??void 0;}if(d)return ze(d)}catch(i){throw new f("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 c=$(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(ne).from(a).where(d).orderBy(asc(a.started_at)).all();for(let l of u)s.has(l.id)||(s.add(l.id),o.push(ze(l)));}catch(d){throw new f("DB_ERROR","Failed to find child tasks",d)}finally{c.close();}}return o}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?sql`
|
|
144
144
|
SELECT
|
|
145
145
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
146
146
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -161,33 +161,33 @@ ${r.join(`
|
|
|
161
161
|
FROM tasks
|
|
162
162
|
GROUP BY workspace_id
|
|
163
163
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
164
|
-
`)}catch(r){throw new f("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),s=new Set,o=0,i=0,
|
|
164
|
+
`)}catch(r){throw new f("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),s=new Set,o=0,i=0,c=0;for(let d of r){if(!existsSync(d))continue;let u=$(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 _)s.has(h.id)||(s.add(h.id),o+=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:o,outputTokens:i,costUsd:c}}findTasksByThread(e,n,r){let s=this.resolveDbPaths(),o=new Set,i=[],c=r?.projection==="activity-log";for(let d of s){if(!existsSync(d))continue;let u=$(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(ne).from(a).where(p).orderBy(asc(a.started_at)).all().map(ze);for(let h of _)o.has(h.id)||(o.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=$(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"]),Co())).orderBy(desc(a.started_at)).all().map(vo));}catch(s){throw new f("DB_ERROR","Failed to find workflow parent tasks",s)}finally{r.close();}}return e}findWorkflowParentTasksByWorkspace(e){let n=[],r=new Map;for(let s of this.resolveDbPaths()){if(!existsSync(s))continue;let o=$(s);try{let i=o.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(!Ln(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(vo(c)));}}catch(i){throw new f("DB_ERROR","Failed to find workflow parent tasks by workspace",i)}finally{o.close();}}return n}findWorkflowParentTask(e){if(this.dbExists())for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let r=$(n);try{let s=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 o of s){let i=this.parseWorkflowCardMetadata(o.metadata);if(i.kind===e.kind&&i.workflowRunId===e.workflowRunId)return vo(o)}}catch(s){throw new f("DB_ERROR","Failed to find workflow parent task",s)}finally{r.close();}}}batchFetchWorkflowCards(e,n){let r=new Map;if(e.length===0)return r;let s=new Set(e),o=new Map,i=n?eq(a.workspace_id,n):void 0,c=(d,u)=>{if(!d)return;let l=o.get(d);if(l&&u.started_at<=l)return;let p=this.parseWorkflowCardMetadata(u.metadata);Ln(p.kind)&&(o.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=$(d);try{let l=and(inArray(a.thread_id,e),Co()),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),Co()),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 E=this.extractThreadIdFromCommand(m.command);!E||!s.has(E)||c(E,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 s=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;s&&r.push(inArray(a.agent_id,s));let o=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;o&&r.push(inArray(a.status,po(o)));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$1(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(ne).from(a).where(c).orderBy(u).limit(e.limit).offset(e.offset).all().map(ze),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 s=this.openHandle(false);try{let o=Po(sql.raw("t.model"),sql.raw("t.metadata")),i=Zn(sql.raw("t.status")),c=Vr(sql.raw("t.metadata")),d=sql`
|
|
165
165
|
COALESCE(t.input_tokens, 0)
|
|
166
166
|
+ CASE
|
|
167
|
-
WHEN t.started_at >= ${
|
|
167
|
+
WHEN t.started_at >= ${fn}
|
|
168
168
|
AND (
|
|
169
169
|
t.crewx_version IS NULL
|
|
170
170
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
171
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
171
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${_n}) AS INTEGER) < ${gn})
|
|
172
172
|
)
|
|
173
173
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
174
174
|
ELSE 0
|
|
175
175
|
END
|
|
176
|
-
`,
|
|
176
|
+
`,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=s.db.all(sql`
|
|
177
177
|
SELECT
|
|
178
178
|
t.agent_id,
|
|
179
179
|
t.workspace_id,
|
|
180
180
|
${o} AS provider,
|
|
181
181
|
COUNT(*) AS total_tasks,
|
|
182
|
-
${
|
|
182
|
+
${c} AS unavailable_task_count,
|
|
183
183
|
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
184
184
|
COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
|
|
185
185
|
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
186
186
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
187
187
|
FROM tasks t
|
|
188
|
-
${
|
|
188
|
+
${u}
|
|
189
189
|
GROUP BY t.agent_id, t.workspace_id, ${o}
|
|
190
|
-
`),p=new Map;for(let m of l){let E=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",S={provider:E,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},
|
|
190
|
+
`),p=new Map;for(let m of l){let E=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",S={provider:E,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},D=m.workspace_id??null,y=JSON.stringify([m.agent_id,D]),v=p.get(y);if(!v){p.set(y,{agentId:m.agent_id,workspaceId:D,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:[S]});continue}v.totalTasks+=m.total_tasks,v.unavailableTaskCount=(v.unavailableTaskCount??0)+m.unavailable_task_count,v.inputTokens+=m.input_tokens,v.outputTokens+=m.output_tokens,v.cachedInputTokens+=m.cached_input_tokens,v.costUsd+=m.cost_usd,v.totalTokens+=m.input_tokens+m.output_tokens;let I=v.providers.find(N=>N.provider===E);I?(I.inputTokens+=S.inputTokens,I.outputTokens+=S.outputTokens,I.cachedInputTokens+=S.cachedInputTokens,I.totalTokens+=S.totalTokens,I.costUsd+=S.costUsd,I.totalTasks+=S.totalTasks,I.unavailableTaskCount+=S.unavailableTaskCount):v.providers.push(S);}let _=[...p.values()];for(let m of _)m.providers.sort((E,S)=>E.provider===S.provider?0:E.provider==="unknown"?1:S.provider==="unknown"?-1:E.totalTokens!==S.totalTokens?S.totalTokens-E.totalTokens:E.provider<S.provider?-1:1);let h=(m,E)=>m===E?0:m<E?-1:1;return _.sort((m,E)=>{if(m.totalTokens!==E.totalTokens)return E.totalTokens-m.totalTokens;let S=h(m.agentId,E.agentId);return S!==0?S:m.workspaceId===E.workspaceId?0:m.workspaceId===null?1:E.workspaceId===null?-1:h(m.workspaceId,E.workspaceId)}),_}catch(o){throw new f("DB_ERROR","Failed to get agent usage",o)}finally{s.close();}}getAgentUsageTrendRaw(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=Zn(sql.raw("t.status")),i=Vr(sql.raw("t.metadata"));return s.db.all(r?sql`
|
|
191
191
|
SELECT
|
|
192
192
|
date(t.started_at) AS date,
|
|
193
193
|
t.agent_id,
|
|
@@ -195,11 +195,11 @@ ${r.join(`
|
|
|
195
195
|
COALESCE(SUM(
|
|
196
196
|
COALESCE(t.input_tokens, 0)
|
|
197
197
|
+ CASE
|
|
198
|
-
WHEN t.started_at >= ${
|
|
198
|
+
WHEN t.started_at >= ${fn}
|
|
199
199
|
AND (
|
|
200
200
|
t.crewx_version IS NULL
|
|
201
201
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
202
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
202
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${_n}) AS INTEGER) < ${gn})
|
|
203
203
|
)
|
|
204
204
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
205
205
|
ELSE 0
|
|
@@ -224,11 +224,11 @@ ${r.join(`
|
|
|
224
224
|
COALESCE(SUM(
|
|
225
225
|
COALESCE(t.input_tokens, 0)
|
|
226
226
|
+ CASE
|
|
227
|
-
WHEN t.started_at >= ${
|
|
227
|
+
WHEN t.started_at >= ${fn}
|
|
228
228
|
AND (
|
|
229
229
|
t.crewx_version IS NULL
|
|
230
230
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
231
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
231
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${_n}) AS INTEGER) < ${gn})
|
|
232
232
|
)
|
|
233
233
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
234
234
|
ELSE 0
|
|
@@ -244,23 +244,23 @@ ${r.join(`
|
|
|
244
244
|
AND t.agent_id != 'workflow'
|
|
245
245
|
GROUP BY date(t.started_at), t.agent_id
|
|
246
246
|
ORDER BY date(t.started_at) ASC
|
|
247
|
-
`).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(o){throw new f("DB_ERROR","Failed to get agent usage trend",o)}finally{s.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let s=r.db.select(ne).from(a).where(and(eq(a.id,e),eq(a.workspace_id,n))).limit(1).get();return s?
|
|
247
|
+
`).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(o){throw new f("DB_ERROR","Failed to get agent usage trend",o)}finally{s.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let s=r.db.select(ne).from(a).where(and(eq(a.id,e),eq(a.workspace_id,n))).limit(1).get();return s?ze(s):void 0}catch(s){throw new f("DB_ERROR","Failed to find task for stop",s)}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,s="failed",o){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:s,error:n,completed_at:c};if(o){let p=se(u.metadata);p.terminalReason=o,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(),s=new Set,o=[];for(let i of r){if(!existsSync(i))continue;let c=$(i);try{let d=n?and(like(a.prompt,`%${e}%`),eq(a.workspace_id,n)):like(a.prompt,`%${e}%`),u=c.db.select(ne).from(a).where(d).orderBy(asc(a.started_at)).all();for(let l of u)s.has(l.id)||(s.add(l.id),o.push(ze(l)));}catch(d){throw new f("DB_ERROR","Failed to find tasks by prompt hint",d)}finally{c.close();}}return o}getProviderUsage(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=Po(),i=Zn(a.status),c=Vr(a.metadata),d=sql`
|
|
248
248
|
COALESCE(${a.input_tokens}, 0)
|
|
249
249
|
+ CASE
|
|
250
|
-
WHEN ${a.started_at} >= ${
|
|
250
|
+
WHEN ${a.started_at} >= ${fn}
|
|
251
251
|
AND (
|
|
252
252
|
${a.crewx_version} IS NULL
|
|
253
253
|
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
254
|
-
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${
|
|
254
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${_n}) AS INTEGER) < ${gn})
|
|
255
255
|
)
|
|
256
256
|
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
257
257
|
ELSE 0
|
|
258
258
|
END
|
|
259
|
-
`,
|
|
259
|
+
`,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 s.db.all(sql`
|
|
260
260
|
SELECT
|
|
261
261
|
${o} AS provider,
|
|
262
262
|
COUNT(*) AS total_tasks,
|
|
263
|
-
${
|
|
263
|
+
${c} AS unavailable_task_count,
|
|
264
264
|
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
265
265
|
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens,
|
|
266
266
|
COALESCE(SUM(${a.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
@@ -268,27 +268,27 @@ ${r.join(`
|
|
|
268
268
|
COALESCE(SUM(${a.duration_ms}), 0) AS active_duration_ms,
|
|
269
269
|
MAX(${a.completed_at}) AS last_active_at
|
|
270
270
|
FROM ${a}
|
|
271
|
-
${
|
|
271
|
+
${u}
|
|
272
272
|
GROUP BY ${o}
|
|
273
273
|
ORDER BY (COALESCE(SUM(${d}), 0) + COALESCE(SUM(${a.output_tokens}), 0)) DESC
|
|
274
|
-
`).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(o){throw new f("DB_ERROR","Failed to get provider usage",o)}finally{s.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=
|
|
274
|
+
`).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(o){throw new f("DB_ERROR","Failed to get provider usage",o)}finally{s.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=Po(),i=Zn(a.status),c=Vr(a.metadata),d=sql`
|
|
275
275
|
COALESCE(${a.input_tokens}, 0)
|
|
276
276
|
+ CASE
|
|
277
|
-
WHEN ${a.started_at} >= ${
|
|
277
|
+
WHEN ${a.started_at} >= ${fn}
|
|
278
278
|
AND (
|
|
279
279
|
${a.crewx_version} IS NULL
|
|
280
280
|
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
281
|
-
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${
|
|
281
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${_n}) AS INTEGER) < ${gn})
|
|
282
282
|
)
|
|
283
283
|
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
284
284
|
ELSE 0
|
|
285
285
|
END
|
|
286
|
-
`,
|
|
286
|
+
`,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=s.db.all(sql`
|
|
287
287
|
SELECT
|
|
288
288
|
${a.model} AS model,
|
|
289
289
|
${o} AS provider,
|
|
290
290
|
COUNT(*) AS total_tasks,
|
|
291
|
-
${
|
|
291
|
+
${c} AS unavailable_task_count,
|
|
292
292
|
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
293
293
|
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens,
|
|
294
294
|
COALESCE(SUM(${a.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
@@ -296,9 +296,9 @@ ${r.join(`
|
|
|
296
296
|
COALESCE(SUM(${a.duration_ms}), 0) AS active_duration_ms,
|
|
297
297
|
MAX(${a.completed_at}) AS last_active_at
|
|
298
298
|
FROM ${a}
|
|
299
|
-
${
|
|
299
|
+
${u}
|
|
300
300
|
GROUP BY ${a.model}, ${o}
|
|
301
|
-
`),p=new Map;for(let
|
|
301
|
+
`),p=new Map;for(let _ of l){let h=Us(_.model??""),m=JSON.stringify([_.provider,h]),E=p.get(m);E?(E.totalTasks+=_.total_tasks,E.unavailableTaskCount=(E.unavailableTaskCount??0)+_.unavailable_task_count,E.inputTokens+=_.input_tokens,E.outputTokens+=_.output_tokens,E.cachedInputTokens+=_.cached_input_tokens,E.costUsd+=_.cost_usd,E.totalTokens+=_.input_tokens+_.output_tokens,E.activeDurationMs+=_.active_duration_ms??0,_.last_active_at&&(!E.lastActiveAt||_.last_active_at>E.lastActiveAt)&&(E.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(o){throw new f("DB_ERROR","Failed to get model usage",o)}finally{s.close();}}getTasksForReport(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=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 s.db.all(sql`
|
|
302
302
|
SELECT
|
|
303
303
|
${a.thread_id} AS thread_id,
|
|
304
304
|
${a.agent_id} AS agent_id,
|
|
@@ -310,19 +310,19 @@ ${r.join(`
|
|
|
310
310
|
FROM ${a}
|
|
311
311
|
${o}
|
|
312
312
|
ORDER BY ${a.started_at} ASC
|
|
313
|
-
`).map(
|
|
313
|
+
`).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:Ge({status:c.status,error:c.error,metadata:c.metadata})??null}))}catch(o){throw new f("DB_ERROR","Failed to get tasks for report",o)}finally{s.close();}}getDelegationMatrix(e,n,r){if(!this.dbExists())return {edges:[],truncated:false};let s=this.openHandle(false);try{let o=sql`
|
|
314
314
|
COALESCE(${a.input_tokens}, 0)
|
|
315
315
|
+ CASE
|
|
316
|
-
WHEN ${a.started_at} >= ${
|
|
316
|
+
WHEN ${a.started_at} >= ${fn}
|
|
317
317
|
AND (
|
|
318
318
|
${a.crewx_version} IS NULL
|
|
319
319
|
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
320
|
-
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${
|
|
320
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${_n}) AS INTEGER) < ${gn})
|
|
321
321
|
)
|
|
322
322
|
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
323
323
|
ELSE 0
|
|
324
324
|
END
|
|
325
|
-
`,i=
|
|
325
|
+
`,i=Zn(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=s.db.all(sql`
|
|
326
326
|
SELECT
|
|
327
327
|
${a.caller_agent_id} AS caller_agent_id,
|
|
328
328
|
${a.agent_id} AS agent_id,
|
|
@@ -330,31 +330,31 @@ ${r.join(`
|
|
|
330
330
|
COALESCE(SUM(${o}), 0) AS input_tokens,
|
|
331
331
|
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens
|
|
332
332
|
FROM ${a}
|
|
333
|
-
${
|
|
333
|
+
${c}
|
|
334
334
|
GROUP BY ${a.caller_agent_id}, ${a.agent_id}
|
|
335
335
|
ORDER BY task_count DESC, ${a.caller_agent_id} ASC, ${a.agent_id} ASC
|
|
336
|
-
LIMIT ${
|
|
337
|
-
`),
|
|
336
|
+
LIMIT ${Do+1}
|
|
337
|
+
`),u=d.length>Do;return {edges:d.slice(0,Do).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(o){throw new f("DB_ERROR","Failed to get delegation matrix",o)}finally{s.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,po(e.statuses))),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt$1(a.started_at,e.to));let s=r.length>0?and(...r):void 0,o=(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(s).orderBy(o).limit(e.limit).all():n.db.select(i).from(a).where(s).orderBy(o).all()).map(({error:d,metadata:u,...l})=>({...l,status:xe({status:l.status,error:d,metadata:u}),terminalReason:Ge({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,s=e.maxTurnsPerThread??4,o=[isNotNull(a.thread_id),isNull(a.parent_task_id),isNull(a.caller_agent_id),or(isNull(a.platform),ne$1(a.platform,"workflow")),or(isNull(a.metadata),mc()),or(isNull(a.metadata),notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&o.push(eq(a.workspace_id,e.workspaceId)),e.from&&o.push(gte(a.started_at,e.from)),e.to&&o.push(lt$1(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(...o)).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(-s)}))}catch(r){throw new f("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}},Ic=["up","down"],Wo=1e3,Ac=200,R_=64,tr=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;}},S_=new Set(jt);});g();g();g();var lt=class{detach(e){}};g();function oi(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 gs(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var hs=class extends lt{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=oi(n.timestamp),s=join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,s);let o=`=== TASK LOG: ${n.traceId} ===
|
|
338
338
|
CrewX Version: ${this.version}
|
|
339
339
|
Mode: ${n.mode}
|
|
340
340
|
Agent: ${n.agentRef}
|
|
341
|
-
Started: ${
|
|
341
|
+
Started: ${gs(n.timestamp)}
|
|
342
342
|
Message: ${n.message}
|
|
343
343
|
|
|
344
344
|
`;writeFileSync(s,o,{encoding:"utf8",mode:384});}catch{}}),e.on("task:output",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let s=new Date().toISOString();appendFileSync(r,`[${s}] STDOUT: ${n.output}
|
|
345
|
-
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let s=
|
|
345
|
+
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let s=gs(new Date),o=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${s}] INFO: Task ${o} in ${n.durationMs}ms
|
|
346
346
|
[${s}] INFO: Process closed with exit code: ${n.error?1:0}
|
|
347
|
-
`;appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};_();_();var ti=Symbol.for("crewx.interceptor.run-stops");function rc(){let t=globalThis,e=t[ti];if(e)return e;let n=new Map;return t[ti]=n,n}function ni(t){let e=rc().get(t);return e?(e.abort(),true):false}_();var Bt=new Map;function ir(t){let e=pe.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 oi(t){let e=ir(t);return createHash("sha256").update(e).digest("hex")}function ii(t){let e=ir(t),n=Bt.get(e);if(n!==void 0)return n;let r=e;try{let s=pe.join(e,".git");if(!lstatSync(s).isFile())return Bt.set(e,r),r;let o=/^gitdir:\s*(.+?)\s*$/i.exec(readFileSync(s,"utf8").trim());if(!o)return Bt.set(e,r),r;let i=o[1],u=pe.isAbsolute(i)?i:pe.resolve(pe.dirname(s),i),d=readFileSync(pe.join(u,"commondir"),"utf8").trim();if(!d)return Bt.set(e,r),r;let c=pe.isAbsolute(d)?d:pe.resolve(u,d);if(pe.basename(c)!==".git"||!statSync(c).isDirectory())return Bt.set(e,r),r;let l=ir(realpathSync.native(e)),p=ir(realpathSync.native(pe.dirname(c)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return Bt.set(e,r),r}dt();Eo();Kt();no();Bn();yo();Sr();var gg=200,_g=200;function hg(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 mg(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=hg(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function wu(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function kg(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function yu(t){if(!t)return {};try{let e=JSON.parse(t);return kg(e)?e:{}}catch{return {}}}function ln(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Tg=new Set(["workflow","mcp"]),Ho=class extends at{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 Kn({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?ii(r):r,i=s?oi(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:g,assignedTaskId:h}=this.runnerIdentity,m=h??d.traceId,E=ln(d.metadata?.runEpoch),S=g?"runner":"caller",P=d.workspaceId??i,w=g?n.getTask(m):void 0,x=d.pid??null,I={...d.metadata??{provider:d.provider??"cli/claude"},ownership:S,...g&&x!==null?{providerPid:x}:{}},b=JSON.stringify(I);if(g&&w?.status==="running"&&w.pid!==null&&E===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:g?process.pid:x,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:P,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:E,ownership:S,...g?{providerPid:x}:{},runtime:{model:d.model??null,renderedPrompt:d.renderedPrompt??null,codingAgentCommand:d.codingAgentCommand??null,metadata:I}})?this.recordOwnedTaskRun({taskId:m,runEpoch:E,workspaceId:P,ownership:S}):console.warn("[crewx] task execution metadata not recorded",{taskId:m,runEpoch:E,ownership:S}),Tg.has(d.platform??"cli")||Yd(n,{taskId:m,runEpoch:E,onStopRequested:Tn=>this.handleStopRequested(n,Tn)})&&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],wu(l));}}),e.on("task:run-update",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;let l=ln(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,ln(l)),qn(c,l)&&this.heartbeatTaskIds.delete(c),this.flushTaskLogs(c);let g=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,E=d.metadata?.suppressPartialResultRecovery===!0;if(d.error&&!E&&(!h||h.trim()==="")){let S=this.recoverPartialResult(c,d,l);S&&(h=S,m=!0);}n.finishTask({id:c,status:d.error?"failed":"success",result:h,error:g,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,model:d.model??null,runEpoch:l,partialResultRecovered:m});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers();for(let n of this.heartbeatTaskIds)qn(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 su(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+=wu(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>=gg){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));},_g);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"||ln(o.run_epoch)!==ln(r))return;let i=yu(o.metadata),u=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!u)return;let d=Hr({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()||et(c,u)?void 0:c}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let s=ln(n.run_epoch),o=yu(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(ni(r),d!==void 0){let c;try{c=await _t(d,{signal:gt});}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:qr(n.stop_requested_at)}),l=e.getTask(r);(c||l?.status!=="running")&&qn(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=mg(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});}};_();_();_();ut();Rt();St();dt();vt();Tr();Hn();_();function Vr(t){return t!==null&&t!==""}function wg(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":Vr(t.parent_task_id)||Vr(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function Eu(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&Vr(e)?e:null}}function Xr(t){let e=wg(t),n=Vr(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 Ru(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?Eu(t.creator_actor_kind,t.creator_actor_id):e?Xr(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?Eu(t.created_by_kind,t.created_by_id):n?Xr(n):void 0}function Vn(t){return $n(t)}function Ag({metadata:t,...e}){return {...e,status:Oe({...e,metadata:t}),terminalReason:Fe({...e,metadata:t})??null}}var Xn=32,Iu=100,Og=["running","failed"];function bg(t){return t==="running"?0:t==="failed"?1:2}function Au(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 Ng(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function xg(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 Ou(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function Uo(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function vg(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function Fo(t,e,n,r){let s=vg(e);s&&(t[s]+=r,t.total+=r,s==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var Qr=900,bu=20;function Nu(t,e){return (t?.origin??"direct")===e}function xu(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 pn=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function fn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Cg(t){let n=fn(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 vu(t,e,n){return t.get(sql`
|
|
347
|
+
`;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 di=Symbol.for("crewx.interceptor.run-stops");function fu(){let t=globalThis,e=t[di];if(e)return e;let n=new Map;return t[di]=n,n}function ci(t){let e=fu().get(t);return e?(e.abort(),true):false}g();var Jt=new Map;function fr(t){let e=_e.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 pi(t){let e=fr(t);return createHash("sha256").update(e).digest("hex")}function fi(t){let e=fr(t),n=Jt.get(e);if(n!==void 0)return n;let r=e;try{let s=_e.join(e,".git");if(!lstatSync(s).isFile())return Jt.set(e,r),r;let o=/^gitdir:\s*(.+?)\s*$/i.exec(readFileSync(s,"utf8").trim());if(!o)return Jt.set(e,r),r;let i=o[1],c=_e.isAbsolute(i)?i:_e.resolve(_e.dirname(s),i),d=readFileSync(_e.join(c,"commondir"),"utf8").trim();if(!d)return Jt.set(e,r),r;let u=_e.isAbsolute(d)?d:_e.resolve(c,d);if(_e.basename(u)!==".git"||!statSync(u).isDirectory())return Jt.set(e,r),r;let l=fr(realpathSync.native(e)),p=fr(realpathSync.native(_e.dirname(u)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return Jt.set(e,r),r}pt();bo();en();uo();Vn();No();vr();var b_=200,x_=200;function v_(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 C_(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=v_(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function xc(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function D_(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vc(t){if(!t)return {};try{let e=JSON.parse(t);return D_(e)?e:{}}catch{return {}}}function kn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var P_=new Set(["workflow","mcp"]),jo=class extends lt{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 er({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?fi(r):r,i=s?pi(o):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,E=kn(d.metadata?.runEpoch),S=_?"runner":"caller",D=d.workspaceId??i,y=_?n.getTask(m):void 0,v=d.pid??null,I={...d.metadata??{provider:d.provider??"cli/claude"},ownership:S,..._&&v!==null?{providerPid:v}:{}},N=JSON.stringify(I);if(_&&y?.status==="running"&&y.pid!==null&&E===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:v,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:D,projectId:d.projectId??null,callerAgentId:u,parentTaskId:l,traceId:p,metadata:N,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:m,runEpoch:E,ownership:S,..._?{providerPid:v}:{},runtime:{model:d.model??null,renderedPrompt:d.renderedPrompt??null,codingAgentCommand:d.codingAgentCommand??null,metadata:I}})?this.recordOwnedTaskRun({taskId:m,runEpoch:E,workspaceId:D,ownership:S}):console.warn("[crewx] task execution metadata not recorded",{taskId:m,runEpoch:E,ownership:S}),P_.has(d.platform??"cli")||ac(n,{taskId:m,runEpoch:E,onStopRequested:An=>this.handleStopRequested(n,An)})&&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],xc(l));}}),e.on("task:run-update",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;let l=kn(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,kn(l)),Jn(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,E=d.metadata?.suppressPartialResultRecovery===!0;if(d.error&&!E&&(!h||h.trim()==="")){let S=this.recoverPartialResult(u,d,l);S&&(h=S,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,model:d.model??null,runEpoch:l,partialResultRecovered:m});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers();for(let n of this.heartbeatTaskIds)Jn(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 _c(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+=xc(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>=b_){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));},x_);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"||kn(o.run_epoch)!==kn(r))return;let i=vc(o.metadata),c=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!c)return;let d=jr({taskLogRepository:s,taskId:e,provider:c,model:o.model});if(!d?.adapter.extractPartialText)return;let u=d.adapter.extractPartialText(d.stdout);return !u||!u.trim()||st(u,c)?void 0:u}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let s=kn(n.run_epoch),o=vc(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 c=typeof o.providerPid=="number"&&Number.isSafeInteger(o.providerPid)&&o.providerPid>0?o.providerPid:void 0,d=i==="runner"?c:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if(ci(r),d!==void 0){let u;try{u=await Tt(d,{signal:kt});}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:s,method:Jr(n.stop_requested_at)}),l=e.getTask(r);(u||l?.status!=="running")&&Jn(r,s)&&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,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=C_(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});}};g();g();g();ft();Ot();Nt();pt();$t();Ar();jn();g();function ns(t){return t!==null&&t!==""}function L_(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":ns(t.parent_task_id)||ns(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function Cc(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&ns(e)?e:null}}function rs(t){let e=L_(t),n=ns(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 Dc(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?Cc(t.creator_actor_kind,t.creator_actor_id):e?rs(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?Cc(t.created_by_kind,t.created_by_id):n?rs(n):void 0}function nr(t){return Gn(t)}function q_({metadata:t,...e}){return {...e,status:xe({...e,metadata:t}),terminalReason:Ge({...e,metadata:t})??null}}var rr=32,Lc=100,B_=["running","failed"];function W_(t){return t==="running"?0:t==="failed"?1:2}function Mc(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 G_(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function j_(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 $c(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function zo(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function z_(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function Ko(t,e,n,r){let s=z_(e);s&&(t[s]+=r,t.total+=r,s==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var os=900,Hc=20;function Uc(t,e){return (t?.origin??"direct")===e}function Fc(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 Tn=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function yn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function K_(t){let n=yn(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`
|
|
348
348
|
SELECT id
|
|
349
349
|
FROM tasks INDEXED BY idx_tasks_thread_id
|
|
350
350
|
WHERE thread_id = ${e}
|
|
351
351
|
AND id <> ${n}
|
|
352
352
|
LIMIT 1
|
|
353
|
-
`)!==void 0}function
|
|
353
|
+
`)!==void 0}function J_(t,e,n){let r=n?and(eq(k.id,e),eq(k.workspace_id,n)):eq(k.id,e),s=t.select({pinned:k.pinned,metadata:k.metadata}).from(k).where(r).get();if(!s)return null;let o=s.pinned?0:1,i=yn(s.metadata);if(o){let c=n?and(eq(k.pinned,1),eq(k.workspace_id,n)):eq(k.pinned,1),d=t.select({metadata:k.metadata}).from(k).where(c).all(),u=null;for(let l of d){let p=yn(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(k).set({pinned:o,metadata:Object.keys(i).length>0?JSON.stringify(i):null}).where(r).run(),{pinned:!!o}}function V_(t,e,n){for(let r=0;r<e.length;r++){let s=n?and(eq(k.id,e[r]),eq(k.workspace_id,n)):eq(k.id,e[r]),o=t.select({metadata:k.metadata}).from(k).where(s).get();if(!o)continue;let i=yn(o.metadata);i.pinOrder=r+1,t.update(k).set({metadata:JSON.stringify(i)}).where(s).run();}}var is=class extends Ee{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 s=dirname(n);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(n))throw new f("NOT_FOUND","Database not found");let r=$(n);if(e)try{De(r.db,n);}catch(s){throw r.close(),s}return r}topLevelTaskPredicateSql(e="child",n){let r=n?`tasks parent INDEXED BY ${n}`:"tasks parent";return sql.raw(`NOT EXISTS (
|
|
354
354
|
SELECT 1 FROM ${r}
|
|
355
355
|
WHERE parent.id = ${e}.parent_task_id
|
|
356
356
|
AND parent.thread_id = ${e}.thread_id
|
|
357
|
-
)`)}workflowAnchorPredicateSql(e){let n=
|
|
357
|
+
)`)}workflowAnchorPredicateSql(e){let n=ht.map(r=>`OR ${e}.metadata LIKE '%"kind":"${r}"%'`).join(`
|
|
358
358
|
`);return sql.raw(`COALESCE(
|
|
359
359
|
${e}.agent_id = 'workflow'
|
|
360
360
|
${n}
|
|
@@ -393,17 +393,17 @@ Message: ${n.message}
|
|
|
393
393
|
)
|
|
394
394
|
)`}findAllThreadsQuery(e,n){let r=[];e&&r.push(sql`workspace_id = ${e}`),n&&r.push(sql`created_by_kind = ${n}`);let s=r.length>0?sql` WHERE ${sql.join(r,sql` AND `)}`:sql``;return sql`SELECT * FROM threads${s} ORDER BY updated_at DESC`}findThreadIdsQuery(e){return e?sql`SELECT id FROM threads INDEXED BY idx_threads_ws_updated
|
|
395
395
|
WHERE workspace_id = ${e}
|
|
396
|
-
ORDER BY updated_at DESC`:sql`SELECT id FROM threads`}readThreadIds(e,n="Failed to find thread ids"){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!existsSync(i))continue;let
|
|
396
|
+
ORDER BY updated_at DESC`:sql`SELECT id FROM threads`}readThreadIds(e,n="Failed to find thread ids"){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!existsSync(i))continue;let c=$(i);try{let d=c.db.all(this.findThreadIdsQuery(e));for(let u of d)s.has(u.id)||(s.add(u.id),o.push(u.id));}catch(d){throw new f("DB_ERROR",n,d)}finally{c.close();}}return o}findThreadSortKeysQuery(e){return sql`SELECT id, updated_at
|
|
397
397
|
FROM threads INDEXED BY idx_threads_ws_updated
|
|
398
|
-
WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let i=$(o);try{let
|
|
398
|
+
WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let i=$(o);try{let c=i.db.all(this.findThreadSortKeysQuery(e));for(let d of c)r.has(d.id)||(r.add(d.id),s.push(d));}catch(c){throw new f("DB_ERROR","Failed to find recent direct threads",c)}finally{i.close();}}return s}readThreadRowsByIds(e,n,r="Failed to find threads by ids"){if(e.length===0)return [];let s=this.resolveDbPaths(),o=new Set,i=[];for(let c of s){if(!existsSync(c))continue;let d=$(c);try{for(let u=0;u<e.length;u+=os){let l=e.slice(u,u+os),p=inArray(k.id,l),_=n?and(p,eq(k.workspace_id,n)):p,h=d.db.select().from(k).where(_).all();for(let m of h)o.has(m.id)||(o.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 s=this.resolveDbPaths(),o=new Set,i=[];for(let c of s){if(!existsSync(c))continue;let d=$(c);try{let u=d.db.all(this.findAllThreadsQuery(e,n));for(let l of u)o.has(l.id)||(o.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 s of r){if(!existsSync(s))continue;let o=$(s);try{return o.db.all(sql`EXPLAIN QUERY PLAN ${this.findAllThreadsQuery(e,n)}`).map(c=>c.detail)}finally{o.close();}}return []}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!existsSync(i))continue;let c=$(i);try{let d=or(inArray(k.id,e),inArray(k.title,e)),u=n?and(d,eq(k.workspace_id,n)):d,l=c.db.select().from(k).where(u).orderBy(desc(k.updated_at)).all();for(let p of l)s.has(p.id)||(s.add(p.id),o.push(p));}catch(d){throw new f("DB_ERROR","Failed to find threads by ids or titles",d)}finally{c.close();}}return o}findThreadById(e,n){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let o=$(s);try{let i=eq(k.id,e),c=n?and(i,eq(k.workspace_id,n)):i,d=o.db.select().from(k).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{o.close();}}}createAppLaunchThread(e){let n=this.openHandle(true);try{return n.db.transaction(r=>{if(!r.select({id:te.id}).from(te).where(eq(te.id,e.workspaceId)).limit(1).get())throw new f("NOT_FOUND","Workspace not found");let o=r.select().from(k).where(eq(k.id,e.threadId)).limit(1).get();if(o){let l=yn(o.metadata).appLaunch,p=l&&typeof l=="object"&&!Array.isArray(l)?l.appId:void 0,_=r.get(sql`
|
|
399
399
|
SELECT COUNT(*) AS count FROM tasks WHERE thread_id = ${e.threadId}
|
|
400
|
-
`)?.count??0;return o.workspace_id===e.workspaceId&&p===e.appId&&o.message_count===0&&o.first_message===null&&o.last_message===null&&
|
|
400
|
+
`)?.count??0;return o.workspace_id===e.workspaceId&&p===e.appId&&o.message_count===0&&o.first_message===null&&o.last_message===null&&_===0?{status:"existing",thread:o}:{status:"conflict"}}let i=new Date().toISOString(),c=JSON.stringify({appLaunch:{appId:e.appId,...e.initialAgentId===void 0?{}:{initialAgentId:e.initialAgentId}}});r.insert(k).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(k).where(eq(k.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 s of r){if(!existsSync(s))continue;let o=$(s);try{let i=eq(k.id,e),c=n?and(i,eq(k.workspace_id,n)):i;if(o.db.select({id:k.id}).from(k).where(c).limit(1).get())return !0}catch(i){throw new f("DB_ERROR","Failed to check thread existence",i)}finally{o.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),s=0,o=0,i=0,c=0,d=0,u=0,l=0,p=0,_=0,h=0,m=new Set;for(let E of r){if(!existsSync(E))continue;let S=$(E);try{let D=S.db.get(sql`
|
|
401
401
|
SELECT count(*) AS cnt
|
|
402
402
|
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
403
403
|
WHERE child.thread_id = ${e}
|
|
404
404
|
AND ${this.topLevelTaskPredicateSql()}
|
|
405
405
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
406
|
-
`);
|
|
406
|
+
`);D&&(s+=D.cnt);let y=S.db.get(sql`
|
|
407
407
|
SELECT
|
|
408
408
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
409
409
|
COALESCE(SUM(child.output_tokens), 0) AS total_output,
|
|
@@ -412,7 +412,7 @@ Message: ${n.message}
|
|
|
412
412
|
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
413
413
|
WHERE child.thread_id = ${e}
|
|
414
414
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
415
|
-
`);
|
|
415
|
+
`);y&&(o+=y.total_input,i+=y.total_output,c+=y.total_cached,d+=y.total_cost);let v=S.db.get(sql`
|
|
416
416
|
WITH RECURSIVE
|
|
417
417
|
own_tasks(task_id) AS (
|
|
418
418
|
SELECT own.id
|
|
@@ -427,7 +427,7 @@ Message: ${n.message}
|
|
|
427
427
|
FROM descendants
|
|
428
428
|
JOIN tasks child INDEXED BY idx_tasks_parent_task_id
|
|
429
429
|
ON child.parent_task_id = descendants.task_id
|
|
430
|
-
WHERE descendants.depth < ${
|
|
430
|
+
WHERE descendants.depth < ${rr}
|
|
431
431
|
),
|
|
432
432
|
delegated_ids(task_id) AS (
|
|
433
433
|
SELECT DISTINCT descendants.task_id
|
|
@@ -446,20 +446,20 @@ Message: ${n.message}
|
|
|
446
446
|
COALESCE(SUM(task.cost_usd), 0) AS total_cost
|
|
447
447
|
FROM delegated_ids
|
|
448
448
|
JOIN tasks task ON task.id = delegated_ids.task_id
|
|
449
|
-
`);
|
|
449
|
+
`);v&&(u+=v.cnt,l+=v.total_input,p+=v.total_output,_+=v.total_cached,h+=v.total_cost);let I=S.db.all(sql`
|
|
450
450
|
SELECT DISTINCT child.agent_id FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
451
451
|
WHERE child.thread_id = ${e}
|
|
452
452
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
453
453
|
AND child.agent_id != 'workflow'
|
|
454
454
|
AND ${this.topLevelTaskPredicateSql()}
|
|
455
455
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
456
|
-
`);for(let
|
|
456
|
+
`);for(let N of I)m.add(N.agent_id);}catch(D){throw new f("DB_ERROR","Failed to aggregate task stats",D)}finally{S.close();}}return {taskCount:s,inputTokens:o,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(),s={},o=new Date().toISOString();for(let i of r){if(!existsSync(i))continue;let c=$(i);try{let d=sql`
|
|
457
457
|
SELECT own.id
|
|
458
458
|
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
459
459
|
WHERE own.thread_id = ${e}
|
|
460
460
|
${n?sql`AND own.workspace_id = ${n}`:sql``}
|
|
461
|
-
`,c
|
|
462
|
-
${this.descendantTraversalSql(d,sql`SELECT own.task_id FROM own_tasks own`,
|
|
461
|
+
`,u=c.db.all(sql`
|
|
462
|
+
${this.descendantTraversalSql(d,sql`SELECT own.task_id FROM own_tasks own`,rr)}
|
|
463
463
|
SELECT
|
|
464
464
|
descendant_ids.root_task_id AS root_task_id,
|
|
465
465
|
task.status AS status,
|
|
@@ -470,7 +470,7 @@ Message: ${n.message}
|
|
|
470
470
|
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
471
471
|
WHERE NOT ${this.descendantSkippedSql("task")}
|
|
472
472
|
GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
|
|
473
|
-
`);for(let l of
|
|
473
|
+
`);for(let l of u){let p=s[l.root_task_id]??=zo(o);Ko(p,xe(l),Ge(l),l.task_count);}}catch(d){throw new f("DB_ERROR","Failed to aggregate task descendant summaries",d)}finally{c.close();}}return s}listUnreadReplyCandidates(e,n){let r=new Map,s=new Map;for(let{threadId:i,readThroughAt:c}of e)c!==null&&s.set(i,c);if(s.size===0)return r;let o=new Set;for(let i of this.resolveDbPaths()){if(!existsSync(i))continue;let c=$(i);try{let d=c.db.all(this.unreadReplyCandidatesQuery(s,n));for(let u of d){if(o.has(u.id))continue;o.add(u.id);let l={id:u.id,threadId:u.thread_id,completedAt:u.completed_at,status:xe(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(([o,i])=>sql`(${o}, ${i})`),sql`, `),s=sql.join(jt.map(o=>sql`${o}`),sql`, `);return sql`
|
|
474
474
|
WITH watermarks(thread_id, read_through_at) AS (VALUES ${r})
|
|
475
475
|
SELECT child.id, child.thread_id, child.completed_at, child.status,
|
|
476
476
|
child.result, child.error, child.metadata
|
|
@@ -483,13 +483,13 @@ Message: ${n.message}
|
|
|
483
483
|
AND COALESCE(length(child.result), 0) > 0
|
|
484
484
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
485
485
|
ORDER BY julianday(child.completed_at), child.id
|
|
486
|
-
`}getThreadTaskStatusBatch(e,n){let r=[...new Set(e)];if(r.length===0)return {tasksByThread:new Map,descendantSummaryByTaskId:{}};let s=this.batchFetchTasks(r,n),o={},i=new Date().toISOString(),
|
|
486
|
+
`}getThreadTaskStatusBatch(e,n){let r=[...new Set(e)];if(r.length===0)return {tasksByThread:new Map,descendantSummaryByTaskId:{}};let s=this.batchFetchTasks(r,n),o={},i=new Date().toISOString(),c=sql.join(r.map(u=>sql`${u}`),sql`, `),d=sql`
|
|
487
487
|
SELECT own.id
|
|
488
488
|
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
489
|
-
WHERE own.thread_id IN (${
|
|
489
|
+
WHERE own.thread_id IN (${c})
|
|
490
490
|
${n?sql`AND own.workspace_id = ${n}`:sql``}
|
|
491
|
-
`;for(let
|
|
492
|
-
${this.descendantTraversalSql(d,sql`SELECT own.task_id FROM own_tasks own`,
|
|
491
|
+
`;for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let l=$(u);try{let p=l.db.all(sql`
|
|
492
|
+
${this.descendantTraversalSql(d,sql`SELECT own.task_id FROM own_tasks own`,rr)}
|
|
493
493
|
SELECT
|
|
494
494
|
descendant_ids.root_task_id AS root_task_id,
|
|
495
495
|
task.status AS status,
|
|
@@ -500,7 +500,7 @@ Message: ${n.message}
|
|
|
500
500
|
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
501
501
|
WHERE NOT ${this.descendantSkippedSql("task")}
|
|
502
502
|
GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
|
|
503
|
-
`);for(let
|
|
503
|
+
`);for(let _ of p){let h=o[_.root_task_id]??=zo(i);Ko(h,xe(_),Ge(_),_.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:s,descendantSummaryByTaskId:o}}listDescendantsByTaskId(e,n,r={}){let s=new Set(r.states??B_),o=$c(r.limit,Lc,Lc),i=$c(r.maxDepth,rr,rr),c=r.cursor?j_(r.cursor):void 0;for(let d of this.resolveDbPaths()){if(!existsSync(d))continue;let u=$(d);try{if(!u.db.get(sql`
|
|
504
504
|
SELECT anchor.id FROM tasks anchor
|
|
505
505
|
WHERE anchor.id = ${e} AND anchor.workspace_id = ${n}
|
|
506
506
|
`))continue;let p=sql`
|
|
@@ -511,7 +511,7 @@ Message: ${n.message}
|
|
|
511
511
|
WHERE anchor.id = ${e} AND anchor.workspace_id = ${n}
|
|
512
512
|
)
|
|
513
513
|
AND own.workspace_id = ${n}
|
|
514
|
-
`,
|
|
514
|
+
`,_=u.db.all(sql`
|
|
515
515
|
${this.descendantTraversalSql(p,sql`SELECT ${e}`,i)}
|
|
516
516
|
SELECT
|
|
517
517
|
task.id AS task_id,
|
|
@@ -534,11 +534,11 @@ Message: ${n.message}
|
|
|
534
534
|
FROM descendant_ids
|
|
535
535
|
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
536
536
|
LEFT JOIN tasks parent ON parent.id = task.parent_task_id
|
|
537
|
-
`),h=
|
|
537
|
+
`),h=zo(new Date().toISOString()),m=!1,E=[];for(let N of _){if(N.has_deeper&&(m=!0),N.skipped)continue;let R=xe(N);Ko(h,R,Ge(N),1),s.has(R)&&E.push({row:N,key:[W_(R),N.started_at?N.started_at:null,N.task_id]});}E.sort((N,R)=>Mc(N.key,R.key));let S=c?E.filter(N=>Mc(N.key,c)>0):E,D=S.slice(0,o),y=S.length>D.length?G_(D[D.length-1].key):null,v=new Map;if(D.length>0){let N=u.db.select(ne).from(a).where(inArray(a.id,D.map(R=>R.row.task_id))).all();for(let R of N)v.set(R.id,nr(R));}let I=[];for(let{row:N}of D){let R=v.get(N.task_id);!R||!N.parent_task_id||I.push({task:R,parentTaskId:N.parent_task_id,parentAgentId:N.parent_agent_id,depth:N.depth});}return {rows:I,summary:h,nextCursor:y,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 s=$(r);try{let o=s.db.all(sql`
|
|
538
538
|
SELECT task_id, input FROM task_provider_inputs
|
|
539
539
|
WHERE run_epoch = 0
|
|
540
540
|
AND task_id IN (${sql.join(e.map(i=>sql`${i}`),sql`, `)})
|
|
541
|
-
`);for(let i of o)n.set(i.task_id,i.input);}catch{}finally{s.close();}}return n}findTopLevelTasks(e,n,r,s){let o=this.resolveDbPaths(),i=s?sql`(${this.topLevelTaskPredicateSql()} OR child.agent_id = ${s})`:this.topLevelTaskPredicateSql(),
|
|
541
|
+
`);for(let i of o)n.set(i.task_id,i.input);}catch{}finally{s.close();}}return n}findTopLevelTasks(e,n,r,s){let o=this.resolveDbPaths(),i=s?sql`(${this.topLevelTaskPredicateSql()} OR child.agent_id = ${s})`:this.topLevelTaskPredicateSql(),c=new Set,d=[];for(let u of o){if(!existsSync(u))continue;let l=$(u);try{let p;r!==void 0?p=l.db.all(sql`
|
|
542
542
|
SELECT * FROM (
|
|
543
543
|
SELECT child.*,
|
|
544
544
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -555,7 +555,7 @@ Message: ${n.message}
|
|
|
555
555
|
AND ${i}
|
|
556
556
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
557
557
|
ORDER BY child.started_at ASC
|
|
558
|
-
`);for(let
|
|
558
|
+
`);for(let _ of p)c.has(_.id)||(c.add(_.id),d.push(nr(_)));}catch(p){throw new f("DB_ERROR","Failed to find top-level tasks",p)}finally{l.close();}}if(r!==void 0&&o.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(),s=new Set,o=[];for(let i of r){if(!existsSync(i))continue;let c=$(i);try{let d=eq(a.thread_id,e),u=n?and(d,eq(a.workspace_id,n)):d,l=c.db.select(ne).from(a).where(u).orderBy(asc(a.started_at)).all();for(let p of l)s.has(p.id)||(s.add(p.id),o.push(nr(p)));}catch(d){throw new f("DB_ERROR","Failed to find all tasks for thread",d)}finally{c.close();}}return o}findRespondedAgents(e,n){let r=this.resolveDbPaths(),s=new Map;for(let o of r){if(!existsSync(o))continue;let i=$(o,{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=s.get(u.agentId);u.lastRepliedAt&&(!l||u.lastRepliedAt>l)&&s.set(u.agentId,u.lastRepliedAt);}}catch(c){throw new f("DB_ERROR","Failed to find responded agents for thread",c)}finally{i.close();}}return [...s.entries()].map(([o,i])=>({agentId:o,lastRepliedAt:i})).sort((o,i)=>(o.lastRepliedAt===i.lastRepliedAt?0:o.lastRepliedAt>i.lastRepliedAt?-1:1)||(o.agentId===i.agentId?0:o.agentId<i.agentId?-1:1))}findTaskById(e,n,r){let s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=$(o);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(ne).from(a).where(d).limit(1).get();if(!u)continue;let l=i.db.select(ne).from(a).where(eq(a.parent_task_id,u.id)).orderBy(asc(a.started_at)).all().map(nr);return {task:nr(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`
|
|
559
559
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
560
560
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
561
561
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -565,7 +565,7 @@ Message: ${n.message}
|
|
|
565
565
|
AND ${this.topLevelTaskPredicateSql()}
|
|
566
566
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
567
567
|
ORDER BY child.started_at ASC
|
|
568
|
-
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=$(o);try{let
|
|
568
|
+
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=$(o);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(q_(d));}}catch(c){throw new f("DB_ERROR","Failed to batch fetch tasks",c)}finally{i.close();}}return r}findThreadOriginsQuery(e,n){return sql`
|
|
569
569
|
WITH root AS (
|
|
570
570
|
SELECT child.thread_id, child.id, child.caller_agent_id, child.parent_task_id,
|
|
571
571
|
CASE
|
|
@@ -617,7 +617,7 @@ Message: ${n.message}
|
|
|
617
617
|
FROM tasks AS child
|
|
618
618
|
LEFT JOIN tasks AS parent ON parent.id = child.parent_task_id
|
|
619
619
|
WHERE child.id IN (${sql.join(e.map(n=>sql`${n}`),sql`, `)})
|
|
620
|
-
`}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=$(o);try{for(let
|
|
620
|
+
`}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=$(o);try{for(let c=0;c<e.length;c+=os){let d=e.slice(c,c+os),l=i.db.all(this.findCreatorPointersQuery(d,n)).filter(y=>!r.has(y.thread_id)),p=l.filter(y=>y.creator_task_id!==null&&y.creator_pointer_unverified===0&&y.creator_actor_kind===null).map(y=>y.creator_task_id),_=p.length>0?i.db.all(this.findTaskOriginLineageQuery(p)):[],h=new Map(_.map(y=>[y.task_id,y])),m=new Map(l.map(y=>[y.thread_id,y])),E=d.filter(y=>{if(r.has(y))return !1;let v=m.get(y);return v?!(v.creator_task_id!==null&&v.creator_pointer_unverified===0)&&v.created_by_kind===null:!0}),S=E.length>0?i.db.all(this.findThreadOriginsQuery(E,n)):[],D=new Map(S.map(y=>[y.thread_id,y]));for(let y of l){if(r.has(y.thread_id))continue;let v=Dc(y,y.created_by_task_id!==null?h.get(y.created_by_task_id):void 0,D.get(y.thread_id));v&&r.set(y.thread_id,v);}for(let y of S)r.has(y.thread_id)||m.has(y.thread_id)||r.set(y.thread_id,rs(y));}}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"),s=this.findThreadOrigins(r,n),o=r.filter(c=>Uc(s.get(c),e));return this.readThreadRowsByIds(o,n,"Failed to find threads by origin").sort(Fc)}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(Fc),s=[],o=new Map;for(let u=0;u<r.length;u+=Hc){let l=r.slice(u,u+Hc),p=this.findThreadOrigins(l.map(_=>_.id),e);for(let[_,h]of p)o.set(_,h);for(let _ of l)if(Uc(p.get(_.id),"direct")&&(s.push(_.id),s.length===n))break;if(s.length===n)break}let i=new Map;if(s.length>0){let u=this.readThreadRowsByIds(s,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 s){let l=i.get(u);if(!l)continue;c.push(l);let p=o.get(u);p&&d.set(u,p);}return {threads:c,originsByThread:d}}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let o=$(s);try{return o.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(c=>c.detail)}finally{o.close();}}return []}explainFindThreadOriginsPlan(e,n){if(e.length===0)return [];let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let o=$(s);try{let i=o.db.all(sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery(e,n)}`),c=o.db.all(sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery(e)}`),d=o.db.all(sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery(e,n)}`);return [...i,...c,...d].map(u=>u.detail)}finally{o.close();}}return []}explainFindThreadsByOriginPlan(e,n){let r=`__thread_origin_${e}_plan__`,s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=$(o);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 s=this.openHandle(true);try{let o=eq(k.id,e),i=r?and(o,eq(k.workspace_id,r)):o;if(!s.db.select({id:k.id}).from(k).where(i).limit(1).get())return;s.db.update(k).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(eq(k.id,e)).run();}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to update thread title",o)}finally{s.close();}}upsertThread(e,n){let r=this.openHandle(true);try{r.db.transaction(s=>{let i=(n.workspaceId?s.select({id:te.id}).from(te).where(eq(te.id,n.workspaceId)).limit(1).get():void 0)?n.workspaceId:null,c=new Date().toISOString(),d=s.select({id:k.id,message_count:k.message_count,created_by_task_id:k.created_by_task_id}).from(k).where(eq(k.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&&!qc(s,e,n.createdByTaskId)&&(u.created_by_task_id=n.createdByTaskId),s.update(k).set(u).where(eq(k.id,e)).run();}else s.insert(k).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(s){throw s instanceof f?s:new f("DB_ERROR","Failed to upsert thread",s)}finally{r.close();}}ensureThread(e,n,r,s){let o=this.openHandle(true);try{o.db.transaction(i=>{let d=(r?i.select({id:te.id}).from(te).where(eq(te.id,r)).limit(1).get():void 0)?r:null,u=i.select({id:k.id,platform:k.platform,workspace_id:k.workspace_id,message_count:k.message_count,created_by_task_id:k.created_by_task_id}).from(k).where(eq(k.id,e)).limit(1).get();if(u){let p={};d&&!u.workspace_id&&(p.workspace_id=d),u.created_by_task_id===null&&s?.createdByTaskId!=null&&u.message_count===0&&!qc(i,e,s.createdByTaskId)&&(p.created_by_task_id=s.createdByTaskId),Object.keys(p).length>0&&i.update(k).set(p).where(eq(k.id,e)).run();return}let l=new Date().toISOString();i.insert(k).values({id:e,platform:n,workspace_id:d,created_by_kind:null,created_by_id:null,created_by_task_id:s?.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{o.close();}}saveUserMessage(e,n,r){if(!this.dbExists())return {firstMessage:false};let s=this.openHandle(true);try{let o=new Date().toISOString();return {firstMessage:s.db.transaction(c=>{let u=c.select({message_count:k.message_count}).from(k).where(eq(k.id,e)).limit(1).get()?.message_count===0;return c.run(sql`
|
|
621
621
|
UPDATE threads
|
|
622
622
|
SET first_message = COALESCE(first_message, ${n}),
|
|
623
623
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
@@ -625,11 +625,11 @@ Message: ${n.message}
|
|
|
625
625
|
message_count = message_count + 1,
|
|
626
626
|
updated_at = ${o}
|
|
627
627
|
WHERE id = ${e}
|
|
628
|
-
`),c},{behavior:"immediate"})}}catch(o){throw o instanceof f?o:new f("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(k).set({last_message:n,updated_at:o}).where(eq(k.id,e)).run();}catch(o){throw o instanceof f?o:new f("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(k).set(s).where(eq(k.id,e)).run();}catch(s){throw s instanceof f?s:new f("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 pn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(s).some(d=>d!=="priority"&&d!=="state"))return new pn("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 pn("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 pn("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(k.id,e),eq(k.workspace_id,r)):eq(k.id,e);return u.db.transaction(c=>{let l=c.select({metadata:k.metadata}).from(k).where(d).get();if(!l)return null;let p=fn(l.metadata),g=p.threadTitle,h=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};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,E=new Date().toISOString();c.update(k).set({metadata:m,updated_at:E}).where(d).run();let S=c.select({metadata:k.metadata}).from(k).where(d).get();if(!S)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let P=Cg(S.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{u.close();}}togglePin(e,n){let r=this.openHandle(true);try{return r.db.transaction(s=>Pg(s,e,n),{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to toggle pin",s)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(s=>Dg(s,e,n),{behavior:"immediate"});}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to reorder pins",s)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let s=n?and(eq(k.id,e),eq(k.workspace_id,n)):eq(k.id,e),o=r.db.select({starred:k.starred}).from(k).where(s).get();if(!o)return null;let i=o.starred?0:1;return r.db.update(k).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof f?s:new f("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(k.id,e),eq(k.workspace_id,n)):eq(k.id,e);return i.db.transaction(c=>{let l=c.select({metadata:k.metadata}).from(k).where(u).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},g=p.overdrive??{},h=s?.defaultTurns??g.defaultTurns??3,m=s?.updatedBy??"ui",E=new Date().toISOString(),S,P,w,x;switch(r){case "enable-count":{let I=s?.turns??h,b=s?.consumeCurrent?Math.max(I-1,0):I;S=b>0?"count":"off",P=b,w=!0,x="count";break}case "enable-latch":{S="latch",P=0,w=!0,x="latch";break}case "disable":{S="off",P=0,w=!1;break}default:{let I=g.state??"off",b=typeof g.remaining=="number"?g.remaining:0;if(I==="count"&&b>0){let R=b-1;R<=0?(S="off",P=0):(S="count",P=R),w=!0,x="count";}else I==="latch"?(S="latch",P=0,w=!0,x="latch"):(S="off",P=0,w=!1);break}}return p.overdrive={state:S,remaining:P,defaultTurns:h,updatedAt:E,updatedBy:m},c.update(k).set({metadata:JSON.stringify(p),updated_at:E}).where(u).run(),{applied:w,appliedMode:x,state:S,remaining:P}},{behavior:"immediate"})}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to resolve overdrive",u)}finally{i.close();}}};_();ut();Rt();St();dt();_();var qo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Lg(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+=qo[s%62]);}for(;n.length<t;)n+=qo[randomBytes(1)[0]%62];return n}function Yn(t){return `${t}_${Lg(8)}`}function Pu(t,e){let{createHash:n}=qt("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+=qo[i%62];return `${t}_${o}`}vt();_();var Mg=["urgent","high","medium","low"],$g=["investigating","in-progress","in-review","on-hold","done"],Du="custom:";var Hg=new Set(Mg),Ug=new Set($g);function Bo(t){return typeof t=="string"&&Hg.has(t)}function Wo(t){if(typeof t!="string")return false;if(Ug.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Du))return false;let e=t.slice(Du.length);return e.length>=1&&e.length<=20}function Lu(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 Go(t){let e=Lu(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,s={};return Bo(r.priority)&&(s.priority=r.priority),Wo(r.state)&&(s.state=r.state),s}function Mu(t,e){let n=Lu(t)??{},r={...Go(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)}Hn();var Gg="regeneration_replaced";var jg="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var zg="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Ko=class extends f{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;}},sr=class extends Ko{},Jo=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;}},Kg=new Set(Yi),Jg=new Set(Xi),Vg=new Set(Qi),Xg=new Set(Zi),Yg=50,Hu=100,Uu=280,Fu=40,Qg=new Set(ea),es=["queued","running"];function zo(t){return Qg.has(t)}function z(t){throw new f("VALIDATION",t)}function ze(t){throw new f("NOT_FOUND",t)}function H(t,e){(typeof t!="string"||t.trim().length===0)&&z(`${e} is required`);}function Zn(t={}){let e=t.actor??t,n=e.actorType??"system";return Kg.has(n)||z(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&z("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Zg(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)&&z("title must not be empty"),t.title.length>120&&z("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!Bo(t.priority)&&z(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Wo(t.state)&&z(`invalid state: ${String(t.state)}`);}function e_(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&z("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)&&z(`${n} must be a non-negative integer`);let e=t.limit??Yg;return (!Number.isInteger(e)||e<1||e>Hu)&&z(`limit must be between 1 and ${Hu}`),e}function Vo(t){typeof t!="string"&&z("text is required");let e=t.trim();return e.length===0&&z("text must not be empty"),e.length>Uu&&z(`text must be at most ${Uu} characters`),e}function it(t,e){return H(t??"",e),t}function Xo(t){Xg.has(t)||z(`invalid highlight kind: ${String(t)}`);}function t_(t){Vg.has(t)||z(`invalid highlight source: ${String(t)}`);}function n_(t){H(t.threadId,"threadId"),H(t.workspaceId,"workspaceId");let e=t.source??"manual";t_(e),Xo(t.kind);let n=Vo(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=it(l,"taskId");return (r!==p||s!==p)&&z("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=it(r,"coversFromTaskId"),i=it(s,"coversToTaskId"),u=t.sourceTaskId??o,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return it(u??void 0,"sourceTaskId"),it(d??void 0,"detectorVersion"),it(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 r_(t,e){(!t||typeof t!="object")&&z(`candidates[${e}] is required`),Xo(t.kind);let n=Vo(t.text),r=it(t.anchorTaskId,`candidates[${e}].anchorTaskId`),s=it(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),o=it(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Pu("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 s_(t){Array.isArray(t)||z("candidates must be an array"),t.length>Fu&&z(`candidates must contain at most ${Fu} items`);let e=new Map;for(let[n,r]of t.entries()){let s=r_(r,n);e.set(s.contentFingerprint,s);}return [...e.values()]}function rr(t){let e=Go(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 o_(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&z("event payload must be a JSON object"),e}catch(e){throw new f("VALIDATION","event payload must be JSON serializable",e)}}function er(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${j.seq}), 0)`}).from(j).where(eq(j.thread_id,e)).get()?.maxSeq??0}function tr(t,e){return !!t.select({id:j.id}).from(j).where(eq(j.thread_id,e)).limit(1).get()}function Ft(t,e){Jg.has(e.type)||z(`invalid thread event type: ${String(e.type)}`);let n=Yn("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:o_(e.payload),created_at:e.createdAt}).run();let r=t.select().from(j).where(eq(j.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function nr(t,e,n,r,s){let o=rr(e);Ft(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 ns(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 ts(t,e,n,r,s,o,i){let u=s==="thread.highlight.created"?ns(e):{before:i?ns({...e,...i,id:e.id}):void 0,after:ns(e)};return Ft(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 i_(t,e,n,r,s,o){return Ft(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:ns(e),...o??{}}})}var rs=class extends Te{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 s=dirname(n);existsSync(s)||mkdirSync(s,{recursive:true});}let r=$(n);if(e)try{xe(r.db,n);}catch(s){throw r.close(),s}return r}findThread(e,n,r){let s=eq(k.id,n),o=r===void 0?s:r===null?and(s,isNull(k.workspace_id)):and(s,eq(k.workspace_id,r));return e.select().from(k).where(o).limit(1).get()}findRegenerationRun(e,n,r){let s=e.select().from(q).where(eq(q.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:k.workspace_id}).from(k).where(eq(k.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(H(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let s=this.findThread(r.db,e,n);return s?rr(s):null}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read thread snapshot",s)}finally{r.close();}}updateSnapshot(e){Zg(e);let n=Zn(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||ze(`Thread ${e.threadId} not found`);let u=rr(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,g=e.state!==void 0&&e.state!==u.state,h=c||p||g;if(!h&&!l)return u;let m=i.metadata;(p||g)&&(m=Mu(i.metadata,{priority:e.priority,state:e.state}));let E={};if(h&&(E.metadata=m,E.updated_at=r),c&&(E.title=e.title),d&&(E.title_locked=1),o.update(k).set(E).where(e.workspaceId===void 0?eq(k.id,e.threadId):e.workspaceId===null?and(eq(k.id,e.threadId),isNull(k.workspace_id)):and(eq(k.id,e.threadId),eq(k.workspace_id,e.workspaceId))).run(),!h){let w={...i,title_locked:1};return rr(w)}let S=er(o,i.id)+1;tr(o,i.id)||(nr(o,i,n,r,S),S+=1),c&&(Ft(o,{threadId:i.id,seq:S,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.title,after:e.title}}),S+=1),p&&(Ft(o,{threadId:i.id,seq:S,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.priority,after:e.priority}}),S+=1),g&&Ft(o,{threadId:i.id,seq:S,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.state,after:e.state}});let P={...i,title:c?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return rr(P)},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("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 f?s:new f("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,[...Ut]),or(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 f?s:new f("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||ze(`Thread ${e.threadId} not found`);let i=s.select().from(q).where(and(eq(q.thread_id,o.id),eq(q.request_id,e.requestId))).orderBy(desc(q.requested_at),desc(q.id)).limit(1).get();if(i)return {run:i,created:!1};let u=s.select().from(q).where(and(eq(q.thread_id,o.id),inArray(q.status,es))).orderBy(asc(q.requested_at),asc(q.id)).limit(1).get();if(u)throw new Jo(u);let d=e.runId??Yn("thr");s.insert(q).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(q).where(eq(q.id,d)).get();if(!c)throw new f("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("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 f?s:new f("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(q).where(and(eq(q.thread_id,e),eq(q.request_id,r))).orderBy(desc(q.requested_at),desc(q.id)).limit(1).get()??null:null}catch(o){throw o instanceof f?o:new f("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||ze(`Highlight regeneration run ${e} not found`),zo(i.status)||z(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;o.update(q).set({status:"running",started_at:r}).where(and(eq(q.id,i.id),eq(q.status,"queued"))).run();let u=o.select().from(q).where(eq(q.id,i.id)).get();if(!u)throw new f("DB_ERROR","Highlight regeneration run start did not return a row");return u},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("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||ze(`Highlight regeneration run ${e.runId} not found`),zo(o.status)||z(`invalid highlight regeneration status: ${o.status}`),o.status==="completed"||o.status==="failed")return o;s.update(q).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(q.id,o.id),inArray(q.status,es))).run();let i=s.select().from(q).where(eq(q.id,o.id)).get();if(!i)throw new f("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to fail highlight regeneration run",s)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=jg){H(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>s.update(q).set({status:"failed",completed_at:n,error_code:e}).where(inArray(q.status,es)).run().changes,{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("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=s_(e.candidates),r=Zn(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)&&ze(`Highlight regeneration run ${e.runId} not found`),zo(u.status)||z(`invalid highlight regeneration status: ${u.status}`),u.status==="failed")throw new f("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||ze(`Thread ${e.threadId} not found`),u.detector_version!==e.detectorVersion&&z("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(R=>R.contentFingerprint)),p=c.filter(R=>R.source==="auto"&&R.status==="active"&&R.revision===0&&!l.has(R.content_fingerprint??"")),g=c.filter(R=>R.source==="auto"&&R.status==="active").length,h=new Set(c.filter(R=>!p.includes(R)&&R.content_fingerprint).map(R=>R.content_fingerprint)),m=n.filter(R=>!h.has(R.contentFingerprint)),E=new Date().toISOString(),S=er(i,d.id)+1;tr(i,d.id)||(nr(i,d,r,E,S),S+=1);for(let R of p)i.delete(U).where(eq(U.id,R.id)).run(),i_(i,R,r,E,S,{runId:e.runId,reason:Gg}),S+=1;let P=0,w=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let R of m){let B=Yn("thl");i.insert(U).values({id:B,thread_id:d.id,source:"auto",kind:R.kind,status:"active",text:R.text,covers_from_task_id:R.coversFromTaskId,covers_to_task_id:R.coversToTaskId,revision:0,created_at:E,updated_at:E,agent_id:w,source_task_id:R.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:R.contentFingerprint,dismissed_at:null}).run();let ke=i.select().from(U).where(eq(U.id,B)).get();if(!ke)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");ts(i,ke,r,E,"thread.highlight.created",S),S+=1,P+=1;}let I=i.select().from(U).where(eq(U.thread_id,d.id)).all().filter(R=>R.source==="auto"&&R.status==="active").length;Ft(i,{threadId:d.id,seq:S,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:E,payload:{runId:u.id,detectorVersion:e.detectorVersion,previousAutoCount:g,newAutoCount:I,deletedCount:p.length,createdCount:P}}),i.update(q).set({status:"completed",started_at:u.started_at??E,completed_at:E,error_code:null,previous_auto_count:g,new_auto_count:I}).where(and(eq(q.id,u.id),inArray(q.status,es))).run();let b=i.select().from(q).where(eq(q.id,u.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:g,newAutoCount:I}},{behavior:"immediate"})}catch(i){if(o)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:zg});}catch{}throw i instanceof f?i:new f("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=e_(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,g=l[0];return g&&(p=!!i.db.select({id:j.id}).from(j).where(and(eq(j.thread_id,s.threadId),lt(j.seq,g.seq))).limit(1).get()),{items:l,latestSeq:u,hasMoreOlder:p}}catch(u){throw u instanceof f?u:new f("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=n_(e),r=Zn(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||ze(`Thread ${e.threadId} not found`),n.source==="auto"){let g=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(g)return g}let d=e.id??Yn("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 f("DB_ERROR","Highlight insert did not return a row");let p=er(i,u.id)+1;return tr(i,u.id)||(nr(i,u,r,s,p),p+=1),ts(i,l,r,s,"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{o.close();}}updateHighlight(e){H(e.threadId,"threadId"),H(e.workspaceId,"workspaceId"),H(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&z("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&z("highlight update requires at least one field"),e.kind!==void 0&&Xo(e.kind);let n=e.text===void 0?void 0:Vo(e.text),r=Zn(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||ze(`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||ze(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new sr(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new sr(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,g=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||g.length===0)&&z("highlight projection is incomplete");let h=c!==d.kind||l!==d.text||p!==d.covers_from_task_id||g!==d.covers_to_task_id,m=r.actorType==="user"&&d.source==="auto"&&h?"manual":d.source;if(!(h||m!==d.source))return d;let S=d.revision+1;i.update(U).set({source:m,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:g,revision:S,updated_at:s}).where(and(eq(U.id,d.id),eq(U.revision,d.revision))).run();let P=i.select().from(U).where(eq(U.id,d.id)).get();if(!P)throw new f("DB_ERROR","Highlight update did not return a row");let w=er(i,u.id)+1;return tr(i,u.id)||(nr(i,u,r,s,w),w+=1),ts(i,P,r,s,"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{o.close();}}dismissHighlight(e){H(e.threadId,"threadId"),H(e.workspaceId,"workspaceId"),H(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&z("expectedRevision must be a non-negative integer");let n=Zn(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||ze(`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||ze(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new sr(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 f("DB_ERROR","Highlight dismissal did not return a row");let l=er(o,i.id)+1;return tr(o,i.id)||(nr(o,i,n,r,l),l+=1),ts(o,c,n,r,"thread.highlight.deleted",l,u),c},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("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`
|
|
628
|
+
`),u},{behavior:"immediate"})}}catch(o){throw o instanceof f?o:new f("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(k).set({last_message:n,updated_at:o}).where(eq(k.id,e)).run();}catch(o){throw o instanceof f?o:new f("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(k).set(s).where(eq(k.id,e)).run();}catch(s){throw s instanceof f?s:new f("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 Tn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(s).some(d=>d!=="priority"&&d!=="state"))return new Tn("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 Tn("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 Tn("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(k.id,e),eq(k.workspace_id,r)):eq(k.id,e);return c.db.transaction(u=>{let l=u.select({metadata:k.metadata}).from(k).where(d).get();if(!l)return null;let p=yn(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,E=new Date().toISOString();u.update(k).set({metadata:m,updated_at:E}).where(d).run();let S=u.select({metadata:k.metadata}).from(k).where(d).get();if(!S)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let D=K_(S.metadata);return {threadId:e,priority:D.priority,state:D.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(s=>J_(s,e,n),{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to toggle pin",s)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(s=>V_(s,e,n),{behavior:"immediate"});}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to reorder pins",s)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let s=n?and(eq(k.id,e),eq(k.workspace_id,n)):eq(k.id,e),o=r.db.select({starred:k.starred}).from(k).where(s).get();if(!o)return null;let i=o.starred?0:1;return r.db.update(k).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to toggle star",s)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,s){let i=this.openHandle(true);try{let c=n?and(eq(k.id,e),eq(k.workspace_id,n)):eq(k.id,e);return i.db.transaction(u=>{let l=u.select({metadata:k.metadata}).from(k).where(c).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},_=p.overdrive??{},h=s?.defaultTurns??_.defaultTurns??3,m=s?.updatedBy??"ui",E=new Date().toISOString(),S,D,y,v;switch(r){case "enable-count":{let I=s?.turns??h,N=s?.consumeCurrent?Math.max(I-1,0):I;S=N>0?"count":"off",D=N,y=!0,v="count";break}case "enable-latch":{S="latch",D=0,y=!0,v="latch";break}case "disable":{S="off",D=0,y=!1;break}default:{let I=_.state??"off",N=typeof _.remaining=="number"?_.remaining:0;if(I==="count"&&N>0){let R=N-1;R<=0?(S="off",D=0):(S="count",D=R),y=!0,v="count";}else I==="latch"?(S="latch",D=0,y=!0,v="latch"):(S="off",D=0,y=!1);break}}return p.overdrive={state:S,remaining:D,defaultTurns:h,updatedAt:E,updatedBy:m},u.update(k).set({metadata:JSON.stringify(p),updated_at:E}).where(c).run(),{applied:y,appliedMode:v,state:S,remaining:D}},{behavior:"immediate"})}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to resolve overdrive",c)}finally{i.close();}}};g();ft();Ot();Nt();pt();g();var Jo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function X_(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+=Jo[s%62]);}for(;n.length<t;)n+=Jo[randomBytes(1)[0]%62];return n}function sr(t){return `${t}_${X_(8)}`}function Wc(t,e){let{createHash:n}=Kt("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+=Jo[i%62];return `${t}_${o}`}$t();g();var Y_=["urgent","high","medium","low"],Q_=["investigating","in-progress","in-review","on-hold","done"],Gc="custom:";var Z_=new Set(Y_),eg=new Set(Q_);function Vo(t){return typeof t=="string"&&Z_.has(t)}function Xo(t){if(typeof t!="string")return false;if(eg.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Gc))return false;let e=t.slice(Gc.length);return e.length>=1&&e.length<=20}function jc(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 Yo(t){let e=jc(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,s={};return Vo(r.priority)&&(s.priority=r.priority),Xo(r.state)&&(s.state=r.state),s}function zc(t,e){let n=jc(t)??{},r={...Yo(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)}jn();var og="regeneration_replaced";var ig="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var ag="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",ei=class extends f{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;}},lr=class extends ei{},ti=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;}},dg=new Set(sa),cg=new Set(ra),ug=new Set(oa),lg=new Set(ia),pg=50,Jc=100,Vc=280,Xc=40,fg=new Set(aa),as=["queued","running"];function Zo(t){return fg.has(t)}function z(t){throw new f("VALIDATION",t)}function Xe(t){throw new f("NOT_FOUND",t)}function H(t,e){(typeof t!="string"||t.trim().length===0)&&z(`${e} is required`);}function ir(t={}){let e=t.actor??t,n=e.actorType??"system";return dg.has(n)||z(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&z("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function _g(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)&&z("title must not be empty"),t.title.length>120&&z("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!Vo(t.priority)&&z(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Xo(t.state)&&z(`invalid state: ${String(t.state)}`);}function gg(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&z("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)&&z(`${n} must be a non-negative integer`);let e=t.limit??pg;return (!Number.isInteger(e)||e<1||e>Jc)&&z(`limit must be between 1 and ${Jc}`),e}function ni(t){typeof t!="string"&&z("text is required");let e=t.trim();return e.length===0&&z("text must not be empty"),e.length>Vc&&z(`text must be at most ${Vc} characters`),e}function ut(t,e){return H(t??"",e),t}function ri(t){lg.has(t)||z(`invalid highlight kind: ${String(t)}`);}function hg(t){ug.has(t)||z(`invalid highlight source: ${String(t)}`);}function mg(t){H(t.threadId,"threadId"),H(t.workspaceId,"workspaceId");let e=t.source??"manual";hg(e),ri(t.kind);let n=ni(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=ut(l,"taskId");return (r!==p||s!==p)&&z("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=ut(r,"coversFromTaskId"),i=ut(s,"coversToTaskId"),c=t.sourceTaskId??o,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),u=t.contentFingerprint??t.idempotencyKey??null;return ut(c??void 0,"sourceTaskId"),ut(d??void 0,"detectorVersion"),ut(u??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:o,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:c,detectorVersion:d,contentFingerprint:u}}function kg(t,e){(!t||typeof t!="object")&&z(`candidates[${e}] is required`),ri(t.kind);let n=ni(t.text),r=ut(t.anchorTaskId,`candidates[${e}].anchorTaskId`),s=ut(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),o=ut(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Wc("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 Tg(t){Array.isArray(t)||z("candidates must be an array"),t.length>Xc&&z(`candidates must contain at most ${Xc} items`);let e=new Map;for(let[n,r]of t.entries()){let s=kg(r,n);e.set(s.contentFingerprint,s);}return [...e.values()]}function ur(t){let e=Yo(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 yg(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&z("event payload must be a JSON object"),e}catch(e){throw new f("VALIDATION","event payload must be JSON serializable",e)}}function ar(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${j.seq}), 0)`}).from(j).where(eq(j.thread_id,e)).get()?.maxSeq??0}function dr(t,e){return !!t.select({id:j.id}).from(j).where(eq(j.thread_id,e)).limit(1).get()}function zt(t,e){cg.has(e.type)||z(`invalid thread event type: ${String(e.type)}`);let n=sr("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:yg(e.payload),created_at:e.createdAt}).run();let r=t.select().from(j).where(eq(j.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function cr(t,e,n,r,s){let o=ur(e);zt(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 cs(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 ds(t,e,n,r,s,o,i){let c=s==="thread.highlight.created"?cs(e):{before:i?cs({...e,...i,id:e.id}):void 0,after:cs(e)};return zt(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:c})}function wg(t,e,n,r,s,o){return zt(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:cs(e),...o??{}}})}var us=class extends Ee{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 s=dirname(n);existsSync(s)||mkdirSync(s,{recursive:true});}let r=$(n);if(e)try{De(r.db,n);}catch(s){throw r.close(),s}return r}findThread(e,n,r){let s=eq(k.id,n),o=r===void 0?s:r===null?and(s,isNull(k.workspace_id)):and(s,eq(k.workspace_id,r));return e.select().from(k).where(o).limit(1).get()}findRegenerationRun(e,n,r){let s=e.select().from(q).where(eq(q.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:k.workspace_id}).from(k).where(eq(k.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(H(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let s=this.findThread(r.db,e,n);return s?ur(s):null}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read thread snapshot",s)}finally{r.close();}}updateSnapshot(e){_g(e);let n=ir(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||Xe(`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=zc(i.metadata,{priority:e.priority,state:e.state}));let E={};if(h&&(E.metadata=m,E.updated_at=r),u&&(E.title=e.title),d&&(E.title_locked=1),o.update(k).set(E).where(e.workspaceId===void 0?eq(k.id,e.threadId):e.workspaceId===null?and(eq(k.id,e.threadId),isNull(k.workspace_id)):and(eq(k.id,e.threadId),eq(k.workspace_id,e.workspaceId))).run(),!h){let y={...i,title_locked:1};return ur(y)}let S=ar(o,i.id)+1;dr(o,i.id)||(cr(o,i,n,r,S),S+=1),u&&(zt(o,{threadId:i.id,seq:S,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.title,after:e.title}}),S+=1),p&&(zt(o,{threadId:i.id,seq:S,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.priority,after:e.priority}}),S+=1),_&&zt(o,{threadId:i.id,seq:S,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.state,after:e.state}});let D={...i,title:u?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return ur(D)},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("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 f?s:new f("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,[...jt]),or(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 f?s:new f("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||Xe(`Thread ${e.threadId} not found`);let i=s.select().from(q).where(and(eq(q.thread_id,o.id),eq(q.request_id,e.requestId))).orderBy(desc(q.requested_at),desc(q.id)).limit(1).get();if(i)return {run:i,created:!1};let c=s.select().from(q).where(and(eq(q.thread_id,o.id),inArray(q.status,as))).orderBy(asc(q.requested_at),asc(q.id)).limit(1).get();if(c)throw new ti(c);let d=e.runId??sr("thr");s.insert(q).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 u=s.select().from(q).where(eq(q.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(s){throw s instanceof f?s:new f("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 f?s:new f("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(q).where(and(eq(q.thread_id,e),eq(q.request_id,r))).orderBy(desc(q.requested_at),desc(q.id)).limit(1).get()??null:null}catch(o){throw o instanceof f?o:new f("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||Xe(`Highlight regeneration run ${e} not found`),Zo(i.status)||z(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;o.update(q).set({status:"running",started_at:r}).where(and(eq(q.id,i.id),eq(q.status,"queued"))).run();let c=o.select().from(q).where(eq(q.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(o){throw o instanceof f?o:new f("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||Xe(`Highlight regeneration run ${e.runId} not found`),Zo(o.status)||z(`invalid highlight regeneration status: ${o.status}`),o.status==="completed"||o.status==="failed")return o;s.update(q).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(q.id,o.id),inArray(q.status,as))).run();let i=s.select().from(q).where(eq(q.id,o.id)).get();if(!i)throw new f("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to fail highlight regeneration run",s)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=ig){H(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>s.update(q).set({status:"failed",completed_at:n,error_code:e}).where(inArray(q.status,as)).run().changes,{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("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=Tg(e.candidates),r=ir(e),s=this.openHandle(true),o=false;try{return s.db.transaction(i=>{let c=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!c||c.thread_id!==e.threadId)&&Xe(`Highlight regeneration run ${e.runId} not found`),Zo(c.status)||z(`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};o=!0;let d=this.findThread(i,e.threadId,e.workspaceId);d||Xe(`Thread ${e.threadId} not found`),c.detector_version!==e.detectorVersion&&z("detectorVersion does not match the regeneration run");let u=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(R=>R.contentFingerprint)),p=u.filter(R=>R.source==="auto"&&R.status==="active"&&R.revision===0&&!l.has(R.content_fingerprint??"")),_=u.filter(R=>R.source==="auto"&&R.status==="active").length,h=new Set(u.filter(R=>!p.includes(R)&&R.content_fingerprint).map(R=>R.content_fingerprint)),m=n.filter(R=>!h.has(R.contentFingerprint)),E=new Date().toISOString(),S=ar(i,d.id)+1;dr(i,d.id)||(cr(i,d,r,E,S),S+=1);for(let R of p)i.delete(U).where(eq(U.id,R.id)).run(),wg(i,R,r,E,S,{runId:e.runId,reason:og}),S+=1;let D=0,y=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let R of m){let B=sr("thl");i.insert(U).values({id:B,thread_id:d.id,source:"auto",kind:R.kind,status:"active",text:R.text,covers_from_task_id:R.coversFromTaskId,covers_to_task_id:R.coversToTaskId,revision:0,created_at:E,updated_at:E,agent_id:y,source_task_id:R.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:R.contentFingerprint,dismissed_at:null}).run();let we=i.select().from(U).where(eq(U.id,B)).get();if(!we)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");ds(i,we,r,E,"thread.highlight.created",S),S+=1,D+=1;}let I=i.select().from(U).where(eq(U.thread_id,d.id)).all().filter(R=>R.source==="auto"&&R.status==="active").length;zt(i,{threadId:d.id,seq:S,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:E,payload:{runId:c.id,detectorVersion:e.detectorVersion,previousAutoCount:_,newAutoCount:I,deletedCount:p.length,createdCount:D}}),i.update(q).set({status:"completed",started_at:c.started_at??E,completed_at:E,error_code:null,previous_auto_count:_,new_auto_count:I}).where(and(eq(q.id,c.id),inArray(q.status,as))).run();let N=i.select().from(q).where(eq(q.id,c.id)).get();if(!N)throw new f("DB_ERROR","Highlight regeneration completion did not return a row");return {run:N,deletedCount:p.length,createdCount:D,previousAutoCount:_,newAutoCount:I}},{behavior:"immediate"})}catch(i){if(o)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:ag});}catch{}throw i instanceof f?i:new f("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=gg(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 c=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$1(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 u=d.length>o,l=s.afterSeq!==void 0?d.slice(0,o):u?d.slice(1):d,p=!1,_=l[0];return _&&(p=!!i.db.select({id:j.id}).from(j).where(and(eq(j.thread_id,s.threadId),lt$1(j.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=mg(e),r=ir(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let c=this.findThread(i,e.threadId,e.workspaceId);if(c||Xe(`Thread ${e.threadId} not found`),n.source==="auto"){let _=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(_)return _}let d=e.id??sr("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: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(u).run();let l=i.select().from(U).where(eq(U.id,d)).get();if(!l)throw new f("DB_ERROR","Highlight insert did not return a row");let p=ar(i,c.id)+1;return dr(i,c.id)||(cr(i,c,r,s,p),p+=1),ds(i,l,r,s,"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{o.close();}}updateHighlight(e){H(e.threadId,"threadId"),H(e.workspaceId,"workspaceId"),H(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&z("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&z("highlight update requires at least one field"),e.kind!==void 0&&ri(e.kind);let n=e.text===void 0?void 0:ni(e.text),r=ir(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let c=this.findThread(i,e.threadId,e.workspaceId);c||Xe(`Thread ${e.threadId} not found`);let d=i.select().from(U).where(and(eq(U.id,e.highlightId),eq(U.thread_id,c.id))).limit(1).get();if(d||Xe(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new lr(c.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new lr(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)&&z("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 S=d.revision+1;i.update(U).set({source:m,kind:u,text:l,covers_from_task_id:p,covers_to_task_id:_,revision:S,updated_at:s}).where(and(eq(U.id,d.id),eq(U.revision,d.revision))).run();let D=i.select().from(U).where(eq(U.id,d.id)).get();if(!D)throw new f("DB_ERROR","Highlight update did not return a row");let y=ar(i,c.id)+1;return dr(i,c.id)||(cr(i,c,r,s,y),y+=1),ds(i,D,r,s,"thread.highlight.updated",y,d),D},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("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)&&z("expectedRevision must be a non-negative integer");let n=ir(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||Xe(`Thread ${e.threadId} not found`);let c=o.select().from(U).where(and(eq(U.id,e.highlightId),eq(U.thread_id,i.id))).limit(1).get();if(c||Xe(`Highlight ${e.highlightId} not found`),c.revision!==e.expectedRevision)throw new lr(i.id,c.id,e.expectedRevision,c.revision);if(c.status==="dismissed")return c;let d=c.revision+1;o.update(U).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(and(eq(U.id,c.id),eq(U.revision,c.revision))).run();let u=o.select().from(U).where(eq(U.id,c.id)).get();if(!u)throw new f("DB_ERROR","Highlight dismissal did not return a row");let l=ar(o,i.id)+1;return dr(o,i.id)||(cr(o,i,n,r,l),l+=1),ds(o,u,n,r,"thread.highlight.deleted",l,c),u},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("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 c=s.db.all(sql`
|
|
629
629
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
630
630
|
ORDER BY started_at ASC, id ASC
|
|
631
|
-
`),d=new Map(
|
|
631
|
+
`),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 E=Math.min(h,m),S=Math.max(h,m);return !(u!==void 0&&(u<E||u>S)||l!==void 0&&S<l||p!==void 0&&E>p)})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to list active thread highlights",o)}finally{s.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};g();ft();Ot();Nt();pt();$t();vs();var Q=class extends f{reason;constructor(e,n="VALIDATION",r=e,s){super(n,r,s),this.name="CommonCodeRepositoryError",this.reason=e;}},Qc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function xg(){let t=randomBytes(16),e="";for(let n of t)e+=Qc[n%Qc.length];return e.slice(0,12)}function Zc(){return `c_${xg()}`}function vg(t){return typeof t=="string"&&bs.includes(t)}function Cg(t){return typeof t=="string"&&xs.includes(t)}function Sn(t){if(!vg(t))throw new Q("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function eu(t){if(!Cg(t))throw new Q("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function tu(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new Q("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function In(t){if(typeof t!="string"||t.trim().length===0)throw new Q("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function ls(t){if(typeof t!="string"||t.trim().length===0)throw new Q("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function It(t,e){return and(eq(C.code_group,t),or(isNull(C.workspace_id),eq(C.workspace_id,e)))}var ps=class extends Ee{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=$(n);if(e)try{De(r.db,n);}catch(s){throw r.close(),s}return r}listSelectable(e,n){if(Sn(e),In(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(C).where(and(It(e,n),eq(C.is_archived,0))).orderBy(asc(C.sort_order),asc(C.code)).all()}catch(s){throw new f("DB_ERROR","Failed to list selectable common codes",s)}finally{r.close();}}listForHistory(e,n){if(Sn(e),In(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(C).where(It(e,n)).orderBy(asc(C.sort_order),asc(C.code)).all()}catch(s){throw new f("DB_ERROR","Failed to list common-code history",s)}finally{r.close();}}reorder(e){let n=e.group;if(Sn(n),In(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let s of e.codes)ls(s);if(new Set(e.codes).size!==e.codes.length)throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(s=>{let o=s.select().from(C).where(It(n,e.workspaceId)).all(),i=o.filter(h=>h.is_archived===0),c=new Set(o.map(h=>h.code)),d=new Set(i.map(h=>h.code)),u=e.codes.find(h=>!c.has(h));if(u)throw new Q("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 Q("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 Q("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(),s.update(C).set({sort_order:h,updated_at:_}).where(and(eq(C.code_group,n),eq(C.code,m.code))).run());return s.select().from(C).where(It(n,e.workspaceId)).orderBy(asc(C.sort_order),asc(C.code)).all()},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to reorder common codes",s)}finally{r.close();}}resolve(e,n){if(Sn(e),ls(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(C).where(and(eq(C.code_group,e),eq(C.code,n))).limit(1).get()??null}catch(s){throw new f("DB_ERROR","Failed to resolve common code",s)}finally{r.close();}}createThreadState(e){In(e.workspaceId);let n=tu(e.name);eu(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{if(s.select({code:C.code}).from(C).where(and(It("THREAD_STATE",e.workspaceId),eq(C.is_archived,0),eq(C.code_name,n))).limit(1).get())throw new Q("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=s.select({maxSortOrder:sql`max(${C.sort_order})`}).from(C).where(It("THREAD_STATE",e.workspaceId)).get(),c=new Date().toISOString(),d=Zc();for(;s.select({code:C.code}).from(C).where(and(eq(C.code_group,"THREAD_STATE"),eq(C.code,d))).limit(1).get();)d=Zc();s.insert(C).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=s.select().from(C).where(and(eq(C.code_group,"THREAD_STATE"),eq(C.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(s){throw s instanceof f?s:new f("DB_ERROR","Failed to create thread state common code",s)}finally{r.close();}}updateDisplay(e){if(Sn(e.group),ls(e.code),In(e.workspaceId),e.name===void 0&&e.color===void 0)throw new Q("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:tu(e.name);e.color!==void 0&&eu(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{let o=s.select().from(C).where(and(eq(C.code_group,e.group),eq(C.code,e.code))).limit(1).get();if(!o)throw new Q("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(o,e.workspaceId),n===null&&o.is_builtin!==1)throw new Q("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&o.is_archived===0){let d=and(It(e.group,e.workspaceId),eq(C.is_archived,0));if(s.select({code:C.code}).from(C).where(and(d,eq(C.code_name,n),sql`${C.code} <> ${e.code}`)).limit(1).get())throw new Q("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),s.update(C).set(i).where(and(eq(C.code_group,e.group),eq(C.code,e.code))).run();let c=s.select().from(C).where(and(eq(C.code_group,e.group),eq(C.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(s){throw s instanceof f?s:new f("DB_ERROR","Failed to update common-code display values",s)}finally{r.close();}}archive(e,n,r,s=true){if(Sn(e),ls(n),In(r),typeof s!="boolean")throw new Q("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let o=this.openHandle(true);try{return o.db.transaction(i=>{let c=i.select().from(C).where(and(eq(C.code_group,e),eq(C.code,n))).limit(1).get();if(!c)throw new Q("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(c.is_builtin===1)throw new Q("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(c,r),!s&&c.code_name!==null&&i.select({code:C.code}).from(C).where(and(It(e,r),eq(C.is_archived,0),eq(C.code_name,c.code_name),ne$1(C.code,n))).limit(1).get())throw new Q("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${c.code_name}`);i.update(C).set({is_archived:s?1:0,updated_at:new Date().toISOString()}).where(and(eq(C.code_group,e),eq(C.code,n))).run();let d=i.select().from(C).where(and(eq(C.code_group,e),eq(C.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{o.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new Q("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};en();jn();g();var Ye={threadContext:"crewx_thread_context",apps:"apps",appsGuidance:"apps_guidance",availableApps:"available_apps",crewxUiState:"crewx_ui_state"};function Lg(t){return t.replace(new RegExp(`<${Ye.threadContext}\\b[^>]*>[\\s\\S]*?<\\/${Ye.threadContext}>`,"g"),"").replace(new RegExp(`<${Ye.apps}\\b[^>]*>[\\s\\S]*?<\\/${Ye.apps}>`,"g"),"").replace(new RegExp(`<${Ye.appsGuidance}\\b[^>]*>[\\s\\S]*?<\\/${Ye.appsGuidance}>`,"g"),"").replace(new RegExp(`<${Ye.availableApps}\\b[^>]*>[\\s\\S]*?<\\/${Ye.availableApps}>`,"g"),"").replace(new RegExp(`<${Ye.crewxUiState}\\b[^>]*>[\\s\\S]*?<\\/${Ye.crewxUiState}>`,"g"),"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
632
632
|
`).filter(s=>!(s.startsWith("Loaded ")&&s.includes("layouts from")||s.includes("[dotenv@")||s.includes("[Nest]")&&s.includes("DEBUG")||s.startsWith("Registered custom layout:")||s.startsWith("Updated custom layout:"))).join(`
|
|
633
|
-
`).trim()}function
|
|
634
|
-
`):s&&typeof s=="object"&&s.result!==void 0&&(r=s.result||"");}catch{r=
|
|
635
|
-
`)[0]??"":"";if(e){let r=
|
|
633
|
+
`).trim()}function Mg(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 $g(t,e,n){if(!t||e&&st(t,n))return "";let r=t;try{let s=JSON.parse(r);Array.isArray(s)?r=s.filter(o=>o?.type==="text"&&o?.text).map(o=>o.text).join(`
|
|
634
|
+
`):s&&typeof s=="object"&&s.result!==void 0&&(r=s.result||"");}catch{r=Lg(r);}return r}var Hg=new Set(["success","failed","stopped","running"]),Ug=new Set(["failed","stopped"]),Fg={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"},fs=200;function nu(t){if(t.length<=fs)return t;let e=t.charCodeAt(fs-1),n=e>=55296&&e<=56319?fs-1:fs;return t.slice(0,n)}function qg(t){let e=Ge(t),n=typeof t.error=="string"?t.error.split(`
|
|
635
|
+
`)[0]??"":"";if(e){let r=Fg[e];return nu(n?`${r}; ${n}`:r)}return n?nu(n):void 0}var _s=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new is({dbPath:this.dbPath})}getThreadHistoryRepo(){return new us({dbPath:this.dbPath})}updateThread(e,n){this.getThreadRepo().updateThread(e,{title:n.title});}async ensureThread(e,n,r,s){let o=this.getThreadRepo(),i=o.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 o.ensureThread(e,n,r,s),{created:false}}return o.ensureThread(e,n,r,s),{created:true}}async fetchHistory(e,n){let r=n?.limit??100,s=this.getThreadRepo(),o=s.findThreadById(e),i=s.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=s.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=o?.platform??"cli",p=this.rowsToMessages(i),_=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,o?.workspace_id??null);return {threadId:e,platform:l,messages:p,..._?{highlights:_}:{},metadata:{title:o?.title??void 0,firstMessage:o?.first_message??void 0,lastMessage:o?.last_message??void 0,messageCount:o?.message_count??0,updatedAt:o?.updated_at?new Date(o.updated_at).getTime():void 0}}}async fetchThreadState(e){try{let n=this.getThreadHistoryRepo().getSnapshot(e);if(!n)return;let r=new ps({dbPath:this.dbPath}),s=(o,i)=>{try{return r.resolve(o,i)?.code_name||i}catch{return i}};return {...n.title?{title:n.title}:{},...n.priority?{priority:{code:n.priority,name:s("THREAD_PRIORITY",n.priority)}}:{},...n.state?{state:{code:n.state,name:s("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,s){let{firstMessage:o}=this.getThreadRepo().saveUserMessage(e,n);return {id:e,firstMessage:o}}async saveAssistantMessage(e,n,r,s){return this.getThreadRepo().saveAssistantMessage(e,n),{id:e}}close(){}readActiveHighlights(e,n){if(!n)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,n)??[]).filter(s=>typeof s.text=="string"&&s.text.length>0).map(s=>({id:s.id,text:s.text,kind:s.kind,source:s.source,coversFromTaskId:s.covers_from_task_id,coversToTaskId:s.covers_to_task_id,createdAt:s.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 s={status:r.status??"",error:r.error,metadata:r.metadata},o=r.status?xe(s):void 0,i=Mg(r.metadata),c=$g(r.result,o!==void 0&&Ug.has(o),i);if(c||o!==void 0&&Hg.has(o)){let d={agent_id:r.agent_id,task_id:r.id};if(o&&o!=="success"){d.status=o;let u=qg(s);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 si=class extends lt{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new _s(e?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(e,n,r,s){}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 s=await this._provider.ensureThread(n.threadId,r,n.workspaceId,{createdByTaskId:n.traceId}),o=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,o.id,s.created||o.firstMessage,n);}catch{}}),this.unsubEnd=e.on("task:end",async n=>{if(!n.result)return;let r=n.metadata?.threadId;if(!r)return;let s=n.agentRef?.replace(/^@/,"")??"";try{let{id:o}=await this._provider.saveAssistantMessage(r,n.result,s);await this.afterAssistantMessage(r,o,n);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{si as ConversationPlugin,hs as FileLoggerPlugin,jo as SqliteTracingPlugin};
|