@crewx/sdk 0.9.0-rc.162 → 0.9.0-rc.164
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/esm/index.js +247 -224
- package/dist/esm/plugins/index.js +102 -85
- package/dist/esm/repository/index.js +134 -111
- package/dist/index.d.ts +4 -0
- package/dist/index.js +249 -226
- package/dist/migrations/0041_tranquil_vivisector.sql +54 -0
- package/dist/migrations/meta/0041_snapshot.json +4156 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/dist/plugins/index.js +102 -85
- package/dist/repository/index.d.ts +2 -0
- package/dist/repository/index.js +132 -109
- package/dist/repository/sidebar-tab.repository.d.ts +82 -0
- package/dist/repository/thread.repository.d.ts +10 -0
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/sidebar-tabs.d.ts +466 -0
- package/package.json +1 -1
package/dist/plugins/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
'use strict';var fs$1=require('fs'),
|
|
1
|
+
'use strict';var fs$1=require('fs'),ce=require('path'),jo=require('os'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core'),drizzleOrm=require('drizzle-orm'),child_process=require('child_process');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ce__namespace=/*#__PURE__*/_interopNamespace(ce);var jo__default=/*#__PURE__*/_interopDefault(jo);var fu=Object.defineProperty;var Pt=(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 v=(t,e)=>()=>(t&&(e=t(t=0)),e);var gu=(t,e)=>{for(var n in e)fu(t,n,{get:e[n],enumerable:true});};var h=v(()=>{});var f,it=v(()=>{h();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 Bo(t){if(t===":memory:")return t;let e=ce.resolve(t),n=e,r=[];for(;!fs$1.existsSync(n);){let o=ce.dirname(n);if(o===n)return e;r.unshift(n.slice(o.length+1)),n=o;}let s=fs$1.realpathSync(n);for(let o of r)s=ce.join(s,o);return ce.resolve(s)}function Iu(t,e){let n=Bo(t),r=Bo(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function _t(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&Au.some(e=>Iu(t,ce.join(jo__default.default.homedir(),".crewx",e))))throw new Error(`${Su}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var Su,Au,_e,at=v(()=>{h();Su="[crewx] Refusing to open the real CrewX database from a test process";Au=["crewx.db","logs.db"];_e=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||ce.join(jo__default.default.homedir(),".crewx","crewx.db");return _t(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return fs$1.existsSync(e??this.resolveDbPath())}};});function $(t,e={}){let n=_t(t),r=Pt("better-sqlite3"),{drizzle:s}=Pt("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 = ${bu}`),o.exec("PRAGMA busy_timeout = 5000"),o.exec("PRAGMA foreign_keys = ON"),o.exec("PRAGMA analysis_limit = 400")),{db:s(o),runRaw:(i,u=[])=>o.prepare(i).run(...u),close:()=>o.close()}}var bu,mt=v(()=>{h();at();bu=32*1024*1024;});function Mt(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function vu(t,e){if(e>0||!Mt(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(Nu))r.has(s)||t.run(`ALTER TABLE tasks ADD COLUMN ${s} ${o}`);}function Cu(t,e,n){if(!Mt(t,"__drizzle_migrations")||!Mt(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),s=new Set(r.map(i=>i.hash)),o=JSON.parse(fs$1.readFileSync(ce__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let u=xu[i.tag];if(!u)continue;let d=ce__namespace.default.join(e,`${i.tag}.sql`);if(!fs$1.existsSync(d))continue;let c=fs$1.readFileSync(d,"utf-8"),l=crypto.createHash("sha256").update(c).digest("hex");if(s.has(l))continue;let p=t.all("PRAGMA table_info(tasks)"),g=new Set(p.map(_=>_.name));for(let[_,m]of Object.entries(u))g.has(_)||(t.run(`ALTER TABLE tasks ADD COLUMN ${_} ${m}`),g.add(_));}}function Ko(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 Vo(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function Du(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(o=>o.name===n)}function Pu(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function er(t,e){return e.kind==="add-column"?Du(t,e.table,e.column):Pu(t,e.name)}function Jo(t,e,n){let r=t;for(let s of Vo(e)){let o=Ko(s);o?.kind==="add-column"&&er(r,o)||o?.kind==="create-index"&&er(r,o)||o?.kind==="drop-index"&&!er(r,o)||r.run(n.raw(s));}}function Lu(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),s=new Set(r.map(i=>i.hash)),o=JSON.parse(fs$1.readFileSync(ce__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let u=ce__namespace.default.join(e,`${i.tag}.sql`);if(!fs$1.existsSync(u))continue;let d=fs$1.readFileSync(u,"utf-8"),c=crypto.createHash("sha256").update(d).digest("hex");if(s.has(c))continue;let p=Vo(d).map(Ko);if(p.some(_=>!_))continue;let g=p;g.some(_=>_.kind==="add-column")&&g.some(_=>er(t,_))&&(t.transaction(_=>{Jo(_,d,n),_.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);},{behavior:"immediate"}),s.add(c),console.error(`[crewx] Reconciled additive migration ${i.tag} from existing schema objects.`));}}function Mu(t,e){let{sql:n}=Pt("drizzle-orm"),r=JSON.parse(fs$1.readFileSync(ce__namespace.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 u=r.entries.find(c=>c.tag===i);if(!u)throw new Error(`Missing release/App compatibility migration: ${i}`);let d=fs$1.readFileSync(ce__namespace.default.join(e,`${i}.sql`),"utf-8");return {entry:u,content:d,hash:crypto.createHash("sha256").update(d).digest("hex")}});t.transaction(i=>{let u=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(d=>d.hash));if(u.has(o[0].hash))for(let d of o.slice(1))u.has(d.hash)||(Jo(i,d.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${d.hash}, ${d.entry.when})`),u.add(d.hash),console.error(`[crewx] Replayed release/App migration ${d.entry.tag} safely.`));},{behavior:"immediate"});}function Fu(t,e,n,r){let o=JSON.parse(fs$1.readFileSync(ce__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===$u);if(!o)return;let i=ce__namespace.default.join(e,`${o.tag}.sql`);if(!fs$1.existsSync(i))return;let u=crypto.createHash("sha256").update(fs$1.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(g=>g.hash===u))return;if(!Mt(t,"tasks"))return {hash:u,affectedRows:0};let d=t.all("PRAGMA table_info(tasks)"),c=new Set(d.map(p=>p.name));if(!c.has("stop_requested_at")||!c.has("stop_requested_epoch"))return {hash:u,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:u,affectedRows:l?.count??0}}function
|
|
6
|
+
`);return {hash:u,affectedRows:l?.count??0}}function qu(t,e,n,r){let o=JSON.parse(fs$1.readFileSync(ce__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===Hu);if(!o)return;let i=ce__namespace.default.join(e,`${o.tag}.sql`);if(!fs$1.existsSync(i))return;let u=crypto.createHash("sha256").update(fs$1.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(g=>g.hash===u))return;if(!Mt(t,"threads"))return {hash:u,markedPointers:0};if(!t.all("PRAGMA table_info(threads)").some(p=>p.name==="created_by_task_id"))return {hash:u,markedPointers:0};let c=Mt(t,zo)?`AND NOT EXISTS (
|
|
7
7
|
SELECT 1
|
|
8
|
-
FROM ${
|
|
8
|
+
FROM ${zo} 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,45 +15,45 @@
|
|
|
15
15
|
SELECT 1
|
|
16
16
|
FROM sqlite_master
|
|
17
17
|
WHERE type = 'trigger'
|
|
18
|
-
AND name = '${
|
|
18
|
+
AND name = '${Uu}'
|
|
19
19
|
)
|
|
20
|
-
${c}`);return {hash:u,markedPointers:l?.count??0}}function
|
|
20
|
+
${c}`);return {hash:u,markedPointers:l?.count??0}}function Bu(t){let{migrate:e}=Pt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=Pt("drizzle-orm"),r=[ce__namespace.default.join(__dirname,"../migrations"),ce__namespace.default.join(__dirname,"migrations"),ce__namespace.default.join(__dirname,"../../../../drizzle/migrations"),ce__namespace.default.join(process.cwd(),"drizzle/migrations")],s=r.find(p=>fs$1.existsSync(ce__namespace.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),yu(t,i),o?.cnt&&(Ou(t,s),Au(t,s,n),Ru(t,s,n));let u=xu(t,s,n,!!o?.cnt),d=Cu(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 Ie(t,e){Ho.has(e)||(Du(t),Ho.add(e));}var Ho,wu,Eu,bu,vu,Nu,Uo,mt=N(()=>{h();Ho=new Set,wu={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"};Eu={"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"}};bu="0027_task_stop_scope_cleanup",vu="0033_thread_creator_boundary_guard",Nu="trg_threads_creator_late_fill_guard",Uo="thread_creator_unverified";});var Ae,Xr=N(()=>{h();Ae=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),starred:sqliteCore.integer("starred").notNull().default(0)});});var a,eh,Hu,ee,Lt=N(()=>{h();a=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),actor_kind:sqliteCore.text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:sqliteCore.text("actor_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),heartbeat_at:sqliteCore.text("heartbeat_at"),stop_requested_at:sqliteCore.text("stop_requested_at"),stop_requested_epoch:sqliteCore.integer("stop_requested_epoch"),rendered_prompt:sqliteCore.text("rendered_prompt"),security_key:sqliteCore.text("security_key"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),cwd:sqliteCore.text("cwd"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0),rating:sqliteCore.text("rating",{enum:["up","down"]}),rated_at:sqliteCore.text("rated_at")},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),rating_check:sqliteCore.check("tasks_rating_ck",drizzleOrm.sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(t.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:sqliteCore.index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:sqliteCore.index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:sqliteCore.index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(drizzleOrm.sql`${t.rating} IS NOT NULL`)})),{security_key:eh,...Hu}=drizzleOrm.getTableColumns(a),ee=Hu;});var et,zo=N(()=>{h();Lt();et=sqliteCore.sqliteTable("task_provider_inputs",{task_id:sqliteCore.text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),run_epoch:sqliteCore.integer("run_epoch").notNull(),input:sqliteCore.text("input").notNull(),key_wrap_skipped:sqliteCore.integer("key_wrap_skipped").notNull().default(0),recorded_at:sqliteCore.text("recorded_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.task_id,t.run_epoch]})}));});var Ge,Vo=N(()=>{h();Lt();Ge=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},t=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:sqliteCore.index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var Gu,zu,T,Qn=N(()=>{h();Xr();Gu="json_extract(metadata, '$.threadTitle.state')",zu="json_extract(metadata, '$.threadTitle.priority')",T=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Ae.id,{onDelete:"set null"}),created_by_kind:sqliteCore.text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:sqliteCore.text("created_by_id"),created_by_task_id:sqliteCore.text("created_by_task_id"),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:sqliteCore.index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:sqliteCore.index("idx_threads_workspace_thread_state").on(t.workspace_id,drizzleOrm.sql.raw(Gu)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(zu))}));});var Yo=N(()=>{h();sqliteCore.sqliteTable("thread_creator_unverified",{thread_id:sqliteCore.text("thread_id").notNull(),created_by_task_id:sqliteCore.text("created_by_task_id").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var Yu,Zo=N(()=>{h();Lt();Yu=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Yu.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},t=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var ei=N(()=>{h();Lt();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},t=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(t.timestamp)}));});var ni=N(()=>{h();Qn();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(t.thread_id,t.seq)}));});var si=N(()=>{h();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},t=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(t.partition_key)}));});var oi=N(()=>{h();sqliteCore.sqliteTable("request_log_daily",{day:sqliteCore.text("day").notNull(),scope:sqliteCore.text("scope").notNull(),ok:sqliteCore.integer("ok").notNull(),client:sqliteCore.integer("client").notNull(),server:sqliteCore.integer("server").notNull(),p50_ms:sqliteCore.integer("p50_ms"),p95_ms:sqliteCore.integer("p95_ms"),computed_at:sqliteCore.text("computed_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.day,t.scope]})}));});var di=N(()=>{h();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var ui=N(()=>{h();sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},t=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var li=N(()=>{h();sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)})),sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));});var fi=N(()=>{h();sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var gi=N(()=>{h();sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),app_id:sqliteCore.text("app_id"),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),opened_by_json:sqliteCore.text("opened_by_json"),agent_open_request_json:sqliteCore.text("agent_open_request_json"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${t.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("ui_instances_app_id_ck",drizzleOrm.sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${t.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:sqliteCore.check("ui_instances_opened_by_json_ck",drizzleOrm.sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:sqliteCore.uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(drizzleOrm.sql`${t.status} = 'active'`)}));});var _i=N(()=>{h();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),definition_id:sqliteCore.text("definition_id"),definition_version:sqliteCore.integer("definition_version"),definition_hash:sqliteCore.text("definition_hash"),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},t=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${t.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${t.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${t.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.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),vu(t,i),o?.cnt&&(Mu(t,s),Lu(t,s,n),Cu(t,s,n));let u=Fu(t,s,n,!!o?.cnt),d=qu(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 Oe(t,e){Go.has(e)||(Bu(t),Go.add(e));}var Go,Nu,xu,$u,Hu,Uu,zo,kt=v(()=>{h();Go=new Set,Nu={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"};xu={"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"}};$u="0027_task_stop_scope_cleanup",Hu="0033_thread_creator_boundary_guard",Uu="trg_threads_creator_late_fill_guard",zo="thread_creator_unverified";});var ee,tr=v(()=>{h();ee=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),starred:sqliteCore.integer("starred").notNull().default(0)});});var a,lh,Ku,te,$t=v(()=>{h();a=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),actor_kind:sqliteCore.text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:sqliteCore.text("actor_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),heartbeat_at:sqliteCore.text("heartbeat_at"),stop_requested_at:sqliteCore.text("stop_requested_at"),stop_requested_epoch:sqliteCore.integer("stop_requested_epoch"),rendered_prompt:sqliteCore.text("rendered_prompt"),security_key:sqliteCore.text("security_key"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),cwd:sqliteCore.text("cwd"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0),rating:sqliteCore.text("rating",{enum:["up","down"]}),rated_at:sqliteCore.text("rated_at")},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),rating_check:sqliteCore.check("tasks_rating_ck",drizzleOrm.sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(t.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:sqliteCore.index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:sqliteCore.index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:sqliteCore.index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(drizzleOrm.sql`${t.rating} IS NOT NULL`)})),{security_key:lh,...Ku}=drizzleOrm.getTableColumns(a),te=Ku;});var tt,Zo=v(()=>{h();$t();tt=sqliteCore.sqliteTable("task_provider_inputs",{task_id:sqliteCore.text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),run_epoch:sqliteCore.integer("run_epoch").notNull(),input:sqliteCore.text("input").notNull(),key_wrap_skipped:sqliteCore.integer("key_wrap_skipped").notNull().default(0),recorded_at:sqliteCore.text("recorded_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.task_id,t.run_epoch]})}));});var Ke,ti=v(()=>{h();$t();Ke=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},t=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:sqliteCore.index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var ec,tc,T,_n=v(()=>{h();tr();ec="json_extract(metadata, '$.threadTitle.state')",tc="json_extract(metadata, '$.threadTitle.priority')",T=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>ee.id,{onDelete:"set null"}),created_by_kind:sqliteCore.text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:sqliteCore.text("created_by_id"),created_by_task_id:sqliteCore.text("created_by_task_id"),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:sqliteCore.index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:sqliteCore.index("idx_threads_workspace_thread_state").on(t.workspace_id,drizzleOrm.sql.raw(ec)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(tc))}));});var si=v(()=>{h();sqliteCore.sqliteTable("thread_creator_unverified",{thread_id:sqliteCore.text("thread_id").notNull(),created_by_task_id:sqliteCore.text("created_by_task_id").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var ic,ii=v(()=>{h();$t();ic=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>ic.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},t=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var ai=v(()=>{h();$t();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},t=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(t.timestamp)}));});var ui=v(()=>{h();_n();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(t.thread_id,t.seq)}));});var li=v(()=>{h();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},t=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(t.partition_key)}));});var pi=v(()=>{h();sqliteCore.sqliteTable("request_log_daily",{day:sqliteCore.text("day").notNull(),scope:sqliteCore.text("scope").notNull(),ok:sqliteCore.integer("ok").notNull(),client:sqliteCore.integer("client").notNull(),server:sqliteCore.integer("server").notNull(),p50_ms:sqliteCore.integer("p50_ms"),p95_ms:sqliteCore.integer("p95_ms"),computed_at:sqliteCore.text("computed_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.day,t.scope]})}));});var hi=v(()=>{h();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var _i=v(()=>{h();sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},t=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var ki=v(()=>{h();sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)})),sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));});var wi=v(()=>{h();sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var yi=v(()=>{h();sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),app_id:sqliteCore.text("app_id"),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),opened_by_json:sqliteCore.text("opened_by_json"),agent_open_request_json:sqliteCore.text("agent_open_request_json"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${t.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("ui_instances_app_id_ck",drizzleOrm.sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${t.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:sqliteCore.check("ui_instances_opened_by_json_ck",drizzleOrm.sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:sqliteCore.uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(drizzleOrm.sql`${t.status} = 'active'`)}));});var Ri=v(()=>{h();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),definition_id:sqliteCore.text("definition_id"),definition_version:sqliteCore.integer("definition_version"),definition_hash:sqliteCore.text("definition_hash"),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},t=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${t.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${t.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${t.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.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:sqliteCore.uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:sqliteCore.index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:sqliteCore.index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));});var
|
|
26
|
+
)`),instanceRequestUnique:sqliteCore.uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:sqliteCore.index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:sqliteCore.index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));});var Si=v(()=>{h();sqliteCore.sqliteTable("ui_instance_repins",{instance_id:sqliteCore.text("instance_id").notNull(),from_version:sqliteCore.integer("from_version").notNull(),from_hash:sqliteCore.text("from_hash").notNull(),to_version:sqliteCore.integer("to_version").notNull(),to_hash:sqliteCore.text("to_hash").notNull(),from_revision:sqliteCore.integer("from_revision").notNull(),to_revision:sqliteCore.integer("to_revision"),status:sqliteCore.text("status").notNull(),code:sqliteCore.text("code"),attempts:sqliteCore.integer("attempts").notNull().default(1),first_at:sqliteCore.integer("first_at").notNull(),last_at:sqliteCore.integer("last_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.instance_id,t.to_hash],name:"ui_instance_repins_pk"}),instanceIdCheck:sqliteCore.check("ui_instance_repins_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 5 AND 128 AND ${t.instance_id} GLOB 'uic_*'`),fromVersionCheck:sqliteCore.check("ui_instance_repins_from_version_ck",drizzleOrm.sql`${t.from_version} >= 1`),toVersionCheck:sqliteCore.check("ui_instance_repins_to_version_ck",drizzleOrm.sql`${t.to_version} >= 1`),fromHashCheck:sqliteCore.check("ui_instance_repins_from_hash_ck",drizzleOrm.sql`length(${t.from_hash}) = 64 AND ${t.from_hash} NOT GLOB '*[^0-9a-f]*'`),toHashCheck:sqliteCore.check("ui_instance_repins_to_hash_ck",drizzleOrm.sql`length(${t.to_hash}) = 64 AND ${t.to_hash} NOT GLOB '*[^0-9a-f]*'`),fromRevisionCheck:sqliteCore.check("ui_instance_repins_from_revision_ck",drizzleOrm.sql`${t.from_revision} >= 0`),toRevisionCheck:sqliteCore.check("ui_instance_repins_to_revision_ck",drizzleOrm.sql`${t.to_revision} IS NULL OR ${t.to_revision} >= 0`),statusCheck:sqliteCore.check("ui_instance_repins_status_ck",drizzleOrm.sql`${t.status} IN ('applied', 'deferred', 'failed')`),attemptsCheck:sqliteCore.check("ui_instance_repins_attempts_ck",drizzleOrm.sql`${t.attempts} >= 1`),datesCheck:sqliteCore.check("ui_instance_repins_dates_ck",drizzleOrm.sql`${t.first_at} >= 0 AND ${t.last_at} >= ${t.first_at}`),resultCheck:sqliteCore.check("ui_instance_repins_result_ck",drizzleOrm.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 Ti=N(()=>{h();sqliteCore.sqliteTable("ui_definition_archive",{definition_hash:sqliteCore.text("definition_hash").primaryKey().notNull(),definition_json:sqliteCore.text("definition_json").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({definitionHashCheck:sqliteCore.check("ui_definition_archive_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:sqliteCore.check("ui_definition_archive_definition_json_ck",drizzleOrm.sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:sqliteCore.check("ui_definition_archive_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`)}));});var yi,Ei=N(()=>{h();yi=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},t=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${t.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${t.stage_index} >= 1`)})),sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>yi.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>yi.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},t=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var ds,us,x,cs=N(()=>{h();ds=["THREAD_STATE","THREAD_PRIORITY"],us=["gray","blue","violet","green","amber","orange","red","pink"],x=sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.code_group,t.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${t.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var Ri,Si,Ii,Ai,Oi,B,U,$,bi=N(()=>{h();Qn();Ri=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Si=["user","agent","system"],Ii=["auto","manual"],Ai=["decision","judgment","issue","result","pivot"],Oi=["queued","running","completed","failed"],B=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),type:sqliteCore.text("type").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),payload_json:sqliteCore.text("payload_json").notNull(),created_at:sqliteCore.text("created_at").notNull(),actor_id:sqliteCore.text("actor_id"),task_id:sqliteCore.text("task_id"),highlight_id:sqliteCore.text("highlight_id")},t=>({typeCheck:sqliteCore.check("thread_events_type_ck",drizzleOrm.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:sqliteCore.check("thread_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:sqliteCore.check("thread_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:sqliteCore.index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:sqliteCore.index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:sqliteCore.uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),U=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),request_id:sqliteCore.text("request_id").notNull(),status:sqliteCore.text("status").notNull(),detector_version:sqliteCore.text("detector_version").notNull(),requested_at:sqliteCore.text("requested_at").notNull(),started_at:sqliteCore.text("started_at"),completed_at:sqliteCore.text("completed_at"),error_code:sqliteCore.text("error_code"),previous_auto_count:sqliteCore.integer("previous_auto_count"),new_auto_count:sqliteCore.integer("new_auto_count")},t=>({statusCheck:sqliteCore.check("thread_highlight_runs_status_ck",drizzleOrm.sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:sqliteCore.check("thread_highlight_runs_counts_ck",drizzleOrm.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:sqliteCore.uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:sqliteCore.uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(drizzleOrm.sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:sqliteCore.index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),$=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),source:sqliteCore.text("source").notNull(),kind:sqliteCore.text("kind").notNull(),status:sqliteCore.text("status").notNull().default("active"),text:sqliteCore.text("text"),covers_from_task_id:sqliteCore.text("covers_from_task_id").notNull(),covers_to_task_id:sqliteCore.text("covers_to_task_id").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),agent_id:sqliteCore.text("agent_id"),source_task_id:sqliteCore.text("source_task_id"),detector_version:sqliteCore.text("detector_version"),content_fingerprint:sqliteCore.text("content_fingerprint"),dismissed_at:sqliteCore.text("dismissed_at")},t=>({sourceCheck:sqliteCore.check("thread_highlights_source_ck",drizzleOrm.sql`${t.source} IN ('auto', 'manual')`),kindCheck:sqliteCore.check("thread_highlights_kind_ck",drizzleOrm.sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:sqliteCore.check("thread_highlights_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:sqliteCore.check("thread_highlights_active_text_ck",drizzleOrm.sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:sqliteCore.check("thread_highlights_covers_ck",drizzleOrm.sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:sqliteCore.check("thread_highlights_auto_key_ck",drizzleOrm.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:sqliteCore.index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:sqliteCore.index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:sqliteCore.uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(drizzleOrm.sql`${t.source} = 'auto'`)}));});var Ni=N(()=>{h();sqliteCore.sqliteTable("storage_metadata",{source_kind:sqliteCore.text("source_kind").notNull(),source_id:sqliteCore.text("source_id").notNull(),utc_ts:sqliteCore.text("utc_ts"),bytes:sqliteCore.integer("bytes").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:sqliteCore.index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteCore.sqliteTable("storage_metadata_state",{unit:sqliteCore.text("unit").primaryKey().notNull(),cursor_rowid:sqliteCore.integer("cursor_rowid").notNull().default(0),end_rowid:sqliteCore.integer("end_rowid"),complete:sqliteCore.integer("complete").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()});});var we,xi=N(()=>{h();we=sqliteCore.sqliteTable("agent_send_history",{workspace_id:sqliteCore.text("workspace_id").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),last_accepted_at:sqliteCore.text("last_accepted_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:sqliteCore.index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var Et=N(()=>{h();Xr();Lt();zo();Vo();Qn();Yo();Zo();ei();ni();si();oi();di();ui();li();fi();gi();_i();mi();Ti();Ei();cs();bi();Ni();xi();});var $t,ps,Ci,fs=N(()=>{h();$t={"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}},ps=new Set(["gpt-5.3-codex-spark"]),Ci=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 gs(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 Pc(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),kn;let e=gs(t),n=Dc[e];if(n)return ir[n]??$t[n]??kn;if(ir[e])return ir[e];if($t[e])return $t[e];if(ps.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),kn;if(Ci.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),kn;let r={...$t,...ir};for(let s of Object.keys(r))if(e.includes(s))return r[s];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),kn}function Lc(t,e,n,r=0,s){let o=Pc(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 Di(t,e,n,r,s,o){return t&&t>0?t:!e&&!n?0:Lc(e??0,n??0,s,r??0)}var Dc,kn,ir,ar=N(()=>{h();fs();fs();Dc={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"},kn={input:0,cachedInput:0,output:0},ir={};});function $i(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function Li(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Hi(t){return Number.isSafeInteger(t)&&t>0}function Fc(t,e){return new Promise(n=>{let r;try{r=child_process.spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:$i(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 ${Pi}ms`)});},Pi);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 Ui(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Fc(t,e)}function qc(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Bc(){return new Promise(t=>{setImmediate(t);})}function Rt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return Li(n)==="ESRCH"?"not_found":Li(n)==="EPERM"?"alive":"unknown"}}function Wc(t,e){let n=Rt(-t,e),r=Rt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function Fi(t,e,n,r){let s=Math.max(0,n),o=Math.max(1,r.pollIntervalMs??Hc),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 Bc();;){let l=Wc(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([c,qc(Math.min(o,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function Mi(t,e,n,r,s){let o=await Fi(t,e,s.hardConfirmMs??Uc,{...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 dr(t,e,n={}){if(!Hi(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 Ui(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"}async function Ut(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(!Hi(t))return s("Invalid process ID");let o=e.kill??process.kill,i=Rt(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 Ui("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){g={status:null,stdout:"",stderr:"",error:$i(m)};}let _=Rt(t,o);return _==="not_found"?g.status===0&&!g.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:s(_==="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 Mi(t,o,u,r,e);if(await Fi(t,o,e.graceMs??$c,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 Mi(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 Pi,Ht,$c,Hc,Uc,ur=N(()=>{h();Pi=3e3,Ht="SIGINT",$c=2e3,Hc=25,Uc=100;});function Gi(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 Wi(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)=>Gi(r,s))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function zi(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 ji(t){return {taskId:t.id,source:zi(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Jc(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var cr,Ki=N(()=>{h();it();_t();mt();ot();Et();cr=class extends ge{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=de.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?ht(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=de.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}else if(!fs$1.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=H(n);if(e)try{Ie(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(drizzleOrm.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(drizzleOrm.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)=>Gi(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=zi(u);if(d==="blob"){let g=Wi(e,u.logs);if(i.update(a).set({logs:JSON.stringify([...g,...r]),log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.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(Ge).values(r.map((g,_)=>({task_id:e,seq:c+_,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),i.update(a).set({last_log_seq:l,log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.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?ji(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 Jc(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=ji(o);if(i.source==="blob"){let l=Wi(e,o.logs);return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let u=s.select({seq:Ge.seq,timestamp:Ge.timestamp,level:Ge.level,message:Ge.message}).from(Ge).where(drizzleOrm.eq(Ge.task_id,e)).orderBy(n===void 0?drizzleOrm.asc(Ge.seq):drizzleOrm.desc(Ge.seq)),c=(n===void 0?u.all():u.limit(n).all()).map(({timestamp:l,level:p,message:g})=>({timestamp:l,level:p,message:g}));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 el,lr,Ji=N(()=>{h();it();_t();mt();ot();Et();el=50,lr=class extends ge{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=H(e);try{return Ie(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(we).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[we.workspace_id,we.actor_id,we.agent_id],set:{last_accepted_at:drizzleOrm.sql`MAX(${we.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:we.agent_id,lastAcceptedAt:we.last_accepted_at}).from(we).where(drizzleOrm.and(drizzleOrm.eq(we.workspace_id,e),drizzleOrm.eq(we.actor_id,n))).orderBy(drizzleOrm.desc(we.last_accepted_at),drizzleOrm.asc(we.agent_id)).limit(el).all()}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to find recent agent sends",s)}finally{r?.close();}}};});var Xi=N(()=>{h();});var Y,St=N(()=>{h();Y=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 It,hs=N(()=>{h();St();It=class extends Y{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function ms(t){if(!pr(t)||t.type!=="item.started"||!Qi(t)||!Yi(t))return false;let e=t.item;return !pr(e)||!Qi(e)||!Yi(e)||!_s(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)&&_s(n.path)&&_s(n.kind)):false}function pr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Zi(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function _s(t){return typeof t=="string"&&t.trim().length>0}function Yi(t){return !Zi(t,"status")||t.status==="in_progress"}function Qi(t){for(let e of ["error","errors","isError","is_error"])if(Zi(t,e))return false;return true}var ks=N(()=>{h();});function tl(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?ul[e]:void 0;return o?o(r,s):Object.values(ta).some(i=>i(r,s))}function Je(t,e){let n=t.split(`
|
|
33
|
-
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>
|
|
32
|
+
)`)}));});var Ai=v(()=>{h();sqliteCore.sqliteTable("ui_definition_archive",{definition_hash:sqliteCore.text("definition_hash").primaryKey().notNull(),definition_json:sqliteCore.text("definition_json").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({definitionHashCheck:sqliteCore.check("ui_definition_archive_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:sqliteCore.check("ui_definition_archive_definition_json_ck",drizzleOrm.sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:sqliteCore.check("ui_definition_archive_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`)}));});var bi,Ni=v(()=>{h();bi=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},t=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${t.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${t.stage_index} >= 1`)})),sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>bi.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>bi.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},t=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var ls,ps,x,fs=v(()=>{h();ls=["THREAD_STATE","THREAD_PRIORITY"],ps=["gray","blue","violet","green","amber","orange","red","pink"],x=sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.code_group,t.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${t.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var vi,xi,Ci,Di,Pi,B,U,H,Li=v(()=>{h();_n();vi=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],xi=["user","agent","system"],Ci=["auto","manual"],Di=["decision","judgment","issue","result","pivot"],Pi=["queued","running","completed","failed"],B=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),type:sqliteCore.text("type").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),payload_json:sqliteCore.text("payload_json").notNull(),created_at:sqliteCore.text("created_at").notNull(),actor_id:sqliteCore.text("actor_id"),task_id:sqliteCore.text("task_id"),highlight_id:sqliteCore.text("highlight_id")},t=>({typeCheck:sqliteCore.check("thread_events_type_ck",drizzleOrm.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:sqliteCore.check("thread_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:sqliteCore.check("thread_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:sqliteCore.index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:sqliteCore.index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:sqliteCore.uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),U=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),request_id:sqliteCore.text("request_id").notNull(),status:sqliteCore.text("status").notNull(),detector_version:sqliteCore.text("detector_version").notNull(),requested_at:sqliteCore.text("requested_at").notNull(),started_at:sqliteCore.text("started_at"),completed_at:sqliteCore.text("completed_at"),error_code:sqliteCore.text("error_code"),previous_auto_count:sqliteCore.integer("previous_auto_count"),new_auto_count:sqliteCore.integer("new_auto_count")},t=>({statusCheck:sqliteCore.check("thread_highlight_runs_status_ck",drizzleOrm.sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:sqliteCore.check("thread_highlight_runs_counts_ck",drizzleOrm.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:sqliteCore.uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:sqliteCore.uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(drizzleOrm.sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:sqliteCore.index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),H=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),source:sqliteCore.text("source").notNull(),kind:sqliteCore.text("kind").notNull(),status:sqliteCore.text("status").notNull().default("active"),text:sqliteCore.text("text"),covers_from_task_id:sqliteCore.text("covers_from_task_id").notNull(),covers_to_task_id:sqliteCore.text("covers_to_task_id").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),agent_id:sqliteCore.text("agent_id"),source_task_id:sqliteCore.text("source_task_id"),detector_version:sqliteCore.text("detector_version"),content_fingerprint:sqliteCore.text("content_fingerprint"),dismissed_at:sqliteCore.text("dismissed_at")},t=>({sourceCheck:sqliteCore.check("thread_highlights_source_ck",drizzleOrm.sql`${t.source} IN ('auto', 'manual')`),kindCheck:sqliteCore.check("thread_highlights_kind_ck",drizzleOrm.sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:sqliteCore.check("thread_highlights_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:sqliteCore.check("thread_highlights_active_text_ck",drizzleOrm.sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:sqliteCore.check("thread_highlights_covers_ck",drizzleOrm.sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:sqliteCore.check("thread_highlights_auto_key_ck",drizzleOrm.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:sqliteCore.index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:sqliteCore.index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:sqliteCore.uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(drizzleOrm.sql`${t.source} = 'auto'`)}));});var $i=v(()=>{h();sqliteCore.sqliteTable("storage_metadata",{source_kind:sqliteCore.text("source_kind").notNull(),source_id:sqliteCore.text("source_id").notNull(),utc_ts:sqliteCore.text("utc_ts"),bytes:sqliteCore.integer("bytes").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:sqliteCore.index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteCore.sqliteTable("storage_metadata_state",{unit:sqliteCore.text("unit").primaryKey().notNull(),cursor_rowid:sqliteCore.integer("cursor_rowid").notNull().default(0),end_rowid:sqliteCore.integer("end_rowid"),complete:sqliteCore.integer("complete").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()});});var Ee,Hi=v(()=>{h();Ee=sqliteCore.sqliteTable("agent_send_history",{workspace_id:sqliteCore.text("workspace_id").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),last_accepted_at:sqliteCore.text("last_accepted_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:sqliteCore.index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var qi,Bi=v(()=>{h();_n();tr();sqliteCore.sqliteTable("sidebar_states",{workspace_id:sqliteCore.text("workspace_id").primaryKey().references(()=>ee.id,{onDelete:"cascade"}),revision:sqliteCore.integer("revision").notNull().default(0),rail_collapsed:sqliteCore.integer("rail_collapsed").notNull().default(0),seeded_at:sqliteCore.text("seeded_at").notNull()},t=>({railCollapsedCheck:sqliteCore.check("sidebar_states_rail_collapsed_ck",drizzleOrm.sql`${t.rail_collapsed} IN (0, 1)`)})),qi=sqliteCore.sqliteTable("sidebar_groups",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),name:sqliteCore.text("name").notNull(),color:sqliteCore.text("color").notNull(),collapsed:sqliteCore.integer("collapsed").notNull().default(0),position:sqliteCore.integer("position").notNull()},t=>({colorCheck:sqliteCore.check("sidebar_groups_color_ck",drizzleOrm.sql`${t.color} IN ('cyan', 'orange', 'purple', 'blue')`),collapsedCheck:sqliteCore.check("sidebar_groups_collapsed_ck",drizzleOrm.sql`${t.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:sqliteCore.index("idx_sidebar_groups_workspace_position").on(t.workspace_id,t.position)})),sqliteCore.sqliteTable("sidebar_tabs",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>qi.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})})),sqliteCore.sqliteTable("sidebar_closed_tabs",{id:sqliteCore.integer("id").primaryKey({autoIncrement:true}),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>qi.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull(),closed_at:sqliteCore.text("closed_at").notNull()},t=>({idxSidebarClosedTabsWorkspaceId:sqliteCore.index("idx_sidebar_closed_tabs_workspace_id").on(t.workspace_id,t.id)})),sqliteCore.sqliteTable("thread_reads",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),read_through_at:sqliteCore.text("read_through_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var St=v(()=>{h();tr();$t();Zo();ti();_n();si();ii();ai();ui();li();pi();hi();_i();ki();wi();yi();Ri();Si();Ai();Ni();fs();Li();$i();Hi();Bi();});var Ut,ms,Wi,ks=v(()=>{h();Ut={"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}},ms=new Set(["gpt-5.3-codex-spark"]),Wi=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 Ts(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 Wc(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),En;let e=Ts(t),n=Bc[e];if(n)return lr[n]??Ut[n]??En;if(lr[e])return lr[e];if(Ut[e])return Ut[e];if(ms.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),En;if(Wi.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),En;let r={...Ut,...lr};for(let s of Object.keys(r))if(e.includes(s))return r[s];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),En}function jc(t,e,n,r=0,s){let o=Wc(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 ji(t,e,n,r,s,o){return t&&t>0?t:!e&&!n?0:jc(e??0,n??0,s,r??0)}var Bc,En,lr,pr=v(()=>{h();ks();ks();Bc={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"},En={input:0,cachedInput:0,output:0},lr={};});function Vi(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function zi(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Ji(t){return Number.isSafeInteger(t)&&t>0}function Jc(t,e){return new Promise(n=>{let r;try{r=child_process.spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:Vi(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 ${Gi}ms`)});},Gi);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 Xi(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Jc(t,e)}function Xc(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Yc(){return new Promise(t=>{setImmediate(t);})}function It(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return zi(n)==="ESRCH"?"not_found":zi(n)==="EPERM"?"alive":"unknown"}}function Qc(t,e){let n=It(-t,e),r=It(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function Yi(t,e,n,r){let s=Math.max(0,n),o=Math.max(1,r.pollIntervalMs??Kc),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 Yc();;){let l=Qc(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([c,Xc(Math.min(o,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function Ki(t,e,n,r,s){let o=await Yi(t,e,s.hardConfirmMs??Vc,{...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 fr(t,e,n={}){if(!Ji(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 Xi(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"}async function qt(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(!Ji(t))return s("Invalid process ID");let o=e.kill??process.kill,i=It(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 Xi("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){g={status:null,stdout:"",stderr:"",error:Vi(m)};}let _=It(t,o);return _==="not_found"?g.status===0&&!g.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:s(_==="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 Ki(t,o,u,r,e);if(await Yi(t,o,e.graceMs??zc,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 Ki(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 Gi,Ft,zc,Kc,Vc,gr=v(()=>{h();Gi=3e3,Ft="SIGINT",zc=2e3,Kc=25,Vc=100;});function na(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 ea(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)=>na(r,s))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function ra(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 ta(t){return {taskId:t.id,source:ra(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function sl(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var hr,sa=v(()=>{h();at();mt();kt();it();St();hr=class extends _e{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ce.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?_t(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=ce.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}else if(!fs$1.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=$(n);if(e)try{Oe(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(drizzleOrm.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(drizzleOrm.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)=>na(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=ra(u);if(d==="blob"){let g=ea(e,u.logs);if(i.update(a).set({logs:JSON.stringify([...g,...r]),log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.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(Ke).values(r.map((g,_)=>({task_id:e,seq:c+_,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),i.update(a).set({last_log_seq:l,log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.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?ta(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 sl(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=ta(o);if(i.source==="blob"){let l=ea(e,o.logs);return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let u=s.select({seq:Ke.seq,timestamp:Ke.timestamp,level:Ke.level,message:Ke.message}).from(Ke).where(drizzleOrm.eq(Ke.task_id,e)).orderBy(n===void 0?drizzleOrm.asc(Ke.seq):drizzleOrm.desc(Ke.seq)),c=(n===void 0?u.all():u.limit(n).all()).map(({timestamp:l,level:p,message:g})=>({timestamp:l,level:p,message:g}));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 ul,_r,ia=v(()=>{h();at();mt();kt();it();St();ul=50,_r=class extends _e{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 Oe(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(Ee).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[Ee.workspace_id,Ee.actor_id,Ee.agent_id],set:{last_accepted_at:drizzleOrm.sql`MAX(${Ee.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:Ee.agent_id,lastAcceptedAt:Ee.last_accepted_at}).from(Ee).where(drizzleOrm.and(drizzleOrm.eq(Ee.workspace_id,e),drizzleOrm.eq(Ee.actor_id,n))).orderBy(drizzleOrm.desc(Ee.last_accepted_at),drizzleOrm.asc(Ee.agent_id)).limit(ul).all()}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to find recent agent sends",s)}finally{r?.close();}}};});var aa=v(()=>{h();});var Y,At=v(()=>{h();Y=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 Ot,ws=v(()=>{h();At();Ot=class extends Y{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function Es(t){if(!mr(t)||t.type!=="item.started"||!ua(t)||!da(t))return false;let e=t.item;return !mr(e)||!ua(e)||!da(e)||!ys(e.id)?false:e.type==="web_search"?e.query===""&&mr(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=>mr(n)&&ys(n.path)&&ys(n.kind)):false}function mr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ca(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function ys(t){return typeof t=="string"&&t.trim().length>0}function da(t){return !ca(t,"status")||t.status==="in_progress"}function ua(t){for(let e of ["error","errors","isError","is_error"])if(ca(t,e))return false;return true}var Rs=v(()=>{h();});function cl(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?kl[e]:void 0;return o?o(r,s):Object.values(pa).some(i=>i(r,s))}function Ye(t,e){let n=t.split(`
|
|
33
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>cl(r,e))}function Re(t){return typeof t=="object"&&t!==null}function la(t,e){if(e==="assistant"||e==="user"){let n=t.message;return Re(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||Re(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?Re(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function ll(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:la(t,e)}function pl(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Re(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 Re(n)&&typeof n.type=="string"}return false}function fl(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||Re(t.part):e==="text"||e==="tool_use"?Re(t.part):e==="result"?typeof t.result=="string":false}function gl(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||Re(t.part)||e==="result"&&typeof t.result=="string")}function hl(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?Re(t.data):e==="result"?typeof t.result=="string":false}function _l(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 ml(t,e){return e==="available_commands"?Re(t.tools)||Re(t.commands):e==="usage"?Re(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||Re(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var pa,kl,Bt=v(()=>{h();Rs();pa={claude:la,codex:pl,opencode:fl,copilot:hl,gemini:_l},kl={...pa,claude:ll,opencode:gl,grok:ml,antigravity:()=>false};});function Qe(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function Ze(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 Wt=v(()=>{h();});function yl(t){let e=El(t),n=e.map((o,i)=>({line:o,index:i})).filter(({line:o})=>Sl(o.value)),r=Rl(e);return {result:n.length===1&&n[0].index===r?Il(n[0].line.value):null,resultPreview:bl(e,n),hasReservedLine:n.length>0}}function Le(t,e){let n=yl(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function El(t){let e=[],n=0;for(let r=0;r<t.length;r++){let s=t[r];if(s!==`
|
|
34
34
|
`&&s!=="\r")continue;let o=s==="\r"&&t[r+1]===`
|
|
35
35
|
`?`\r
|
|
36
|
-
`: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 gl(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function hl(t){return t.trimStart().startsWith(cl)}function _l(t){let e=t.trim();if(!e.startsWith(na)||!e.endsWith("]]"))return null;let n=e.slice(na.length,-2);if(!n)return null;try{return ml(JSON.parse(n))}catch{return null}}function ml(t){return kl(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function kl(t){if(!wl(t)||Object.keys(t).some(r=>!ll.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?ra(t.taskId)&&ra(t.agentId):t.isError===true}function Tl(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 ra(t){return typeof t=="string"&&t.trim().length>0}function wl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var na,cl,ll,Bt=N(()=>{h();na="[[crewx:delegation-result ",cl="[[crewx:delegation-result",ll=new Set(["schema","taskId","agentId","isError"]);});function Pe(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 Wt=N(()=>{h();});var sa,fr,Ts,gr=N(()=>{h();sa=["none","minimal","low","medium","high","xhigh","max","ultra"],fr={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"]},Ts={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(Ts).map(([t,e])=>[t,e.models]));});function ws(t){return El[t]??t}function Sl(t){return Rl.get(t)??t}function ys(t){if(!t)return {};let e=Al.get(t);return e?{...e}:{model:t}}function Es(t,e){return t==="antigravity"||t==="cli/antigravity"?ys(e):e===void 0?{}:{model:Sl(e)}}var yl,El,Rl,Il,Al,wn=N(()=>{h();yl=[{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]"}],El={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Rl=new Map(yl.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Il=[{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"}],Al=new Map(Il.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function bl(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function ut(t){return hr(t).models}function hr(t){return Ol[t]??Ts[t]??bl()}function yn(t,e){let n=hr(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Es(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function oa(t){return hr(t).modelOverrides}function ia(){return ut("claude")}function aa(){return ut("codex")}function da(){return ut("copilot")}function ua(){return ut("antigravity")}var Ol,At=N(()=>{h();gr();ar();wn();Ol={};});function ca(t){return vl[t]??t}var vl,la=N(()=>{h();At();wn();vl={auto:"default"};});function _r(t,e){return (fr[t]??[]).includes(e)}function ct(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Nl.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function pa(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 fa(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 ga(t){return !t||!_r("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function ha(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=ca(t);return e.has(n)?["--permission-mode",n]:[]}function _a(t){return t?_r("claude",t)?["--effort",t]:[]:[]}function ma(t){return t==="default"?[]:t&&xl.has(t)?["--permission-mode",t]:[]}function ka(t){return t===true?["--always-approve"]:[]}function Ta(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 wa(t){return t?_r("grok",t)?["--effort",t]:[]:[]}function ya(t){if(!t)return [];switch(ws(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Ea(t){return t?_r("antigravity",t)?["--effort",t]:[]:[]}var Nl,xl,En=N(()=>{h();la();wn();gr();Nl=new Set(sa);xl=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function Cl(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 Dl(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 Pl(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 Ra(t){let e=new Map,n;for(let o of t.split(`
|
|
37
|
-
`))if(o.trim())try{let i=JSON.parse(o);if(i.type!=="assistant")continue;let u=i.message,d=u?.id,c=u?.usage;if(typeof d!="string"||!c)continue;let l=Number(c.input_tokens??0),p=Number(c.cache_read_input_tokens??0);e.set(d,{inputTokens:l+p,cachedInputTokens:p});let g=u?.model;typeof g=="string"&&g&&(n=g);}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
|
|
38
|
-
`))if(r.trim())try{let s=JSON.parse(r),o=
|
|
39
|
-
`).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
|
|
40
|
-
`).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
|
|
41
|
-
`)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=
|
|
36
|
+
`: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 Rl(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Sl(t){return t.trimStart().startsWith(Tl)}function Il(t){let e=t.trim();if(!e.startsWith(fa)||!e.endsWith("]]"))return null;let n=e.slice(fa.length,-2);if(!n)return null;try{return Al(JSON.parse(n))}catch{return null}}function Al(t){return Ol(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Ol(t){if(!Nl(t)||Object.keys(t).some(r=>!wl.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?ga(t.taskId)&&ga(t.agentId):t.isError===true}function bl(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 ga(t){return typeof t=="string"&&t.trim().length>0}function Nl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var fa,Tl,wl,jt=v(()=>{h();fa="[[crewx:delegation-result ",Tl="[[crewx:delegation-result",wl=new Set(["schema","taskId","agentId","isError"]);});function Me(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 Gt=v(()=>{h();});var ha,kr,Ss,Tr=v(()=>{h();ha=["none","minimal","low","medium","high","xhigh","max","ultra"],kr={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"]},Ss={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(Ss).map(([t,e])=>[t,e.models]));});function Is(t){return xl[t]??t}function Dl(t){return Cl.get(t)??t}function As(t){if(!t)return {};let e=Ll.get(t);return e?{...e}:{model:t}}function Os(t,e){return t==="antigravity"||t==="cli/antigravity"?As(e):e===void 0?{}:{model:Dl(e)}}var vl,xl,Cl,Pl,Ll,Sn=v(()=>{h();vl=[{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]"}],xl={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Cl=new Map(vl.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Pl=[{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"}],Ll=new Map(Pl.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function $l(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function ct(t){return wr(t).models}function wr(t){return Ml[t]??Ss[t]??$l()}function In(t,e){let n=wr(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Os(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function _a(t){return wr(t).modelOverrides}function ma(){return ct("claude")}function ka(){return ct("codex")}function Ta(){return ct("copilot")}function wa(){return ct("antigravity")}var Ml,bt=v(()=>{h();Tr();pr();Sn();Ml={};});function ya(t){return Hl[t]??t}var Hl,Ea=v(()=>{h();bt();Sn();Hl={auto:"default"};});function yr(t,e){return (kr[t]??[]).includes(e)}function lt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Ul.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Ra(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 Sa(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 Ia(t){return !t||!yr("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Aa(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=ya(t);return e.has(n)?["--permission-mode",n]:[]}function Oa(t){return t?yr("claude",t)?["--effort",t]:[]:[]}function ba(t){return t==="default"?[]:t&&Fl.has(t)?["--permission-mode",t]:[]}function Na(t){return t===true?["--always-approve"]:[]}function va(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 xa(t){return t?yr("grok",t)?["--effort",t]:[]:[]}function Ca(t){if(!t)return [];switch(Is(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Da(t){return t?yr("antigravity",t)?["--effort",t]:[]:[]}var Ul,Fl,An=v(()=>{h();Ea();Sn();Tr();Ul=new Set(ha);Fl=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function ql(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 Bl(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 Wl(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 Pa(t){let e=new Map,n;for(let o of t.split(`
|
|
37
|
+
`))if(o.trim())try{let i=JSON.parse(o);if(i.type!=="assistant")continue;let u=i.message,d=u?.id,c=u?.usage;if(typeof d!="string"||!c)continue;let l=Number(c.input_tokens??0),p=Number(c.cache_read_input_tokens??0);e.set(d,{inputTokens:l+p,cachedInputTokens:p});let g=u?.model;typeof g=="string"&&g&&(n=g);}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 zt(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
|
|
38
|
+
`))if(r.trim())try{let s=JSON.parse(r),o=Wl(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=ql(s)??Bl(s);i&&(e=i);}catch{}return n||(e??void 0)}var On=v(()=>{h();});function $e(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 Nt=v(()=>{h();});function La(t){let e=t.split(`
|
|
39
|
+
`).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 zl(t){let e=t.split(`
|
|
40
|
+
`).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 Kt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function Ua(t){let e=Kt(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=Xl(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(Yl(n))return `Claude rate limit: ${n}`}}function Kl(t){for(let e of t.split(`
|
|
41
|
+
`)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=Kt(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 Vl(t){let e=Kt(t);if(e?.type!=="rate_limit_event")return;let n=Kt(Kt(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=Ma(n.five_hour),s=Ma(n.seven_day);if(!(!r&&!s))return {...r?{five_hour:r}:{},...s?{seven_day:s}:{}}}function Ma(t){let e=Kt(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function Jl(t){let e=Ua(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 Xl(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
42
42
|
|
|
43
|
-
`):""}function
|
|
44
|
-
`):i=JSON.stringify(o),{timestamp:t,type:"tool_result",toolUseId:s,...
|
|
45
|
-
`);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,u=s.modelUsage,d=u?Object.keys(u)[0]??null:null;return {usage:i,model:d}}}catch{}let n=
|
|
46
|
-
`).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
|
|
47
|
-
`).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
|
|
48
|
-
`),u=typeof e.error=="string"?e.error:lt(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=Pe(o);return s==="Bash"&&Xe(i)?Ye(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",...De(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&&!(lt(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 Zl(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=Pe(s);return r==="Bash"&&Xe(o)?Ye(t,o):{timestamp:t,type:"tool_use",toolName:r,toolInput:o}}return null}var zl,Kl,As,Os=N(()=>{h();St();Ft();Rn();qt();Wt();ks();Bt();En();At();Ot();zl=new Set(["turn.started","turn.completed","item.updated"]),Kl="cli/codex";As={command:"codex",meta:{displayName:"Codex",models:aa(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:s}=ct(e.model),o=e.effort??s,i=e.resumeSessionId?fa(e.mode):pa(e.mode),u=ga(o),d=r?["-m",r]:[],c=Jl(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=Xl(t);if(e)throw new Y(e,Kl);let n=Na(t);if(n)return n;let r=t.trim();return Je(r,"codex")?"":r},extractPartialText(t){return Na(t)},parseResultMeta(t){let e=jt(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=Vl(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(!lt(d))continue;let c=d.type;if(!c)continue;let l=Le(d,r);if(Ca(d)){let g=Da(d);s.push({timestamp:l,type:"error",content:g,errorMessage:g});continue}if(!c.startsWith("item.")&&!c.startsWith("turn.")&&!c.startsWith("thread.")||ms(d))continue;c==="thread.started"&&n&&n.state.delete("codex.pending");let p=d.item;if(p){if(c==="item.started"){s.push(...Yl(l,p,xa(p,c,n,i)));continue}if(c==="item.completed"){let g=Ql(l,p,xa(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?zl.has(r):!1}catch{return false}}};});function np(t){return t?tp[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function kr(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ha(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 Kt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function rp(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);Kt(i)?e.push(i):n=!0;continue}catch{}let o=Ha(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);Kt(u)?e.push(u):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,$a).trim()}function Ua(t){let e=Kt(t.error)?t.error:void 0,n=e&&Kt(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??Ma;return (o?`${i} (ref: ${o})`:i).slice(0,$a)}function Pa(t){let e=rp(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=Kt(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(Ua(d));continue}if(c==="step_finish"){u=true;let l=Kt(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 Fa(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Tr(){return new Y("OpenCode returned no assistant output.",zt,{code:"EMPTY_OUTPUT",kind:"transient"})}function sp(){return new Y("OpenCode emitted malformed JSON output.",zt,{code:"PROVIDER_CRASHED",kind:"transient"})}function La(t,e){switch(Fa(t)){case "length":return new Y("OpenCode stopped because the context window was exceeded.",zt,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new Y("OpenCode stopped because the content filter blocked the response.",zt,{code:"UNKNOWN",kind:"permanent"});case "error":return new Y(e?`OpenCode error: ${e}`:`${Ma} while generating a response.`,zt,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var ep,zt,Ma,$a,tp,bs,vs=N(()=>{h();St();Rn();Wt();Ot();ep=new Set(["step_start","step_finish"]),zt="cli/opencode",Ma="OpenCode provider error",$a=240,tp={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};bs={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,s=r!==void 0?[...r]:["run"];kr(s,"--format")||s.push("--format","json"),e.resumeSessionId&&!s.includes("-s")&&!s.includes("--session")&&s.push("-s",e.resumeSessionId);let{agent:o,autoApprove:i}=np(e.mode);kr(s,"--agent")||o!==void 0&&s.push("--agent",o),i&&!kr(s,"--auto")&&s.push("--auto"),e.effort!==void 0&&!kr(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=Pa(t),n=e.errorMessages[0];if(n){let i=La("error",n);if(i)throw i}let r=La(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 Tr();return s}if(e.resultText?.trim()){if(!e.hasTerminal)throw Tr();return e.resultText}if(e.malformed)throw sp();if(!e.hasTerminal)throw Tr();let o=Fa(e.terminalReason);if((o==="stop"||o==="tool-calls")&&e.toolUseCount>0)return "";throw Tr()},interpretExit(t,e,n=""){if(t===0)return null;let s=Pa(n).errorMessages[0];return s?new Y(`OpenCode error: ${s}`,zt,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=jt(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=Ha(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=Le(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,_=String(g?.status||""),m=g?.input,y=Pe(m);if(r.push({timestamp:u,type:"tool_use",toolName:l,toolUseId:p,toolInput:y}),_==="completed"&&g?.output!==void 0){let k=g.output,v=typeof k=="string"?k:JSON.stringify(k);r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:v,isError:false});}else _==="error"&&r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(d==="error"){let c=Ua(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?ep.has(r):!1}catch{return false}}};});function Sn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function op(t,e){if(!(t?ut(Ns).some(o=>o.id===t):false)||!t)return e;let r=yn(Ns,t),s=oa(Ns)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:s&&r.includes(s)?s:void 0:s}var Ns,xs,Cs=N(()=>{h();St();wn();At();En();Ns="antigravity";xs={command:"agy",meta:{displayName:"Antigravity",models:ua(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:s}=ct(e.model),o=ys(r),i=o.model,u=e.effort??s??o.effort,d=op(i,u),c=e.additionalArgs??[],l=i&&!Sn(c,"--model")?["--model",i]:[],p=Sn(c,"--effort")?[]:Ea(d),g=Sn(c,"--mode")||Sn(c,"--dangerously-skip-permissions")?[]:ya(e.mode),_=Sn(c,"--print")?[]:["--print",t];return {args:[...l,...p,...g,...c,..._]}},extractText(t){let e=t.trim();if(!e)throw new Y("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 qa=N(()=>{h();qt();Wt();Bt();Ot();});function Vt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Jt(t){return Vt(t)?t:void 0}function _e(t){return typeof t=="string"?t:void 0}function Nt(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function cp(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 In(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return Vt(n)?[n]:[]}catch{return cp(e).flatMap(n=>{try{let r=JSON.parse(n);return Vt(r)?[r]:[]}catch{return []}})}}function za(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function vt(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(vt).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
49
|
-
`):void 0}if(
|
|
43
|
+
`):""}function Yl(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function Ha(t){return t.replace(/\s+/g," ").trim()}function Ql(t,e){let n=t?.description;if(typeof n!="string")return;let r=Ha(n);if(!r||r===Ha(e))return;if(r.length<=$a)return r;let s=r.slice(0,$a-1);return /[\uD800-\uDBFF]$/.test(s)&&(s=s.slice(0,-1)),`${s}\u2026`}function Zl(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=Me(o);if(r==="Bash"&&Qe(i))return Ze(t,i,s);let u=Ql(o,i);return {timestamp:t,type:"tool_use",toolUseId:s,toolName:r,toolInput:i,...u?{toolTitle:u}:{}}}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(u=>u.type==="text"&&typeof u.text=="string").map(u=>u.text).join(`
|
|
44
|
+
`):i=JSON.stringify(o),{timestamp:t,type:"tool_result",toolUseId:s,...Le(i,r)}}return null}var jl,Gl,Er,$a,bs=v(()=>{h();ws();At();Bt();Wt();jt();Gt();An();bt();On();Nt();jl=new Set(["tool_progress"]),Gl="cli/claude";Er={command:"claude",meta:{displayName:"Claude",models:ma(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:s}=lt(e.model),o=e.effort??s,i=Aa(e.mode),u=Oa(o),d=r?["--model",r]:[],c=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",...c,...i,...u,...d,...p],stdinMessage:t}:{args:["--output-format","stream-json","--verbose",...c,...i,...u,...d,...p],stdinMessage:t}}return {args:["-p","--output-format","stream-json","--verbose",...c,...i,...u,...d],stdinMessage:t}},extractText(t){let e=zl(t);if(e?.is_error===true){let s=Er.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 Y(`Claude ended without an answer (subtype=${o}, terminal_reason=${i})`,Gl,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=La(t);if(n)return n;let r=t.trim();return Ye(r,"claude")?"":r},extractPartialText(t){return La(t)},extractFailure(t){try{let e=JSON.parse(t),n=Ua(e);if(n)return new Ot(n)}catch{}return null},interpretExit(t,e,n){let r=Kl(n??"");return r?new Y(`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"}):null},observeRateLimit(t){try{let e=JSON.parse(t);return Vl(e)}catch{return}},parseResultMeta(t){let e=t.split(`
|
|
45
|
+
`);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,u=s.modelUsage,d=u?Object.keys(u)[0]??null:null;return {usage:i,model:d}}}catch{}let n=Pa(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=$e(n,e??new Date().toISOString()),o=Jl(n);if(o)return [{timestamp:s,type:"error",content:o,errorMessage:o}];let i=n.output_file,u=n.summary;if(r==="system"&&n.subtype==="task_notification"&&n.status==="completed"&&typeof i=="string"&&i.trim().length>0&&typeof u=="string"&&u.trim().length>0)return [{timestamp:s,type:"text",content:u}];if(r!=="assistant"&&r!=="user")return [];let c=n.message?.content;if(!Array.isArray(c))return [];let l=[];for(let p of c){let g=Zl(s,p);g&&l.push(g);}return l},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?jl.has(r):!1}catch{return false}}};$a=200;});function Fa(t){let e=t.split(`
|
|
46
|
+
`).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 ep,Ns,vs=v(()=>{h();Bt();On();Wt();Gt();jt();bt();Tr();Nt();ep=new Set(["interactive","plan","autopilot"]);Ns={command:"copilot",meta:{displayName:"Copilot",models:Ta()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&ep.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(kr.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=Fa(t);if(e)return e;let n=t.trim();return Ye(n,"copilot")?"":n},extractPartialText(t){return Fa(t)},parseResultMeta(t){let e=zt(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=$e(n,e??new Date().toISOString()),i=s.toolCallId;if(r==="tool.execution_start"){let u=String(s.toolName||""),d=s.arguments,c=Me(d);return (u==="bash"||u==="Bash")&&Qe(c)?[Ze(o,c,i)]:[{timestamp:o,type:"tool_use",toolName:u,toolInput:c,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let u=s.error;if(u)return [{timestamp:o,type:"tool_result",...i&&{toolUseId:i},...Le(String(u.message||""),true)}];let d=s.result,c=String(d?.content||"");return [{timestamp:o,type:"tool_result",...i&&{toolUseId:i},...Le(c,false)}]}if(r==="assistant.message"){let u=String(s.content||"");return u?[{timestamp:o,type:"text",content:u}]:[]}return []}};});function rp(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 sp(t){return t[0]==="exec"?t.slice(1):t}function qa(t){let e=t.split(`
|
|
47
|
+
`).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 pt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Wa(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||pt(t.error)}function ja(t){let e=pt(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 op(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(pt(n)&&Wa(n))return ja(n)}}function Ba(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}`,c=s.get(o)??[];return c.push(d),s.set(o,c),d}let i=s.get(o),u=i?.pop();return i?.length||s.delete(o),u}function ip(t,e,n){let r=e.type;if(r==="command_execution"){let s=String(e.command||"");return Qe(s)?[Ze(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:Me(e.arguments),...n?{toolUseId:n}:{}}]:[]}function ap(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=dp(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",...Le(s,o),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let s=pt(e.result)?e.result:void 0,i=(Array.isArray(s?.content)?s.content:[]).filter(d=>pt(d)&&d.type==="text"&&typeof d.text=="string").map(d=>d.text).join(`
|
|
48
|
+
`),u=typeof e.error=="string"?e.error:pt(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=Me(o);return s==="Bash"&&Qe(i)?Ze(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",...Le(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&&!(pt(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 dp(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=Me(s);return r==="Bash"&&Qe(o)?Ze(t,o):{timestamp:t,type:"tool_use",toolName:r,toolInput:o}}return null}var tp,np,xs,Cs=v(()=>{h();At();Bt();On();Wt();Gt();Rs();jt();An();bt();Nt();tp=new Set(["turn.started","turn.completed","item.updated"]),np="cli/codex";xs={command:"codex",meta:{displayName:"Codex",models:ka(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:s}=lt(e.model),o=e.effort??s,i=e.resumeSessionId?Sa(e.mode):Ra(e.mode),u=Ia(o),d=r?["-m",r]:[],c=sp(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=op(t);if(e)throw new Y(e,np);let n=qa(t);if(n)return n;let r=t.trim();return Ye(r,"codex")?"":r},extractPartialText(t){return qa(t)},parseResultMeta(t){let e=zt(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=rp(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(!pt(d))continue;let c=d.type;if(!c)continue;let l=$e(d,r);if(Wa(d)){let g=ja(d);s.push({timestamp:l,type:"error",content:g,errorMessage:g});continue}if(!c.startsWith("item.")&&!c.startsWith("turn.")&&!c.startsWith("thread.")||Es(d))continue;c==="thread.started"&&n&&n.state.delete("codex.pending");let p=d.item;if(p){if(c==="item.started"){s.push(...ip(l,p,Ba(p,c,n,i)));continue}if(c==="item.completed"){let g=ap(l,p,Ba(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?tp.has(r):!1}catch{return false}}};});function lp(t){return t?cp[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Rr(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ja(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 Jt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pp(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);Jt(i)?e.push(i):n=!0;continue}catch{}let o=Ja(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);Jt(u)?e.push(u):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function vt(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,Va).trim()}function Xa(t){let e=Jt(t.error)?t.error:void 0,n=e&&Jt(e.data)?e.data:void 0,r=vt(e?.name),s=vt(n?.message)??vt(e?.message)??vt(t.message)??vt(t.errorMessage)??vt(t.error),o=vt(t.ref),i=r&&s&&r!==s?`${r}: ${s}`:r??s??Ka;return (o?`${i} (ref: ${o})`:i).slice(0,Va)}function Ga(t){let e=pp(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=Jt(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(Xa(d));continue}if(c==="step_finish"){u=true;let l=Jt(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 Ya(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Sr(){return new Y("OpenCode returned no assistant output.",Vt,{code:"EMPTY_OUTPUT",kind:"transient"})}function fp(){return new Y("OpenCode emitted malformed JSON output.",Vt,{code:"PROVIDER_CRASHED",kind:"transient"})}function za(t,e){switch(Ya(t)){case "length":return new Y("OpenCode stopped because the context window was exceeded.",Vt,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new Y("OpenCode stopped because the content filter blocked the response.",Vt,{code:"UNKNOWN",kind:"permanent"});case "error":return new Y(e?`OpenCode error: ${e}`:`${Ka} while generating a response.`,Vt,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var up,Vt,Ka,Va,cp,Ds,Ps=v(()=>{h();At();On();Gt();Nt();up=new Set(["step_start","step_finish"]),Vt="cli/opencode",Ka="OpenCode provider error",Va=240,cp={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};Ds={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,s=r!==void 0?[...r]:["run"];Rr(s,"--format")||s.push("--format","json"),e.resumeSessionId&&!s.includes("-s")&&!s.includes("--session")&&s.push("-s",e.resumeSessionId);let{agent:o,autoApprove:i}=lp(e.mode);Rr(s,"--agent")||o!==void 0&&s.push("--agent",o),i&&!Rr(s,"--auto")&&s.push("--auto"),e.effort!==void 0&&!Rr(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=Ga(t),n=e.errorMessages[0];if(n){let i=za("error",n);if(i)throw i}let r=za(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 Sr();return s}if(e.resultText?.trim()){if(!e.hasTerminal)throw Sr();return e.resultText}if(e.malformed)throw fp();if(!e.hasTerminal)throw Sr();let o=Ya(e.terminalReason);if((o==="stop"||o==="tool-calls")&&e.toolUseCount>0)return "";throw Sr()},interpretExit(t,e,n=""){if(t===0)return null;let s=Ga(n).errorMessages[0];return s?new Y(`OpenCode error: ${s}`,Vt,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=zt(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=Ja(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=$e(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,_=String(g?.status||""),m=g?.input,y=Me(m);if(r.push({timestamp:u,type:"tool_use",toolName:l,toolUseId:p,toolInput:y}),_==="completed"&&g?.output!==void 0){let k=g.output,N=typeof k=="string"?k:JSON.stringify(k);r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:N,isError:false});}else _==="error"&&r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(d==="error"){let c=Xa(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?up.has(r):!1}catch{return false}}};});function bn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function gp(t,e){if(!(t?ct(Ls).some(o=>o.id===t):false)||!t)return e;let r=In(Ls,t),s=_a(Ls)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:s&&r.includes(s)?s:void 0:s}var Ls,Ms,$s=v(()=>{h();At();Sn();bt();An();Ls="antigravity";Ms={command:"agy",meta:{displayName:"Antigravity",models:wa(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:s}=lt(e.model),o=As(r),i=o.model,u=e.effort??s??o.effort,d=gp(i,u),c=e.additionalArgs??[],l=i&&!bn(c,"--model")?["--model",i]:[],p=bn(c,"--effort")?[]:Da(d),g=bn(c,"--mode")||bn(c,"--dangerously-skip-permissions")?[]:Ca(e.mode),_=bn(c,"--print")?[]:["--print",t];return {args:[...l,...p,...g,...c,..._]}},extractText(t){let e=t.trim();if(!e)throw new Y("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 Qa=v(()=>{h();Wt();Gt();jt();Nt();});function Xt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Yt(t){return Xt(t)?t:void 0}function ke(t){return typeof t=="string"?t:void 0}function Ct(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Tp(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 Nn(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return Xt(n)?[n]:[]}catch{return Tp(e).flatMap(n=>{try{let r=JSON.parse(n);return Xt(r)?[r]:[]}catch{return []}})}}function rd(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function xt(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(xt).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
49
|
+
`):void 0}if(Xt(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=xt(t[e]);if(n!==void 0)return n}}}function wp(t){let e=i=>Array.isArray(i)&&i.every(u=>Number.isInteger(u)&&u>=0&&u<=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 u=JSON.stringify(i,(d,c)=>e(c)?`<bytes:${c.length}>`:c);return u===void 0?String(i):u},o=t.rawOutput;if(o!=null){let i=Yt(o);if(!i)return n(xt(o))??s(o);let u;if(e(i.output)&&i.output.length>0&&(u=n(r(i.output))),!u&&e(i.stdout)&&i.stdout.length>0&&(u=n(r(i.stdout))),!u){let l=Yt(i.Result);u=n(i.output)??n(l?.output)??n(xt(o));}let d=e(i.stderr)&&i.stderr.length>0?r(i.stderr):void 0;if(d!==void 0)if(u){let l=u.endsWith(`
|
|
50
50
|
`)||u.endsWith("\r")?"":`
|
|
51
|
-
`;u=`${u}${l}${d}`;}else u=n(d);if(u)return u;let c=n(i.summary)??n(
|
|
52
|
-
`).flatMap(
|
|
53
|
-
`),s=r.length>
|
|
54
|
-
`).flatMap(
|
|
55
|
-
`).flatMap(
|
|
56
|
-
`)??"";if(!n.trim())return;let r=Ya(t.provider);if(!r)return;let s;try{s=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let o=mp(s?.model,t.model),i=s?.usage;if(!i)return {stdout:n,adapter:r};let u=yr(i.inputTokens),d=yr(i.outputTokens),c=yr(i.cachedInputTokens),l=Di(yr(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 Ls=N(()=>{h();Qa();ar();});function $s(t){let e=new Set;for(let n of t)for(let r of kp.get(n)??[n])e.add(r);return [...e]}function Hs(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"&&Tp.has(n)?n:void 0}catch{return}}function Qe(t){let e=Hs(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(Ms.stopped.test(t.error))return "user_stop";if(Ms.runnerLost.test(t.error))return "runner_lost"}}function Me(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=Hs(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&Ms.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function wp(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function On(t){let e=Me(t);return t.status==="runner_lost"&&Hs(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...wp(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}var An,kp,Ms,Tp,bn=N(()=>{h();An=["success","completed","done","failed","error","stopped","runner_lost"],kp=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);Ms={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},Tp=new Set(["user_stop","runner_lost","launch_failed"]);});function Us(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 Fs(){return Us("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Yt(){return Us("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function Sr(){return Us("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Xt(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Rr(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 yp(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 Za(t,e){return !!t.stop_requested_at&&Xt(t.stop_requested_epoch)===Xt(e)}function ed(t,e){let n=Xt(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let s=yp(t.getTask(e.taskId));return !s||s.status!=="running"||Xt(s.run_epoch)!==n?{accepted:false,row:s}:{accepted:true,row:s}}function sd(t,e){let n=vn.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),vn.delete(t),true)}function Nn(t,e){let n=vn.get(t);return !n||e!==void 0&&n.runEpoch!==Xt(e)?false:sd(t,n)}function od(t,e){let n=Xt(e.runEpoch);Nn(e.taskId);let r=true,s=null;try{let c=ed(t,{...e,runEpoch:n});r=c.accepted,s=c.row;}catch(c){Rr(c);}if(!r)return false;let o=Fs(),i=Math.min(o,1e3),u=setInterval(()=>{let c=vn.get(e.taskId);if(!(!c||c.timer!==u))try{c.heartbeatElapsedMs+=i;let l=c.heartbeatElapsedMs>=o,p=ed(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){sd(e.taskId,c);return}l&&(c.heartbeatElapsedMs%=o,c.lastHeartbeatAt=Date.now()),p.row&&Za(p.row,n)&&!c.stopRequested&&(c.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(Rr));}catch(l){Rr(l);}},i),d={timer:u,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return vn.set(e.taskId,d),typeof u=="object"&&u!==null&&"unref"in u&&u.unref(),s&&Za(s,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(s)).catch(Rr)),true}var td,nd,rd,vn,xn=N(()=>{h();td=1e4,nd=3e4,rd=18e5;vn=new Map;});function Ir(t,e=Date.now(),n=js){let r=t?Date.parse(t):Number.NaN,s=typeof e=="number"?e:Date.parse(e),o=Ks(n,js,0);return Number.isFinite(r)&&Number.isFinite(s)&&s-r>o?"forced":"cooperative"}function Ks(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function cd(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function vp(t){if(!t)return;let e=cd(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function Ee(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=vp(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function Ys(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 K(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 Ws(t,e){return K(t,Sp,e)}function Np(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=Yt():false}function xp(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Cp(t){let e=typeof t.pid=="number"&&t.pid>0?t.pid:void 0,n=cd(t.metadata),r=n.ownership==="runner"&&typeof n.providerPid=="number"&&Number.isSafeInteger(n.providerPid)&&n.providerPid>0?n.providerPid:void 0;return [...new Set([e,r].filter(s=>s!==void 0))]}function Dp(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return Ee(r,n)}async function Pp(t,e,n,r){let s=Date.now()+n;for(;;){let o=Dp(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 ud(t,e,n){let r=new Date().toISOString(),s={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},o=t.requestTaskStop({id:e,requestedAt:r,...s}),i=t.getTask(e);if(!o.accepted){if(o.status==="pending"){let C=t.stopPendingTask(e,void 0,void 0,{...s,at:r}),E=t.getTask(e);if(C||!E||E.status!=="running")return Ee(E);if(o=t.requestTaskStop({id:e,requestedAt:r,...s}),!o.accepted&&o.status!=="running"||!o.accepted&&!o.alreadyRequestedAt)return Ee(t.getTask(e))}else if(!(o.status==="running"&&o.alreadyRequestedAt))return Ee(i)}let u=o.runEpoch,d=Ks(n.graceMs,js,0),c=Ks(n.pollMs,Ep,1),l=await Pp(t,e,d,c);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return Ee(p);let g=Cp(p),_=g[0];if(!_){let C=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),E=t.getTask(e);return C||E?.status!=="running"?Ee(E):K(E,"Failed to finalize task stop")}let m=xp(n),y="unknown";if(!Np(p,Date.now())){let C=n.processControl?.checkProcessOwnershipAsync??dr;try{y=await C(_,n.ownershipMarkers??Xs,m);}catch{y="unknown";}if(y!=="owned")return Ys(p)}let k=n.processControl?.terminateProcessTree??Ut;for(let C of g){let E;try{E=await k(C,{...m,signal:Ht});}catch(I){E={status:"failed",pid:C,method:m.platform==="win32"?"taskkill":"process-group",error:I instanceof Error?I.message:String(I)};}if(E.status==="failed")return K(t.getTask(e),E.error??"Failed to terminate process tree")}let v=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),S=t.getTask(e);return v||S?.status!=="running"?Ee(S,_):K(S,"Task changed before stop was finalized")}function Vs(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Js(t){return Number.isSafeInteger(t)&&t>=0}function Cn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Lp(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Mp(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function $p(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 Hp(t){switch(t){case "epoch_mismatch":return Gs;case "workspace_mismatch":return zs;default:return}}async function ld(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Ws(n,Vs(e.targetPid)?e.targetPid:void 0);if(!Js(e.sourceRunEpoch)||!Js(e.settleRunEpoch)||Cn(n.run_epoch)!==e.settleRunEpoch)return K(n,qs,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return K(n,Bs,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 K(n,Ip,e.targetPid)}let o=t.getTask(e.taskId);if(!o||o.status!=="running")return Ws(o,e.targetPid);if(s.runEpoch!==e.settleRunEpoch||Cn(o.run_epoch)!==e.settleRunEpoch)return K(o,qs,e.targetPid);if(e.workspaceId!==void 0&&o.workspace_id!==e.workspaceId)return K(o,Bs,e.targetPid);if(!Vs(e.targetPid))return K(o,Rp);let i=Lp(e),u=e.processControl?.checkProcessOwnershipAsync??dr,d="unknown";try{d=await u(e.targetPid,e.ownershipMarkers??Xs,i);}catch{d="unknown";}if(d!=="owned")return Ys(o,e.targetPid);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return Ws(c,e.targetPid);if(Cn(c.run_epoch)!==e.settleRunEpoch)return K(c,qs,e.targetPid);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return K(c,Bs,e.targetPid);let l=e.processControl?.terminateProcessTree??Ut,p;try{p=await l(e.targetPid,{...i,signal:Ht});}catch{return K(t.getTask(e.taskId),id,e.targetPid)}if(p.status==="failed")return K(t.getTask(e.taskId),id,e.targetPid);let g;try{g=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return K(t.getTask(e.taskId),ad,e.targetPid)}return g?Ee(t.getTask(e.taskId),e.targetPid):K(t.getTask(e.taskId),ad,e.targetPid)}async function pd(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Ee(n);if(!Js(e.expectedRunEpoch)||Cn(n.run_epoch)!==e.expectedRunEpoch)return K(n,Gs);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return K(n,zs);let r=n.pid;if(!Vs(r))return K(n,Ap);let s=Mp(e),o=e.processControl?.checkProcessOwnershipAsync??dr,i="unknown";try{i=await o(r,e.ownershipMarkers??Xs,s);}catch{i="unknown";}if(i!=="owned")return Ys(n,r,Op);let u=e.processControl?.terminateProcessTree??Ut,d;try{d=await u(r,{...s,signal:Ht});}catch{return K(t.getTask(e.taskId),dd,r)}if(d.status==="failed")return K(t.getTask(e.taskId),dd,r);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return Ee(c,r);if(Cn(c.run_epoch)!==e.expectedRunEpoch)return K(c,Gs,r);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return K(c,zs,r);let l;try{l=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return K(t.getTask(e.taskId),bp,r)}let p=Hp(l);return p?K(t.getTask(e.taskId),p,r):l!=="settled"?Ee(t.getTask(e.taskId),r):$p(t.getTask(e.taskId),r)}function fd(t,e,n={}){if(typeof t=="string"){let r=t,s=e??{};return Promise.resolve().then(()=>(Zs(),gd)).then(({TaskRepository:o})=>ud(new o,r,s))}return ud(t,e,n)}var js,Ep,Xs,Rp,qs,Bs,Sp,id,ad,Ip,Gs,zs,Ap,Op,dd,bp,Qs=N(()=>{h();ur();xn();js=5e3,Ep=250;Xs=["crewx","claude","codex","opencode","grok","node"],Rp="INSTRUCTION_STOP_TARGET_PID_MISSING",qs="INSTRUCTION_STOP_EPOCH_MISMATCH",Bs="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Sp="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",id="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",ad="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Ip="INSTRUCTION_STOP_REQUEST_FAILED",Gs="HOST_SHUTDOWN_EPOCH_MISMATCH",zs="HOST_SHUTDOWN_WORKSPACE_MISMATCH",Ap="HOST_SHUTDOWN_TARGET_PID_MISSING",Op="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",dd="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",bp="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var gd={};ou(gd,{DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>yd,HOST_SHUTDOWN_TERMINAL_ERROR:()=>kd,PENDING_ADOPT_GRACE_MS:()=>wd,PID_NULL_REAP_GRACE_MS:()=>co,RATED_TASK_EXCERPT_MAX_CHARS:()=>lo,RATED_TASK_LIST_MAX_LIMIT:()=>Rd,TASK_HEARTBEAT_HARD_STALE_MS:()=>rd,TASK_HEARTBEAT_INTERVAL_MS:()=>td,TASK_HEARTBEAT_STALE_MS:()=>nd,TASK_RATINGS:()=>Ed,TaskRatingError:()=>Hn,TaskRepository:()=>$n,buildRatedTasksCountQuery:()=>Id,buildRatedTasksQuery:()=>Sd,countRatedTasks:()=>nf,hasRecordedUsage:()=>uo,listRatedTasks:()=>tf,mergeTerminalReason:()=>ao,resolveTaskHeartbeatHardStaleMs:()=>Sr,resolveTaskHeartbeatIntervalMs:()=>Fs,resolveTaskHeartbeatStaleMs:()=>Yt,setTaskRating:()=>ef});function He(t){return On(t)}function to(t){return On(t)}function ro(t=a.model,e=a.metadata){let n=drizzleOrm.sql`
|
|
51
|
+
`;u=`${u}${l}${d}`;}else u=n(d);if(u)return u;let c=n(i.summary)??n(xt(t.content))??n(i.output_for_prompt);return c!==void 0?c:s(o)}if(t.content!==null&&t.content!==void 0)return xt(t.content)??s(t.content);if(t.result!==null&&t.result!==void 0)return xt(t.result)??s(t.result)}function sd(t){let e=Yt(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?od(n):"Grok CLI reported an error."}function od(t){return (t.replace(kp,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function nd(t){return mp.test(t)}function yp(t){let e=Yt(t.modelUsage);return e?Object.keys(e)[0]??null:null}function Ep(t){let e=Yt(t.usage);if(!e)return null;let n=Ct(e.cache_read_input_tokens);return {inputTokens:Ct(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Ct(e.output_tokens),costUsd:Ct(t.total_cost_usd)}}function Rp(t){let e=0,n=0,r=0,s=false,o=new Set;for(let i of t.split(`
|
|
52
|
+
`).flatMap(Nn)){if(i.type!=="usage")continue;let u=Yt(i.usage);if(!u)continue;let d=ke(i.signature);if(d&&d.length>0){let l=`signature:${d}`;if(o.has(l))continue;o.add(l);}let c=Ct(u.cache_read_input_tokens);e+=Ct(u.input_tokens)+c,n+=c,r+=Ct(u.output_tokens),s=true;}return s?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function Sp(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let o of e.entries.slice(0,Za)){if(!Xt(o))continue;let i=ke(o.content)?.trim();if(!i)continue;let u=ke(o.status)?.trim(),d=ke(o.priority)?.trim(),c=[u?`status=${u}`:void 0,d?`priority=${d}`:void 0].filter(p=>!!p),l=c.length>0?` (${c.join(", ")})`:"";n.push(`- ${i}${l}`);}if(n.length===0)return [];e.entries.length>Za&&n.push(td);let r=n.join(`
|
|
53
|
+
`),s=r.length>ed?`${r.slice(0,ed-1)}${td}`:r;return [{timestamp:t,type:"info",content:s}]}function Ip(t,e){let n=ke(e.type);if(n==="thought"){let r=ke(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=ke(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return Sp(t,e);if(n==="tool_call"){let r=ke(e.toolCallId),s=ke(e.toolName)??ke(e.title),o=e.rawInput===void 0?void 0:rd(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:s,toolInput:o}]}if(n==="tool_call_update"){let r=ke(e.status);if(r!=="completed"&&r!=="failed"&&r!=="error")return [];let s=wp(e),o=r!=="completed"||e.isError===true;return [{timestamp:t,type:"tool_result",toolUseId:ke(e.toolCallId),toolName:ke(e.toolName)??ke(e.title),...s!==void 0?Le(s,o):{isError:o}}]}if(n==="error"){let r=sd(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}var Ir,_p,mp,kp,Za,ed,td,Hs,Us=v(()=>{h();At();ws();bt();jt();An();Nt();Ir="cli/grok",_p=new Set(["available_commands","usage","end"]),mp=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,kp=/\u001b\[[0-?]*[ -/]*[@-~]/g,Za=20,ed=4e3,td="\u2026";Hs={command:"grok",createSessionId:()=>crypto.randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=lt(e.model),s=e.effort??r,o=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],u=n?ct("grok").some(E=>E.id===n):false,d=n&&u?In("grok",n):[],c=!s||d.length===0||d.includes(s)?s:void 0,l=xa(c),p=e.additionalArgs??[],g=E=>p.some(I=>I===E||I.startsWith(`${E}=`)),_=e.providerOptions,m=_?.alwaysApprove,y=_?.sandbox,k=g("--permission-mode")?[]:ba(e.mode),N=g("--always-approve")?[]:Na(m),S=g("--sandbox")?[]:va(y),C=g("--verbatim")?[]:["--verbatim"];return {args:["--no-auto-update",...o,"--single",t,...C,"--output-format","streaming-json","--no-alt-screen",...i,...l,...k,...N,...S,...p]}},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
54
|
+
`).flatMap(Nn))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 Nn(t))if(e.type==="error"){let n=sd(e);return nd(rd(e))?new Ot(n,Ir):new Y(n,Ir)}return null},interpretExit(t,e){if(t===0)return null;let n=od(e)||`Grok CLI exited with code ${t}.`;return nd(e)?new Ot(n,Ir):new Y(n,Ir)},parseResultMeta(t){let n=t.split(`
|
|
55
|
+
`).flatMap(Nn).find(r=>r.type==="end");return n?{usage:Ep(n),model:yp(n)}:{usage:Rp(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return Nn(t).flatMap(r=>Ip($e(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return Xt(n)&&typeof n.type=="string"?_p.has(n.type):!1}catch{return false}}};});var id,ad=v(()=>{h();bs();vs();Cs();Ps();$s();Qa();Us();bs();vs();Cs();Ps();$s();Us();Wt();id={codex:xs,claude:Er,opencode:Ds,antigravity:Ms,copilot:Ns,grok:Hs};});function dd(t){if(t.startsWith("cli/"))return id[t.slice(4)]}var ud=v(()=>{h();aa();ad();});function Ar(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ap(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function Or(t){if(typeof t.provider!="string"||t.provider.length===0)return;let n=t.taskLogRepository.readLogs(t.taskId)?.entries.filter(g=>g.level==="stdout").map(g=>g.message).join(`
|
|
56
|
+
`)??"";if(!n.trim())return;let r=dd(t.provider);if(!r)return;let s;try{s=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let o=Ap(s?.model,t.model),i=s?.usage;if(!i)return {stdout:n,adapter:r};let u=Ar(i.inputTokens),d=Ar(i.outputTokens),c=Ar(i.cachedInputTokens),l=ji(Ar(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 Fs=v(()=>{h();ud();pr();});function Bs(t){let e=new Set;for(let n of t)for(let r of Op.get(n)??[n])e.add(r);return [...e]}function Ws(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"&&bp.has(n)?n:void 0}catch{return}}function He(t){let e=Ws(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(qs.stopped.test(t.error))return "user_stop";if(qs.runnerLost.test(t.error))return "runner_lost"}}function ve(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=Ws(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&qs.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function Np(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function xn(t){let e=ve(t);return t.status==="runner_lost"&&Ws(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...Np(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}var vn,Op,qs,bp,Cn=v(()=>{h();vn=["success","completed","done","failed","error","stopped","runner_lost"],Op=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);qs={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},bp=new Set(["user_stop","runner_lost","launch_failed"]);});function js(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 Gs(){return js("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Zt(){return js("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function Nr(){return js("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Qt(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function br(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 vp(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 cd(t,e){return !!t.stop_requested_at&&Qt(t.stop_requested_epoch)===Qt(e)}function ld(t,e){let n=Qt(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let s=vp(t.getTask(e.taskId));return !s||s.status!=="running"||Qt(s.run_epoch)!==n?{accepted:false,row:s}:{accepted:true,row:s}}function hd(t,e){let n=Dn.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),Dn.delete(t),true)}function Pn(t,e){let n=Dn.get(t);return !n||e!==void 0&&n.runEpoch!==Qt(e)?false:hd(t,n)}function _d(t,e){let n=Qt(e.runEpoch);Pn(e.taskId);let r=true,s=null;try{let c=ld(t,{...e,runEpoch:n});r=c.accepted,s=c.row;}catch(c){br(c);}if(!r)return false;let o=Gs(),i=Math.min(o,1e3),u=setInterval(()=>{let c=Dn.get(e.taskId);if(!(!c||c.timer!==u))try{c.heartbeatElapsedMs+=i;let l=c.heartbeatElapsedMs>=o,p=ld(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){hd(e.taskId,c);return}l&&(c.heartbeatElapsedMs%=o,c.lastHeartbeatAt=Date.now()),p.row&&cd(p.row,n)&&!c.stopRequested&&(c.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(br));}catch(l){br(l);}},i),d={timer:u,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return Dn.set(e.taskId,d),typeof u=="object"&&u!==null&&"unref"in u&&u.unref(),s&&cd(s,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(s)).catch(br)),true}var pd,fd,gd,Dn,Ln=v(()=>{h();pd=1e4,fd=3e4,gd=18e5;Dn=new Map;});function vr(t,e=Date.now(),n=Js){let r=t?Date.parse(t):Number.NaN,s=typeof e=="number"?e:Date.parse(e),o=Qs(n,Js,0);return Number.isFinite(r)&&Number.isFinite(s)&&s-r>o?"forced":"cooperative"}function Qs(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function yd(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function Hp(t){if(!t)return;let e=yd(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function Se(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=Hp(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function no(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 K(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 Vs(t,e){return K(t,Dp,e)}function Up(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=Zt():false}function Fp(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function qp(t){let e=typeof t.pid=="number"&&t.pid>0?t.pid:void 0,n=yd(t.metadata),r=n.ownership==="runner"&&typeof n.providerPid=="number"&&Number.isSafeInteger(n.providerPid)&&n.providerPid>0?n.providerPid:void 0;return [...new Set([e,r].filter(s=>s!==void 0))]}function Bp(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return Se(r,n)}async function Wp(t,e,n,r){let s=Date.now()+n;for(;;){let o=Bp(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 wd(t,e,n){let r=new Date().toISOString(),s={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},o=t.requestTaskStop({id:e,requestedAt:r,...s}),i=t.getTask(e);if(!o.accepted){if(o.status==="pending"){let C=t.stopPendingTask(e,void 0,void 0,{...s,at:r}),E=t.getTask(e);if(C||!E||E.status!=="running")return Se(E);if(o=t.requestTaskStop({id:e,requestedAt:r,...s}),!o.accepted&&o.status!=="running"||!o.accepted&&!o.alreadyRequestedAt)return Se(t.getTask(e))}else if(!(o.status==="running"&&o.alreadyRequestedAt))return Se(i)}let u=o.runEpoch,d=Qs(n.graceMs,Js,0),c=Qs(n.pollMs,xp,1),l=await Wp(t,e,d,c);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return Se(p);let g=qp(p),_=g[0];if(!_){let C=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),E=t.getTask(e);return C||E?.status!=="running"?Se(E):K(E,"Failed to finalize task stop")}let m=Fp(n),y="unknown";if(!Up(p,Date.now())){let C=n.processControl?.checkProcessOwnershipAsync??fr;try{y=await C(_,n.ownershipMarkers??to,m);}catch{y="unknown";}if(y!=="owned")return no(p)}let k=n.processControl?.terminateProcessTree??qt;for(let C of g){let E;try{E=await k(C,{...m,signal:Ft});}catch(I){E={status:"failed",pid:C,method:m.platform==="win32"?"taskkill":"process-group",error:I instanceof Error?I.message:String(I)};}if(E.status==="failed")return K(t.getTask(e),E.error??"Failed to terminate process tree")}let N=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),S=t.getTask(e);return N||S?.status!=="running"?Se(S,_):K(S,"Task changed before stop was finalized")}function Zs(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function eo(t){return Number.isSafeInteger(t)&&t>=0}function Mn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function jp(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Gp(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function zp(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 Kp(t){switch(t){case "epoch_mismatch":return Xs;case "workspace_mismatch":return Ys;default:return}}async function Ed(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Vs(n,Zs(e.targetPid)?e.targetPid:void 0);if(!eo(e.sourceRunEpoch)||!eo(e.settleRunEpoch)||Mn(n.run_epoch)!==e.settleRunEpoch)return K(n,zs,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return K(n,Ks,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 K(n,Pp,e.targetPid)}let o=t.getTask(e.taskId);if(!o||o.status!=="running")return Vs(o,e.targetPid);if(s.runEpoch!==e.settleRunEpoch||Mn(o.run_epoch)!==e.settleRunEpoch)return K(o,zs,e.targetPid);if(e.workspaceId!==void 0&&o.workspace_id!==e.workspaceId)return K(o,Ks,e.targetPid);if(!Zs(e.targetPid))return K(o,Cp);let i=jp(e),u=e.processControl?.checkProcessOwnershipAsync??fr,d="unknown";try{d=await u(e.targetPid,e.ownershipMarkers??to,i);}catch{d="unknown";}if(d!=="owned")return no(o,e.targetPid);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return Vs(c,e.targetPid);if(Mn(c.run_epoch)!==e.settleRunEpoch)return K(c,zs,e.targetPid);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return K(c,Ks,e.targetPid);let l=e.processControl?.terminateProcessTree??qt,p;try{p=await l(e.targetPid,{...i,signal:Ft});}catch{return K(t.getTask(e.taskId),md,e.targetPid)}if(p.status==="failed")return K(t.getTask(e.taskId),md,e.targetPid);let g;try{g=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return K(t.getTask(e.taskId),kd,e.targetPid)}return g?Se(t.getTask(e.taskId),e.targetPid):K(t.getTask(e.taskId),kd,e.targetPid)}async function Rd(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Se(n);if(!eo(e.expectedRunEpoch)||Mn(n.run_epoch)!==e.expectedRunEpoch)return K(n,Xs);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return K(n,Ys);let r=n.pid;if(!Zs(r))return K(n,Lp);let s=Gp(e),o=e.processControl?.checkProcessOwnershipAsync??fr,i="unknown";try{i=await o(r,e.ownershipMarkers??to,s);}catch{i="unknown";}if(i!=="owned")return no(n,r,Mp);let u=e.processControl?.terminateProcessTree??qt,d;try{d=await u(r,{...s,signal:Ft});}catch{return K(t.getTask(e.taskId),Td,r)}if(d.status==="failed")return K(t.getTask(e.taskId),Td,r);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return Se(c,r);if(Mn(c.run_epoch)!==e.expectedRunEpoch)return K(c,Xs,r);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return K(c,Ys,r);let l;try{l=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return K(t.getTask(e.taskId),$p,r)}let p=Kp(l);return p?K(t.getTask(e.taskId),p,r):l!=="settled"?Se(t.getTask(e.taskId),r):zp(t.getTask(e.taskId),r)}function Sd(t,e,n={}){if(typeof t=="string"){let r=t,s=e??{};return Promise.resolve().then(()=>(so(),Id)).then(({TaskRepository:o})=>wd(new o,r,s))}return wd(t,e,n)}var Js,xp,to,Cp,zs,Ks,Dp,md,kd,Pp,Xs,Ys,Lp,Mp,Td,$p,ro=v(()=>{h();gr();Ln();Js=5e3,xp=250;to=["crewx","claude","codex","opencode","grok","node"],Cp="INSTRUCTION_STOP_TARGET_PID_MISSING",zs="INSTRUCTION_STOP_EPOCH_MISMATCH",Ks="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Dp="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",md="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",kd="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Pp="INSTRUCTION_STOP_REQUEST_FAILED",Xs="HOST_SHUTDOWN_EPOCH_MISMATCH",Ys="HOST_SHUTDOWN_WORKSPACE_MISMATCH",Lp="HOST_SHUTDOWN_TARGET_PID_MISSING",Mp="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",Td="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",$p="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var Id={};gu(Id,{DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>Cd,HOST_SHUTDOWN_TERMINAL_ERROR:()=>Nd,PENDING_ADOPT_GRACE_MS:()=>xd,PID_NULL_REAP_GRACE_MS:()=>ho,RATED_TASK_EXCERPT_MAX_CHARS:()=>_o,RATED_TASK_LIST_MAX_LIMIT:()=>Pd,TASK_HEARTBEAT_HARD_STALE_MS:()=>gd,TASK_HEARTBEAT_INTERVAL_MS:()=>pd,TASK_HEARTBEAT_STALE_MS:()=>fd,TASK_RATINGS:()=>Dd,TaskRatingError:()=>Bn,TaskRepository:()=>qn,buildRatedTasksCountQuery:()=>Md,buildRatedTasksQuery:()=>Ld,countRatedTasks:()=>pf,hasRecordedUsage:()=>go,listRatedTasks:()=>lf,mergeTerminalReason:()=>fo,resolveTaskHeartbeatHardStaleMs:()=>Nr,resolveTaskHeartbeatIntervalMs:()=>Gs,resolveTaskHeartbeatStaleMs:()=>Zt,setTaskRating:()=>cf});function Fe(t){return xn(t)}function io(t){return xn(t)}function uo(t=a.model,e=a.metadata){let n=drizzleOrm.sql`
|
|
57
57
|
CASE
|
|
58
58
|
WHEN ${t} LIKE 'claude-%' OR ${t} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
59
59
|
WHEN ${t} LIKE 'gpt-%' OR ${t} LIKE 'codex-%' THEN 'codex'
|
|
@@ -82,7 +82,7 @@ ${r.join(`
|
|
|
82
82
|
WHEN trim(${i}) = '' THEN 'unknown'
|
|
83
83
|
ELSE ${i}
|
|
84
84
|
END
|
|
85
|
-
`}function
|
|
85
|
+
`}function tf(t){let e={status:t.status,metadata:t.metadata},n=ve(e);return n==="stopped"||n==="failed"&&He(e)==="runner_lost"}function Fn(t){return drizzleOrm.sql`${t} NOT IN (${drizzleOrm.sql.join(nf.map(e=>drizzleOrm.sql`${e}`),drizzleOrm.sql`, `)})`}function xr(t){let e=drizzleOrm.sql`
|
|
86
86
|
CASE
|
|
87
87
|
WHEN json_valid(${t}) = 1
|
|
88
88
|
THEN json_extract(${t}, '$.usageAccounting')
|
|
@@ -92,7 +92,7 @@ ${r.join(`
|
|
|
92
92
|
COALESCE(SUM(
|
|
93
93
|
CASE WHEN ${e} = 'unavailable' THEN 1 ELSE 0 END
|
|
94
94
|
), 0)
|
|
95
|
-
`}function
|
|
95
|
+
`}function rn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ne(t){if(!t)return {};try{let e=JSON.parse(t);return rn(e)?{...e}:{}}catch{return {}}}function Lr(t){return t==null||t===""}function Cr(t,e){return Lr(t)&&!Lr(e)?e:t}function rf(t,e){let n=ne(t);if(!e)return n;for(let[r,s]of Object.entries(e))Lr(n[r])&&!Lr(s)&&(n[r]=s);return n}function Dr(t,e){let n=t.origin&&vd.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 sf(t){let e=ne(t).stopRequest;if(rn(e)&&!(typeof e.origin!="string"||!vd.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function Od(){return drizzleOrm.or(drizzleOrm.isNull(a.stop_requested_at),drizzleOrm.ne(drizzleOrm.sql`COALESCE(${a.stop_requested_epoch}, 0)`,drizzleOrm.sql`COALESCE(${a.run_epoch}, 0)`))}function fo(t,e){let n=ne(t??null);return n.terminalReason=e,JSON.stringify(n)}function lo(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==Ad&&(n[ef]=e),{error:Ad,metadata:n}}function ae(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function go(t){return ae(t.input_tokens)!==0||ae(t.output_tokens)!==0||ae(t.cached_input_tokens)!==0||ae(t.cost_usd)!==0}function W(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function bd(t){return {inputTokens:ae(t.inputTokens??0),outputTokens:ae(t.outputTokens??0),cachedInputTokens:ae(t.cachedInputTokens??0),costUsd:ae(t.costUsd??0)}}function of(t){if(rn(t))return {inputTokens:ae(t.inputTokens),outputTokens:ae(t.outputTokens),cachedInputTokens:ae(t.cachedInputTokens),costUsd:ae(t.costUsd)}}function af(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=of(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function Pr(t,e,n){let r=Date.parse(t),s=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(s)?s-r:n??null}function sn(t,e){if(typeof t!="string"||t.length===0)throw new f("VALIDATION",`${e} is required`);return t}function mo(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 cf(t,e){let n=sn(e.workspaceId,"workspaceId"),r=sn(e.taskId,"taskId"),s=e.rating;if(s!==null&&!Dd.includes(s))throw new f("VALIDATION","rating must be 'up', 'down' or null");let o=e.now===void 0?new Date().toISOString():mo(e.now,"now");try{return t.transaction(i=>{let u=drizzleOrm.and(drizzleOrm.eq(a.id,r),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,[...vn])),d=i.update(a).set({rating:s,rated_at:s===null?null:o}).where(drizzleOrm.and(u,drizzleOrm.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 c=i.select({status:a.status,rating:a.rating,rated_at:a.rated_at}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,r),drizzleOrm.eq(a.workspace_id,n))).limit(1).get();if(!c)throw new Bn("TASK_NOT_FOUND",r);if(!uf.has(c.status))throw new Bn("TASK_RATING_NOT_TERMINAL",r);return {taskId:r,rating:c.rating,ratedAt:c.rated_at,changed:!1}},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to set task rating",i)}}function Ld(t){let e=drizzleOrm.sql`
|
|
96
96
|
SELECT id, rated_at FROM tasks
|
|
97
97
|
WHERE workspace_id = ${t.workspaceId}
|
|
98
98
|
AND rating IS NOT NULL
|
|
@@ -102,41 +102,41 @@ ${r.join(`
|
|
|
102
102
|
LIMIT ${t.limit}
|
|
103
103
|
`;return drizzleOrm.sql`
|
|
104
104
|
SELECT t.id AS taskId, t.agent_id AS agentId, t.thread_id AS threadId, t.status AS status,
|
|
105
|
-
substr(t.error, 1, ${
|
|
105
|
+
substr(t.error, 1, ${df}) AS errorHead,
|
|
106
106
|
CASE WHEN json_valid(t.metadata) THEN json_extract(t.metadata, '$.terminalReason') END AS terminalReason,
|
|
107
107
|
t.rating AS rating, t.rated_at AS ratedAt,
|
|
108
|
-
NULLIF(substr(t.prompt, 1, ${
|
|
109
|
-
NULLIF(substr(t.result, 1, ${
|
|
108
|
+
NULLIF(substr(t.prompt, 1, ${_o}), '') AS promptExcerpt,
|
|
109
|
+
NULLIF(substr(t.result, 1, ${_o}), '') AS resultExcerpt
|
|
110
110
|
FROM (${e}) AS page
|
|
111
111
|
JOIN tasks t ON t.id = page.id
|
|
112
112
|
ORDER BY page.rated_at DESC, page.id DESC
|
|
113
|
-
`}function
|
|
113
|
+
`}function lf(t,e){let n=sn(e.workspaceId,"workspaceId");if(e.agentId!==void 0&&sn(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),Pd),s=e.sinceIso===void 0?void 0:mo(e.sinceIso,"sinceIso");try{return t.all(Ld({workspaceId:n,agentId:e.agentId,sinceIso:s,limit:r})).map(i=>({taskId:i.taskId,agentId:i.agentId,threadId:i.threadId,status:ve({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 Md(t){return drizzleOrm.sql`
|
|
114
114
|
SELECT COUNT(*) AS total FROM tasks
|
|
115
115
|
WHERE workspace_id = ${t.workspaceId}
|
|
116
116
|
AND rating IS NOT NULL
|
|
117
117
|
${t.agentId!==void 0?drizzleOrm.sql`AND agent_id = ${t.agentId}`:drizzleOrm.sql``}
|
|
118
118
|
${t.sinceIso!==void 0?drizzleOrm.sql`AND rated_at >= ${t.sinceIso}`:drizzleOrm.sql``}
|
|
119
|
-
`}function nf(t,e){let n=nn(e.workspaceId,"workspaceId");e.agentId!==void 0&&nn(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:po(e.sinceIso,"sinceIso");try{return t.all(Id({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 no,Qt,Wp,Zt,en,jp,so,Ln,Ue,hd,kd,Gp,Kp,Td,co,wd,yd,$n,Ed,lo,Rd,Qp,Hn,Zp,Zs=N(()=>{h();it();_t();mt();ot();Et();ar();ur();Ki();Ji();Ls();bn();xn();Qs();xn();no=40,Qt="2026-05-09",Wp="0.8.9-rc.13",Zt=10,en=parseInt(Wp.split("rc.")[1]);jp=new Set(["workflow","mcp"]),so="usageByEpoch",Ln="lateUsage",Ue="usageAccounting",hd="Stopped by user",kd="Stopped by app shutdown",Gp="terminalErrorOriginal";Kp=["pending","running"];Td=new Set(["http","cli","instruction","workflow","internal"]);co=600*1e3,wd=600*1e3,yd=300*1e3,$n=class extends ge{dbPath;clock;taskLogRepository;lastReaperTickAt;pidNullObservedSince=new Map;constructor(e={}){super(),this.clock=e.clock??(()=>Date.now()),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=de.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new cr({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?ht(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=de.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}else if(!fs$1.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=H(n);if(e)try{Ie(r.db,n);}catch(s){throw r.close(),s}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=W(e.runEpoch),s=r===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,r);return n.db.update(a).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),s,drizzleOrm.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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=W(o.run_epoch);if(o.status!=="running"){r={accepted:!1,status:o.status,runEpoch:i};return}let u=o.stop_requested_at!==null&&W(o.stop_requested_epoch)===i,d=u?o.stop_requested_at:e.requestedAt,c=te(o.metadata),l=u?Jp(o.metadata)??br({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):br({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:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...c,stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),_d())).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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:W(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:W(m.run_epoch),...m.stop_requested_at&&W(m.stop_requested_epoch)===W(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:o.status,runEpoch:i};let g=new Set([e.id]),_=(m,y)=>{if(y>=8)return;let k=s.select({id:a.id,status:a.status,metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.parent_task_id,m),drizzleOrm.eq(a.status,"running"))).all();for(let v of k)g.has(v.id)||(g.add(v.id),s.update(a).set({stop_requested_at:d,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...te(v.metadata),stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,v.id),drizzleOrm.eq(a.status,"running"),_d())).run(),_(v.id,y+1));};_(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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=W(o.run_epoch),u=W(e.sourceRunEpoch),d=W(e.settleRunEpoch);if(o.status!=="running"||i!==d||e.workspaceId!==void 0&&o.workspace_id!==e.workspaceId){r={accepted:!1,status:o.status,runEpoch:i};return}let c=d===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,d),l=drizzleOrm.or(drizzleOrm.isNull(a.stop_requested_at),drizzleOrm.isNull(a.stop_requested_epoch),drizzleOrm.ne(a.stop_requested_epoch,u)),p=br({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),g=k=>s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:u,metadata:JSON.stringify({...te(o.metadata),stopRequest:p})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),c,k,l)).run();if((e.workspaceId===void 0?g():e.workspaceId===null?g(drizzleOrm.isNull(a.workspace_id)):g(drizzleOrm.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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:W(m?.run_epoch)};return}let y=W(m.run_epoch);r={accepted:!1,status:m.status,runEpoch:y,...m.stop_requested_at&&W(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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||W(i.run_epoch)!==W(e.runEpoch))return;let u=i.stop_requested_at!==null&&W(i.stop_requested_epoch)===W(e.runEpoch),d=te(i.metadata),c=u?oo(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??vr(i.started_at,r,void 0),g=i.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.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(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.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=W(e.expectedRunEpoch),o="not_running";return n.db.transaction(i=>{let u=i.select({status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!u||u.status!=="running"){o="not_running";return}if(W(u.run_epoch)!==s){o="epoch_mismatch";return}if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId){o="workspace_mismatch";return}let c=u.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,u.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?drizzleOrm.isNull(a.workspace_id):drizzleOrm.eq(a.workspace_id,e.workspaceId),p={...te(u.metadata),terminalReason:"runner_lost"},g=u.duration_ms??vr(u.started_at,r,void 0);o=i.update(a).set({status:"failed",error:kd,completed_at:r,duration_ms:g,metadata:JSON.stringify(p)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.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 fd(this,e,n)}async stopTaskGenerationForInstruction(e){return ld({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(drizzleOrm.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,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,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:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN 'running' ELSE ${a.status} END`,pid:drizzleOrm.sql`COALESCE(excluded.pid, ${a.pid})`,actor_kind:drizzleOrm.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:drizzleOrm.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:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.command ELSE ${a.command} END`,metadata:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.metadata ELSE ${a.metadata} END`,workspace_id:drizzleOrm.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:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.cwd}, excluded.cwd) ELSE ${a.cwd} END`,project_id:drizzleOrm.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:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.crewx_version ELSE ${a.crewx_version} END`,model:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.model ELSE ${a.model} END`,rendered_prompt:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.rendered_prompt ELSE ${a.rendered_prompt} END`,security_key:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.security_key ELSE ${a.security_key} END`,coding_agent_command:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.coding_agent_command ELSE ${a.coding_agent_command} END`},setWhere:drizzleOrm.or(drizzleOrm.eq(a.status,"running"),drizzleOrm.and(drizzleOrm.eq(a.status,"pending"),drizzleOrm.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|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(ru=>ru.name)),l=c.has("cwd"),p=c.has("user_id"),g=c.has("actor_kind"),_=c.has("actor_id"),m=c.has("log_storage"),y=l?", cwd":"",k=l?", ?":"",v=l?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",S=m?", log_storage":"",C=m?", ?":"",E=p?", user_id":"",I=p?", ?":"",b=g?", actor_kind":"",Q=g?", ?":"",fe=_?", actor_id":"",zr=_?", ?":"",nu=m?`,
|
|
119
|
+
`}function pf(t,e){let n=sn(e.workspaceId,"workspaceId");e.agentId!==void 0&&sn(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:mo(e.sinceIso,"sinceIso");try{return t.all(Md({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,en,Qp,tn,nn,Zp,co,Un,qe,Ad,Nd,ef,nf,vd,ho,xd,Cd,qn,Dd,_o,Pd,df,Bn,uf,so=v(()=>{h();at();mt();kt();it();St();pr();gr();sa();ia();Fs();Cn();Ln();ro();Ln();ao=40,en="2026-05-09",Qp="0.8.9-rc.13",tn=10,nn=parseInt(Qp.split("rc.")[1]);Zp=new Set(["workflow","mcp"]),co="usageByEpoch",Un="lateUsage",qe="usageAccounting",Ad="Stopped by user",Nd="Stopped by app shutdown",ef="terminalErrorOriginal";nf=["pending","running"];vd=new Set(["http","cli","instruction","workflow","internal"]);ho=600*1e3,xd=600*1e3,Cd=300*1e3,qn=class extends _e{dbPath;clock;taskLogRepository;lastReaperTickAt;pidNullObservedSince=new Map;constructor(e={}){super(),this.clock=e.clock??(()=>Date.now()),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ce.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new hr({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?_t(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=ce.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}else if(!fs$1.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=$(n);if(e)try{Oe(r.db,n);}catch(s){throw r.close(),s}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=W(e.runEpoch),s=r===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,r);return n.db.update(a).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),s,drizzleOrm.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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=W(o.run_epoch);if(o.status!=="running"){r={accepted:!1,status:o.status,runEpoch:i};return}let u=o.stop_requested_at!==null&&W(o.stop_requested_epoch)===i,d=u?o.stop_requested_at:e.requestedAt,c=ne(o.metadata),l=u?sf(o.metadata)??Dr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):Dr({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:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...c,stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),Od())).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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:W(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:W(m.run_epoch),...m.stop_requested_at&&W(m.stop_requested_epoch)===W(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:o.status,runEpoch:i};let g=new Set([e.id]),_=(m,y)=>{if(y>=8)return;let k=s.select({id:a.id,status:a.status,metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.parent_task_id,m),drizzleOrm.eq(a.status,"running"))).all();for(let N of k)g.has(N.id)||(g.add(N.id),s.update(a).set({stop_requested_at:d,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...ne(N.metadata),stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,N.id),drizzleOrm.eq(a.status,"running"),Od())).run(),_(N.id,y+1));};_(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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=W(o.run_epoch),u=W(e.sourceRunEpoch),d=W(e.settleRunEpoch);if(o.status!=="running"||i!==d||e.workspaceId!==void 0&&o.workspace_id!==e.workspaceId){r={accepted:!1,status:o.status,runEpoch:i};return}let c=d===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,d),l=drizzleOrm.or(drizzleOrm.isNull(a.stop_requested_at),drizzleOrm.isNull(a.stop_requested_epoch),drizzleOrm.ne(a.stop_requested_epoch,u)),p=Dr({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),g=k=>s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:u,metadata:JSON.stringify({...ne(o.metadata),stopRequest:p})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),c,k,l)).run();if((e.workspaceId===void 0?g():e.workspaceId===null?g(drizzleOrm.isNull(a.workspace_id)):g(drizzleOrm.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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:W(m?.run_epoch)};return}let y=W(m.run_epoch);r={accepted:!1,status:m.status,runEpoch:y,...m.stop_requested_at&&W(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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||W(i.run_epoch)!==W(e.runEpoch))return;let u=i.stop_requested_at!==null&&W(i.stop_requested_epoch)===W(e.runEpoch),d=ne(i.metadata),c=u?lo(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??Pr(i.started_at,r,void 0),g=i.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.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(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.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=W(e.expectedRunEpoch),o="not_running";return n.db.transaction(i=>{let u=i.select({status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!u||u.status!=="running"){o="not_running";return}if(W(u.run_epoch)!==s){o="epoch_mismatch";return}if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId){o="workspace_mismatch";return}let c=u.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,u.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?drizzleOrm.isNull(a.workspace_id):drizzleOrm.eq(a.workspace_id,e.workspaceId),p={...ne(u.metadata),terminalReason:"runner_lost"},g=u.duration_ms??Pr(u.started_at,r,void 0);o=i.update(a).set({status:"failed",error:Nd,completed_at:r,duration_ms:g,metadata:JSON.stringify(p)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.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 Sd(this,e,n)}async stopTaskGenerationForInstruction(e){return Ed({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(drizzleOrm.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,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,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:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN 'running' ELSE ${a.status} END`,pid:drizzleOrm.sql`COALESCE(excluded.pid, ${a.pid})`,actor_kind:drizzleOrm.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:drizzleOrm.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:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.command ELSE ${a.command} END`,metadata:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.metadata ELSE ${a.metadata} END`,workspace_id:drizzleOrm.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:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.cwd}, excluded.cwd) ELSE ${a.cwd} END`,project_id:drizzleOrm.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:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.crewx_version ELSE ${a.crewx_version} END`,model:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.model ELSE ${a.model} END`,rendered_prompt:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.rendered_prompt ELSE ${a.rendered_prompt} END`,security_key:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.security_key ELSE ${a.security_key} END`,coding_agent_command:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.coding_agent_command ELSE ${a.coding_agent_command} END`},setWhere:drizzleOrm.or(drizzleOrm.eq(a.status,"running"),drizzleOrm.and(drizzleOrm.eq(a.status,"pending"),drizzleOrm.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|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(pu=>pu.name)),l=c.has("cwd"),p=c.has("user_id"),g=c.has("actor_kind"),_=c.has("actor_id"),m=c.has("log_storage"),y=l?", cwd":"",k=l?", ?":"",N=l?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",S=m?", log_storage":"",C=m?", ?":"",E=p?", user_id":"",I=p?", ?":"",b=g?", actor_kind":"",Q=g?", ?":"",he=_?", actor_id":"",Xr=_?", ?":"",lu=m?`,
|
|
120
120
|
log_storage = CASE WHEN tasks.status = 'pending' THEN excluded.log_storage ELSE tasks.log_storage END`:"";n.runRaw(`INSERT INTO tasks (
|
|
121
121
|
id, agent_id, prompt, mode, status, started_at, pid,
|
|
122
122
|
parent_task_id, caller_agent_id, trace_id, command, metadata,
|
|
123
123
|
workspace_id${y}, project_id, platform, crewx_version, thread_id,
|
|
124
|
-
model, rendered_prompt, coding_agent_command${E}${b}${
|
|
125
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${k}${I}${Q}${
|
|
124
|
+
model, rendered_prompt, coding_agent_command${E}${b}${he}${S}
|
|
125
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${k}${I}${Q}${Xr}${C})
|
|
126
126
|
ON CONFLICT(id) DO UPDATE SET
|
|
127
127
|
status = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN 'running' ELSE tasks.status END,
|
|
128
128
|
pid = COALESCE(excluded.pid, tasks.pid),
|
|
129
129
|
command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.command ELSE tasks.command END,
|
|
130
130
|
metadata = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.metadata ELSE tasks.metadata END,
|
|
131
|
-
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${
|
|
131
|
+
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${N},
|
|
132
132
|
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,
|
|
133
133
|
crewx_version = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.crewx_version ELSE tasks.crewx_version END,
|
|
134
134
|
model = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.model ELSE tasks.model END,
|
|
135
135
|
rendered_prompt = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.rendered_prompt ELSE tasks.rendered_prompt END,
|
|
136
|
-
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${
|
|
137
|
-
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]:[],...g?[o.actor_kind]:[],..._?[o.actor_id]:[],...m?[o.log_storage]:[]]);}r&&!s&&new
|
|
138
|
-
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(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"),drizzleOrm.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(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.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(u=>{let d=u.select({metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).limit(1).get();if(!d)return;let c=
|
|
139
|
-
`);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.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=
|
|
136
|
+
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${lu}
|
|
137
|
+
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]:[],...g?[o.actor_kind]:[],..._?[o.actor_id]:[],...m?[o.log_storage]:[]]);}r&&!s&&new _r({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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||W(r.run_epoch)!==W(e.runEpoch))return !1;let s=r.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,r.run_epoch);return n.db.update(a).set({pid:e.pid}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||W(r.run_epoch)!==W(e.runEpoch))return !1;let s=rf(r.metadata,e.runtime?.metadata);s.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0&&(s.providerPid=e.providerPid);let o=r.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,r.run_epoch),i=n.db.update(a).set({metadata:JSON.stringify(s),model:Cr(r.model,e.runtime?.model),rendered_prompt:Cr(r.rendered_prompt,e.runtime?.renderedPrompt),security_key:Cr(r.security_key,e.runtime?.securityKey),coding_agent_command:Cr(r.coding_agent_command,e.runtime?.codingAgentCommand)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),o)).run();return i.changes>0&&W(e.runEpoch)>0&&n.db.update(a).set({stop_requested_at:null,stop_requested_epoch:null}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),o,drizzleOrm.sql`${a.stop_requested_at} IS NOT NULL
|
|
138
|
+
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(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"),drizzleOrm.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(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.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(u=>{let d=u.select({metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).limit(1).get();if(!d)return;let c=lo(ne(d.metadata),n),l={...c.metadata,stopMethod:"cooperative",stopRequest:Dr(s,r)};i=u.update(a).set({status:"stopped",error:c.error,completed_at:r,metadata:JSON.stringify(l)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.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(te).from(a).where(drizzleOrm.eq(a.project_id,e)).orderBy(drizzleOrm.desc(a.started_at)).all().map(Fe)}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(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i)return;let u=W(i.run_epoch),d=W(e.runEpoch),c=i.status==="running"&&u===d,l=i.stop_requested_at!==null&&W(i.stop_requested_epoch)===u,p=c&&l,g=i.status==="stopped"&&u===d&&l,_=ne(i.metadata),m=rn(_[Un])?_[Un]:{},y=String(d),k=tf(i),N=k&&u===d&&!go(i)&&!Object.prototype.hasOwnProperty.call(m,y),S=k&&u===d&&!Object.prototype.hasOwnProperty.call(m,y),C=u>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||u!==d,E={},I;if(i.status!=="running"&&(r=i.status,s=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),C&&(i.status==="running"||S)){I=ne(i.metadata);let b=rn(I[co])?{...I[co]}:{};b[String(d)]=bd(e),I[co]=b;let Q=af(b),he=Q.inputTokens!==0||Q.outputTokens!==0||Q.cachedInputTokens!==0||Q.costUsd!==0;he&&_[qe]==="unavailable"?I[qe]="recorded":i.status!=="running"&&!he&&_[qe]===void 0&&(I[qe]="unavailable"),E.metadata=JSON.stringify(I),E.input_tokens=Q.inputTokens,E.output_tokens=Q.outputTokens,E.cached_input_tokens=Q.cachedInputTokens,E.cost_usd=Q.costUsd;}else if(c||N)if(c)E.input_tokens=ae(e.inputTokens??0),E.output_tokens=ae(e.outputTokens??0),E.cached_input_tokens=ae(e.cachedInputTokens??0),E.cost_usd=ae(e.costUsd??0);else {let b=bd(e),Q=b.inputTokens!==0||b.outputTokens!==0||b.cachedInputTokens!==0||b.costUsd!==0;Q&&(E.input_tokens=b.inputTokens,E.output_tokens=b.outputTokens,E.cached_input_tokens=b.cachedInputTokens,E.cost_usd=b.costUsd),I={..._};let he=rn(_[Un])?{..._[Un]}:{};he[y]={at:e.completedAt},I[Un]=he,I[qe]===void 0?I[qe]=Q?"recorded":"unavailable":Q&&I[qe]==="unavailable"&&(I[qe]="recorded"),E.metadata=JSON.stringify(I);}if((c||N)&&e.model!==void 0&&e.model!==null&&(!N||i.model===null)&&(E.model=e.model),p){I??=ne(i.metadata);let b=lo(I,e.error);I={...b.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:vr(i.stop_requested_at,e.completedAt)},E.status="stopped",E.result=e.result??i.result,E.error=b.error,E.completed_at=e.completedAt,E.duration_ms=i.duration_ms??e.durationMs??Pr(i.started_at,e.completedAt,void 0),E.exit_code=e.exitCode??i.exit_code,E.metadata=JSON.stringify(I);}else if(c)e.partialResultRecovered===!0&&(I??=ne(i.metadata),I.partialResultRecovered=!0,E.metadata=JSON.stringify(I)),E.status=e.status,E.result=e.result??null,E.error=e.error??null,E.completed_at=e.completedAt,E.duration_ms=u>0?Pr(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,E.exit_code=e.exitCode??null;else if(g){let b=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(E.result=e.result,b=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(E.exit_code=e.exitCode),e.partialResultRecovered===!0&&(I??=ne(i.metadata),I.partialResultRecovered=!0,E.metadata=JSON.stringify(I)),b&&(r=void 0,s=void 0);}Object.keys(E).length>0&&o.update(a).set(E).where(drizzleOrm.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
|
|
139
|
+
`);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.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=ne(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(te).from(a).where(drizzleOrm.eq(a.status,"running")).orderBy(drizzleOrm.desc(a.started_at)).all().map(Fe)}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(te).from(a).where(drizzleOrm.inArray(a.status,["pending","running"])).orderBy(drizzleOrm.desc(a.started_at)).all().map(Fe)}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(te).from(a).orderBy(drizzleOrm.desc(a.started_at)).limit(100).all().map(Fe)}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(drizzleOrm.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=W(e.runEpoch);if(n===0&&e.interceptedRequest!==true)return false;let r=e.recordedAt??new Date(this.clock()).toISOString(),s=this.openHandle(true);try{let o=!1;return s.db.transaction(i=>{let u=i.select({run_epoch:a.run_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!u||W(u.run_epoch)!==n)return;o=i.insert(tt).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(drizzleOrm.eq(a.id,e)).limit(1).get();if(!s)return [];let o=W(s.run_epoch),i=r.db.select({run_epoch:tt.run_epoch,key_wrap_skipped:tt.key_wrap_skipped}).from(tt).where(drizzleOrm.eq(tt.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(tt).where(drizzleOrm.and(drizzleOrm.eq(tt.task_id,e),drizzleOrm.eq(tt.run_epoch,W(n)))).limit(1).get();return s?{runEpoch:s.run_epoch,input:s.input,keyWrapSkipped:s.key_wrap_skipped===1,recordedAt:s.recorded_at}:void 0}catch(s){throw new 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(te).from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get();return r?Fe(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={}){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,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(drizzleOrm.or(drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.status,"pending"))).all(),s=this.clock(),o=Math.max(1,Math.trunc(e.tickIntervalMs??Cd)),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=Zt(),l=Nr(),p=new Date(s-xd).toISOString(),g=new Date(s).toISOString(),_=new Set,m=0,y=(k,N)=>{let S=ne(fo(k.metadata,"runner_lost")),C=typeof S.provider=="string"?S.provider:void 0,E;try{E=Or({taskLogRepository:this.taskLogRepository,taskId:k.id,provider:C,model:k.model})?.usage;}catch{}let I={status:"failed",error:N,completed_at:g};E?(I.input_tokens=E.inputTokens,I.output_tokens=E.outputTokens,I.cached_input_tokens=E.cachedInputTokens,I.cost_usd=E.costUsd,k.model===null&&E.model!==null&&(I.model=E.model),S[qe]="recorded"):!go(k)&&S[qe]!=="recorded"&&(S[qe]="unavailable"),I.metadata=JSON.stringify(S);let b=k.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,k.run_epoch),Q=k.heartbeat_at===null?drizzleOrm.isNull(a.heartbeat_at):drizzleOrm.eq(a.heartbeat_at,k.heartbeat_at),he=n.db.update(a).set(I).where(drizzleOrm.and(drizzleOrm.eq(a.id,k.id),drizzleOrm.eq(a.status,"running"),b,Q)).run();return he.changes>0&&m++,he.changes>0};for(let k of r){if(k.status==="pending"){if(k.pid!==null||k.started_at>=p)continue;let E=fo(k.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:g,metadata:E}).where(drizzleOrm.and(drizzleOrm.eq(a.id,k.id),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,p))).run().changes>0&&m++;continue}if(Zp.has(k.platform??"cli"))continue;if(k.pid===null){let E=`${k.id}:${k.run_epoch??0}`;_.add(E);let I=this.pidNullObservedSince.get(E);if(I===void 0){this.pidNullObservedSince.set(E,s);continue}s-I>=ho&&y(k,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(E);continue}if(k.heartbeat_at===null){It(k.pid)==="not_found"&&y(k,"Reaped: process not found (orphaned task)");continue}let N=Date.parse(k.heartbeat_at),S=Number.isFinite(N)?s-N:Number.POSITIVE_INFINITY;if(S<=c)continue;It(k.pid)==="not_found"?y(k,"Reaped: process not found (orphaned task)"):S>l&&d&&y(k,"Reaped: heartbeat stale beyond hard limit (orphaned task)");}for(let k of Array.from(this.pidNullObservedSince.keys()))_.has(k)||this.pidNullObservedSince.delete(k);return m}finally{n.close();}}reapRunningWorkflowTasks(e=ho){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),s=drizzleOrm.and(drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,r),drizzleOrm.or(drizzleOrm.isNull(a.metadata),drizzleOrm.and(drizzleOrm.notLike(a.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(a.metadata,'%"kind":"workflow_ui_instance"%')))),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=ne(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(drizzleOrm.and(drizzleOrm.eq(a.id,d.id),drizzleOrm.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(!fs$1.existsSync(s))continue;let o=$(s);try{let i=n?drizzleOrm.eq(a.workspace_id,n):void 0,u=i?drizzleOrm.and(drizzleOrm.eq(a.id,e),i):drizzleOrm.eq(a.id,e),d=o.db.select(te).from(a).where(u).limit(1).get()??void 0;if(!d){let c=i?drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),i):drizzleOrm.eq(a.thread_id,e);d=o.db.select(te).from(a).where(c).orderBy(drizzleOrm.desc(a.started_at)).limit(1).get()??void 0;}if(d)return Fe(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(!fs$1.existsSync(i))continue;let u=$(i);try{let d=n?drizzleOrm.and(drizzleOrm.eq(a.parent_task_id,e),drizzleOrm.eq(a.workspace_id,n)):drizzleOrm.eq(a.parent_task_id,e),c=u.db.select(te).from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of c)s.has(l.id)||(s.add(l.id),o.push(Fe(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?drizzleOrm.sql`
|
|
140
140
|
SELECT
|
|
141
141
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
142
142
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -157,14 +157,14 @@ ${r.join(`
|
|
|
157
157
|
FROM tasks
|
|
158
158
|
GROUP BY workspace_id
|
|
159
159
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
160
|
-
`)}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,u=0;for(let d of r){if(!fs$1.existsSync(d))continue;let c
|
|
160
|
+
`)}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,u=0;for(let d of r){if(!fs$1.existsSync(d))continue;let c=$(d);try{let l=drizzleOrm.eq(a.thread_id,e),p=n?drizzleOrm.and(l,drizzleOrm.eq(a.workspace_id,n)):l,g=c.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 _ of g)s.has(_.id)||(s.add(_.id),o+=_.input_tokens??0,i+=_.output_tokens??0,u+=_.cost_usd??0);}catch(l){throw new f("DB_ERROR","Failed to get thread token usage",l)}finally{c.close();}}return {inputTokens:o,outputTokens:i,costUsd:u}}findTasksByThread(e,n,r){let s=this.resolveDbPaths(),o=new Set,i=[],u=r?.projection==="activity-log";for(let d of s){if(!fs$1.existsSync(d))continue;let c=$(d);try{let l=drizzleOrm.eq(a.thread_id,e),p=n?drizzleOrm.and(l,drizzleOrm.eq(a.workspace_id,n)):l,g=u?c.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(drizzleOrm.asc(a.started_at)).all():c.db.select(te).from(a).where(p).orderBy(drizzleOrm.asc(a.started_at)).all().map(Fe);for(let _ of g)o.has(_.id)||(o.add(_.id),i.push(_));}catch(l){throw new f("DB_ERROR","Failed to find tasks by thread",l)}finally{c.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(!fs$1.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(drizzleOrm.and(drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.inArray(a.status,["running","pending"]),drizzleOrm.or(drizzleOrm.like(a.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(a.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(drizzleOrm.desc(a.started_at)).all().map(io));}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(!fs$1.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(drizzleOrm.and(drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.eq(a.workspace_id,e))).orderBy(drizzleOrm.desc(a.started_at),drizzleOrm.desc(a.id)).all();for(let u of i){let d=this.parseWorkflowCardMetadata(u.metadata);if(d.kind!=="workflow_card"&&d.kind!=="workflow_ui_instance"||typeof d.workflowRunId!="string")continue;let c=d.kind,l=r.get(c)??new Set;l.has(d.workflowRunId)||(l.add(d.workflowRunId),r.set(c,l),n.push(io(u)));}}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(!fs$1.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(drizzleOrm.and(drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.eq(a.workspace_id,e.workspaceId))).orderBy(drizzleOrm.desc(a.started_at),drizzleOrm.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 io(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?drizzleOrm.eq(a.workspace_id,n):void 0,u=(d,c)=>{if(!d)return;let l=o.get(d);if(l&&c.started_at<=l)return;let p=this.parseWorkflowCardMetadata(c.metadata);p.kind!=="workflow_card"&&p.kind!=="workflow_ui_instance"||(o.set(d,c.started_at),r.set(d,{taskId:c.id,workflowRunId:p.workflowRunId,raw:c.result??void 0}));};for(let d of this.resolveDbPaths()){if(!fs$1.existsSync(d))continue;let c=$(d);try{let l=drizzleOrm.and(drizzleOrm.inArray(a.thread_id,e),drizzleOrm.or(drizzleOrm.like(a.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(a.metadata,'%"kind":"workflow_ui_instance"%'))),p=c.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?drizzleOrm.and(l,i):l).all();for(let m of p)u(m.thread_id,m);let g=drizzleOrm.and(drizzleOrm.isNull(a.thread_id),drizzleOrm.or(drizzleOrm.like(a.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(a.metadata,'%"kind":"workflow_ui_instance"%'))),_=c.db.select({id:a.id,command:a.command,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?drizzleOrm.and(g,i):g).all();for(let m of _){let y=this.extractThreadIdFromCommand(m.command);!y||!s.has(y)||u(y,m);}}catch(l){throw new f("DB_ERROR","Failed to batch fetch workflow cards",l)}finally{c.close();}}return r}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(drizzleOrm.eq(a.workspace_id,e.workspaceId));let s=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;s&&r.push(drizzleOrm.inArray(a.agent_id,s));let o=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;o&&r.push(drizzleOrm.inArray(a.status,Bs(o)));let i=e.q??e.search;i&&r.push(drizzleOrm.like(a.prompt,`%${i}%`)),e.from&&r.push(drizzleOrm.gte(a.started_at,e.from)),e.to&&r.push(drizzleOrm.lt(a.started_at,e.to));let u=r.length>0?drizzleOrm.and(...r):void 0,d=n.db.select({count:drizzleOrm.sql`count(*)`}).from(a).where(u).get(),c=(e.sortDir??"DESC")==="ASC"?drizzleOrm.asc(a.started_at):drizzleOrm.desc(a.started_at);return {rows:n.db.select(te).from(a).where(u).orderBy(c).limit(e.limit).offset(e.offset).all().map(Fe),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=uo(drizzleOrm.sql.raw("t.model"),drizzleOrm.sql.raw("t.metadata")),i=Fn(drizzleOrm.sql.raw("t.status")),u=xr(drizzleOrm.sql.raw("t.metadata")),d=drizzleOrm.sql`
|
|
161
161
|
COALESCE(t.input_tokens, 0)
|
|
162
162
|
+ CASE
|
|
163
|
-
WHEN t.started_at >= ${
|
|
163
|
+
WHEN t.started_at >= ${en}
|
|
164
164
|
AND (
|
|
165
165
|
t.crewx_version IS NULL
|
|
166
166
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
167
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
167
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${tn}) AS INTEGER) < ${nn})
|
|
168
168
|
)
|
|
169
169
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
170
170
|
ELSE 0
|
|
@@ -183,7 +183,7 @@ ${r.join(`
|
|
|
183
183
|
FROM tasks t
|
|
184
184
|
${c}
|
|
185
185
|
GROUP BY t.agent_id, t.workspace_id, ${o}
|
|
186
|
-
`),p=new Map;for(let m of l){let y=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",k={provider:y,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},
|
|
186
|
+
`),p=new Map;for(let m of l){let y=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",k={provider:y,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},N=m.workspace_id??null,S=JSON.stringify([m.agent_id,N]),C=p.get(S);if(!C){p.set(S,{agentId:m.agent_id,workspaceId:N,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:[k]});continue}C.totalTasks+=m.total_tasks,C.unavailableTaskCount=(C.unavailableTaskCount??0)+m.unavailable_task_count,C.inputTokens+=m.input_tokens,C.outputTokens+=m.output_tokens,C.cachedInputTokens+=m.cached_input_tokens,C.costUsd+=m.cost_usd,C.totalTokens+=m.input_tokens+m.output_tokens;let E=C.providers.find(I=>I.provider===y);E?(E.inputTokens+=k.inputTokens,E.outputTokens+=k.outputTokens,E.cachedInputTokens+=k.cachedInputTokens,E.totalTokens+=k.totalTokens,E.costUsd+=k.costUsd,E.totalTasks+=k.totalTasks,E.unavailableTaskCount+=k.unavailableTaskCount):C.providers.push(k);}let g=[...p.values()];for(let m of g)m.providers.sort((y,k)=>y.provider===k.provider?0:y.provider==="unknown"?1:k.provider==="unknown"?-1:y.totalTokens!==k.totalTokens?k.totalTokens-y.totalTokens:y.provider<k.provider?-1:1);let _=(m,y)=>m===y?0:m<y?-1:1;return g.sort((m,y)=>{if(m.totalTokens!==y.totalTokens)return y.totalTokens-m.totalTokens;let k=_(m.agentId,y.agentId);return k!==0?k:m.workspaceId===y.workspaceId?0:m.workspaceId===null?1:y.workspaceId===null?-1:_(m.workspaceId,y.workspaceId)}),g}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=Fn(drizzleOrm.sql.raw("t.status")),i=xr(drizzleOrm.sql.raw("t.metadata"));return s.db.all(r?drizzleOrm.sql`
|
|
187
187
|
SELECT
|
|
188
188
|
date(t.started_at) AS date,
|
|
189
189
|
t.agent_id,
|
|
@@ -191,11 +191,11 @@ ${r.join(`
|
|
|
191
191
|
COALESCE(SUM(
|
|
192
192
|
COALESCE(t.input_tokens, 0)
|
|
193
193
|
+ CASE
|
|
194
|
-
WHEN t.started_at >= ${
|
|
194
|
+
WHEN t.started_at >= ${en}
|
|
195
195
|
AND (
|
|
196
196
|
t.crewx_version IS NULL
|
|
197
197
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
198
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
198
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${tn}) AS INTEGER) < ${nn})
|
|
199
199
|
)
|
|
200
200
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
201
201
|
ELSE 0
|
|
@@ -220,11 +220,11 @@ ${r.join(`
|
|
|
220
220
|
COALESCE(SUM(
|
|
221
221
|
COALESCE(t.input_tokens, 0)
|
|
222
222
|
+ CASE
|
|
223
|
-
WHEN t.started_at >= ${
|
|
223
|
+
WHEN t.started_at >= ${en}
|
|
224
224
|
AND (
|
|
225
225
|
t.crewx_version IS NULL
|
|
226
226
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
227
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
227
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${tn}) AS INTEGER) < ${nn})
|
|
228
228
|
)
|
|
229
229
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
230
230
|
ELSE 0
|
|
@@ -240,14 +240,14 @@ ${r.join(`
|
|
|
240
240
|
AND t.agent_id != 'workflow'
|
|
241
241
|
GROUP BY date(t.started_at), t.agent_id
|
|
242
242
|
ORDER BY date(t.started_at) ASC
|
|
243
|
-
`).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(
|
|
243
|
+
`).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(te).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.workspace_id,n))).limit(1).get();return s?Fe(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(drizzleOrm.and(drizzleOrm.eq(a.agent_id,e.agentId),drizzleOrm.eq(a.workspace_id,e.workspaceId),drizzleOrm.sql`${a.metadata} IS NOT NULL AND json_valid(${a.metadata}) AND json_extract(${a.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(drizzleOrm.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 u=new Date().toISOString(),d=r?drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.workspace_id,r)):drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"running")),c=i.db.select({metadata:a.metadata}).from(a).where(d).limit(1).get();if(!c)return;let l={status:s,error:n,completed_at:u};if(o){let p=ne(c.metadata);p.terminalReason=o,l.metadata=JSON.stringify(p);}i.db.update(a).set(l).where(d).run();}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to mark task failed",u)}finally{i.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!fs$1.existsSync(i))continue;let u=$(i);try{let d=n?drizzleOrm.and(drizzleOrm.like(a.prompt,`%${e}%`),drizzleOrm.eq(a.workspace_id,n)):drizzleOrm.like(a.prompt,`%${e}%`),c=u.db.select(te).from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of c)s.has(l.id)||(s.add(l.id),o.push(Fe(l)));}catch(d){throw new f("DB_ERROR","Failed to find tasks by prompt hint",d)}finally{u.close();}}return o}getProviderUsage(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=uo(),i=Fn(a.status),u=xr(a.metadata),d=drizzleOrm.sql`
|
|
244
244
|
COALESCE(${a.input_tokens}, 0)
|
|
245
245
|
+ CASE
|
|
246
|
-
WHEN ${a.started_at} >= ${
|
|
246
|
+
WHEN ${a.started_at} >= ${en}
|
|
247
247
|
AND (
|
|
248
248
|
${a.crewx_version} IS NULL
|
|
249
249
|
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
250
|
-
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${
|
|
250
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${tn}) AS INTEGER) < ${nn})
|
|
251
251
|
)
|
|
252
252
|
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
253
253
|
ELSE 0
|
|
@@ -267,14 +267,14 @@ ${r.join(`
|
|
|
267
267
|
${c}
|
|
268
268
|
GROUP BY ${o}
|
|
269
269
|
ORDER BY (COALESCE(SUM(${d}), 0) + COALESCE(SUM(${a.output_tokens}), 0)) DESC
|
|
270
|
-
`).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=
|
|
270
|
+
`).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=uo(),i=Fn(a.status),u=xr(a.metadata),d=drizzleOrm.sql`
|
|
271
271
|
COALESCE(${a.input_tokens}, 0)
|
|
272
272
|
+ CASE
|
|
273
|
-
WHEN ${a.started_at} >= ${
|
|
273
|
+
WHEN ${a.started_at} >= ${en}
|
|
274
274
|
AND (
|
|
275
275
|
${a.crewx_version} IS NULL
|
|
276
276
|
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
277
|
-
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${
|
|
277
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${tn}) AS INTEGER) < ${nn})
|
|
278
278
|
)
|
|
279
279
|
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
280
280
|
ELSE 0
|
|
@@ -294,7 +294,7 @@ ${r.join(`
|
|
|
294
294
|
FROM ${a}
|
|
295
295
|
${c}
|
|
296
296
|
GROUP BY ${a.model}, ${o}
|
|
297
|
-
`),p=new Map;for(let g of l){let _=
|
|
297
|
+
`),p=new Map;for(let g of l){let _=Ts(g.model??""),m=JSON.stringify([g.provider,_]),y=p.get(m);y?(y.totalTasks+=g.total_tasks,y.unavailableTaskCount=(y.unavailableTaskCount??0)+g.unavailable_task_count,y.inputTokens+=g.input_tokens,y.outputTokens+=g.output_tokens,y.cachedInputTokens+=g.cached_input_tokens,y.costUsd+=g.cost_usd,y.totalTokens+=g.input_tokens+g.output_tokens,y.activeDurationMs+=g.active_duration_ms??0,g.last_active_at&&(!y.lastActiveAt||g.last_active_at>y.lastActiveAt)&&(y.lastActiveAt=g.last_active_at)):p.set(m,{model:_,provider:g.provider,totalTasks:g.total_tasks,unavailableTaskCount:g.unavailable_task_count,inputTokens:g.input_tokens,outputTokens:g.output_tokens,cachedInputTokens:g.cached_input_tokens,costUsd:g.cost_usd,totalTokens:g.input_tokens+g.output_tokens,activeDurationMs:g.active_duration_ms??0,lastActiveAt:g.last_active_at??null});}return Array.from(p.values()).sort((g,_)=>_.costUsd-g.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?drizzleOrm.sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:drizzleOrm.sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`;return s.db.all(drizzleOrm.sql`
|
|
298
298
|
SELECT
|
|
299
299
|
${a.thread_id} AS thread_id,
|
|
300
300
|
${a.agent_id} AS agent_id,
|
|
@@ -306,19 +306,19 @@ ${r.join(`
|
|
|
306
306
|
FROM ${a}
|
|
307
307
|
${o}
|
|
308
308
|
ORDER BY ${a.started_at} ASC
|
|
309
|
-
`).map(u=>({threadId:u.thread_id,agentId:u.agent_id,startedAt:u.started_at,status:u.status,error:u.error,exitCode:u.exit_code,terminalReason:
|
|
309
|
+
`).map(u=>({threadId:u.thread_id,agentId:u.agent_id,startedAt:u.started_at,status:u.status,error:u.error,exitCode:u.exit_code,terminalReason:He({status:u.status,error:u.error,metadata:u.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=drizzleOrm.sql`
|
|
310
310
|
COALESCE(${a.input_tokens}, 0)
|
|
311
311
|
+ CASE
|
|
312
|
-
WHEN ${a.started_at} >= ${
|
|
312
|
+
WHEN ${a.started_at} >= ${en}
|
|
313
313
|
AND (
|
|
314
314
|
${a.crewx_version} IS NULL
|
|
315
315
|
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
316
|
-
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${
|
|
316
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${tn}) AS INTEGER) < ${nn})
|
|
317
317
|
)
|
|
318
318
|
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
319
319
|
ELSE 0
|
|
320
320
|
END
|
|
321
|
-
`,i=
|
|
321
|
+
`,i=Fn(a.status),u=r?drizzleOrm.sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:drizzleOrm.sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`,d=s.db.all(drizzleOrm.sql`
|
|
322
322
|
SELECT
|
|
323
323
|
${a.caller_agent_id} AS caller_agent_id,
|
|
324
324
|
${a.agent_id} AS agent_id,
|
|
@@ -329,24 +329,24 @@ ${r.join(`
|
|
|
329
329
|
${u}
|
|
330
330
|
GROUP BY ${a.caller_agent_id}, ${a.agent_id}
|
|
331
331
|
ORDER BY task_count DESC, ${a.caller_agent_id} ASC, ${a.agent_id} ASC
|
|
332
|
-
LIMIT ${
|
|
333
|
-
`),c=d.length>
|
|
332
|
+
LIMIT ${ao+1}
|
|
333
|
+
`),c=d.length>ao;return {edges:d.slice(0,ao).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:c}}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(drizzleOrm.eq(a.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(drizzleOrm.inArray(a.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(drizzleOrm.inArray(a.status,Bs(e.statuses))),e.from&&r.push(drizzleOrm.gte(a.started_at,e.from)),e.to&&r.push(drizzleOrm.lt(a.started_at,e.to));let s=r.length>0?drizzleOrm.and(...r):void 0,o=(e.order??"DESC")==="ASC"?drizzleOrm.asc(a.started_at):drizzleOrm.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:c,...l})=>({...l,status:ve({status:l.status,error:d,metadata:c}),terminalReason:He({status:l.status,error:d,metadata:c})??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=[drizzleOrm.isNotNull(a.thread_id),drizzleOrm.isNull(a.parent_task_id),drizzleOrm.isNull(a.caller_agent_id),drizzleOrm.or(drizzleOrm.isNull(a.platform),drizzleOrm.ne(a.platform,"workflow")),drizzleOrm.or(drizzleOrm.isNull(a.metadata),drizzleOrm.and(drizzleOrm.notLike(a.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(a.metadata,'%"kind":"workflow_ui_instance"%'))),drizzleOrm.or(drizzleOrm.isNull(a.metadata),drizzleOrm.notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&o.push(drizzleOrm.eq(a.workspace_id,e.workspaceId)),e.from&&o.push(drizzleOrm.gte(a.started_at,e.from)),e.to&&o.push(drizzleOrm.lt(a.started_at,e.to));let i=n.db.select({id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id}).from(a).where(drizzleOrm.and(...o)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.asc(a.id)).all(),u=new Map;for(let c of i){if(!c.thread_id)continue;let l={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},p=u.get(c.thread_id);p?p.push(l):u.set(c.thread_id,[l]);}let d=[];for(let[c,l]of u){let p=l.filter(g=>g.agentId===e.targetAgentId).length;p<2||d.push({threadId:c,targetAgentTurnCount:p,turns:l});}return d.sort((c,l)=>{let p=c.turns[c.turns.length-1].startedAt,g=l.turns[l.turns.length-1].startedAt;return p<g?1:p>g?-1:0}),d.slice(0,r).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-s)}))}catch(r){throw new f("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}},Dd=["up","down"],_o=1e3,Pd=200,df=64,Bn=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;}},uf=new Set(vn);});h();h();h();var ot=class{detach(e){}};h();function Co(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 Yr(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var Qr=class extends ot{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(e){super(),this.logsDir=ce.join(e?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=e?.version??"unknown";}attach(e){this.unsubs.push(e.on("task:start",n=>{try{fs$1.existsSync(this.logsDir)||fs$1.mkdirSync(this.logsDir,{recursive:!0});let r=Co(n.timestamp),s=ce.join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,s);let o=`=== TASK LOG: ${n.traceId} ===
|
|
334
334
|
CrewX Version: ${this.version}
|
|
335
335
|
Mode: ${n.mode}
|
|
336
336
|
Agent: ${n.agentRef}
|
|
337
|
-
Started: ${
|
|
337
|
+
Started: ${Yr(n.timestamp)}
|
|
338
338
|
Message: ${n.message}
|
|
339
339
|
|
|
340
340
|
`;fs$1.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();fs$1.appendFileSync(r,`[${s}] STDOUT: ${n.output}
|
|
341
|
-
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let s=
|
|
341
|
+
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let s=Yr(new Date),o=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${s}] INFO: Task ${o} in ${n.durationMs}ms
|
|
342
342
|
[${s}] INFO: Process closed with exit code: ${n.error?1:0}
|
|
343
|
-
`;fs$1.appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};h();h();var bo=Symbol.for("crewx.interceptor.run-stops");function uu(){let t=globalThis,e=t[bo];if(e)return e;let n=new Map;return t[bo]=n,n}function vo(t){let e=uu().get(t);return e?(e.abort(),true):false}h();var Dt=new Map;function Vn(t){let e=de__namespace.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 Co(t){let e=Vn(t);return crypto.createHash("sha256").update(e).digest("hex")}function Do(t){let e=Vn(t),n=Dt.get(e);if(n!==void 0)return n;let r=e;try{let s=de__namespace.join(e,".git");if(!fs$1.lstatSync(s).isFile())return Dt.set(e,r),r;let o=/^gitdir:\s*(.+?)\s*$/i.exec(fs$1.readFileSync(s,"utf8").trim());if(!o)return Dt.set(e,r),r;let i=o[1],u=de__namespace.isAbsolute(i)?i:de__namespace.resolve(de__namespace.dirname(s),i),d=fs$1.readFileSync(de__namespace.join(u,"commondir"),"utf8").trim();if(!d)return Dt.set(e,r),r;let c=de__namespace.isAbsolute(d)?d:de__namespace.resolve(u,d);if(de__namespace.basename(c)!==".git"||!fs$1.statSync(c).isDirectory())return Dt.set(e,r),r;let l=Vn(fs$1.realpathSync.native(e)),p=Vn(fs$1.realpathSync.native(de__namespace.dirname(c)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return Dt.set(e,r),r}ot();Zs();Ft();Ls();xn();Qs();ur();var sf=200,of=200;function af(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 df(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=af(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function Od(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function uf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bd(t){if(!t)return {};try{let e=JSON.parse(t);return uf(e)?e:{}}catch{return {}}}function rn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var cf=new Set(["workflow","mcp"]),fo=class extends st{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?de.join(e.dbRoot,".crewx","crewx.db"):n??de.join($o.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 $n({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),s=fs$1.existsSync(de.join(r,"crewx.yaml"))||fs$1.existsSync(de.join(r,"crewx.yml")),o=this.inheritWorktreeOwner?Do(r):r,i=s?Co(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:_}=this.runnerIdentity,m=_??d.traceId,y=rn(d.metadata?.runEpoch),k=g?"runner":"caller",v=d.workspaceId??i,S=g?n.getTask(m):void 0,C=d.pid??null,E={...d.metadata??{provider:d.provider??"cli/claude"},ownership:k,...g&&C!==null?{providerPid:C}:{}},I=JSON.stringify(E);if(g&&S?.status==="running"&&S.pid!==null&&y===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:C,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,securityKey:d.renderedPrompt==null?null:d.securityKey??null,command:u,codingAgentCommand:d.codingAgentCommand??null,workspaceId:v,projectId:d.projectId??null,callerAgentId:c,parentTaskId:l,traceId:p,metadata:I,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:m,runEpoch:y,ownership:k,...g?{providerPid:C}:{},runtime:{model:d.model??null,renderedPrompt:d.renderedPrompt??null,codingAgentCommand:d.codingAgentCommand??null,metadata:E}})?this.recordOwnedTaskRun({taskId:m,runEpoch:y,workspaceId:v,ownership:k}):console.warn("[crewx] task execution metadata not recorded",{taskId:m,runEpoch:y,ownership:k}),cf.has(d.platform??"cli")||od(n,{taskId:m,runEpoch:y,onStopRequested:zr=>this.handleStopRequested(n,zr)})&&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],Od(l));}}),e.on("task:run-update",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;let l=rn(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,rn(l)),Nn(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,_=d.result??null,m=!1,y=d.metadata?.suppressPartialResultRecovery===!0;if(d.error&&!y&&(!_||_.trim()==="")){let k=this.recoverPartialResult(c,d,l);k&&(_=k,m=!0);}n.finishTask({id:c,status:d.error?"failed":"success",result:_,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)Nn(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 pd(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+=Od(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>=sf){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));},of);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"||rn(o.run_epoch)!==rn(r))return;let i=bd(o.metadata),u=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!u)return;let d=Er({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()||Je(c,u)?void 0:c}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let s=rn(n.run_epoch),o=bd(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(vo(r),d!==void 0){let c;try{c=await Ut(d,{signal:Ht});}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:Ir(n.stop_requested_at)}),l=e.getTask(r);(c||l?.status!=="running")&&Nn(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=df(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});}};h();h();h();it();_t();mt();ot();Et();bn();h();function Cr(t){return t!==null&&t!==""}function lf(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":Cr(t.parent_task_id)||Cr(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function vd(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&Cr(e)?e:null}}function Dr(t){let e=lf(t),n=Cr(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 Nd(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?vd(t.creator_actor_kind,t.creator_actor_id):e?Dr(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?vd(t.created_by_kind,t.created_by_id):n?Dr(n):void 0}function Un(t){return On(t)}function mf({metadata:t,...e}){return {...e,status:Me({...e,metadata:t}),terminalReason:Qe({...e,metadata:t})??null}}var Lr=32,Cd=100,kf=["running","failed"];function Tf(t){return t==="running"?0:t==="failed"?1:2}function Dd(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 wf(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function yf(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 Pd(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function Ld(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function Ef(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function Md(t,e,n,r){let s=Ef(e);s&&(t[s]+=r,t.total+=r,s==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var Mr=900,$d=20;function Hd(t,e){return (t?.origin??"direct")===e}function Ud(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 on=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function sn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Rf(t){let n=sn(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 Fd(t,e,n){return t.get(drizzleOrm.sql`
|
|
343
|
+
`;fs$1.appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};h();h();var Lo=Symbol.for("crewx.interceptor.run-stops");function ku(){let t=globalThis,e=t[Lo];if(e)return e;let n=new Map;return t[Lo]=n,n}function Mo(t){let e=ku().get(t);return e?(e.abort(),true):false}h();var Lt=new Map;function Zn(t){let e=ce__namespace.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 Uo(t){let e=Zn(t);return crypto.createHash("sha256").update(e).digest("hex")}function Fo(t){let e=Zn(t),n=Lt.get(e);if(n!==void 0)return n;let r=e;try{let s=ce__namespace.join(e,".git");if(!fs$1.lstatSync(s).isFile())return Lt.set(e,r),r;let o=/^gitdir:\s*(.+?)\s*$/i.exec(fs$1.readFileSync(s,"utf8").trim());if(!o)return Lt.set(e,r),r;let i=o[1],u=ce__namespace.isAbsolute(i)?i:ce__namespace.resolve(ce__namespace.dirname(s),i),d=fs$1.readFileSync(ce__namespace.join(u,"commondir"),"utf8").trim();if(!d)return Lt.set(e,r),r;let c=ce__namespace.isAbsolute(d)?d:ce__namespace.resolve(u,d);if(ce__namespace.basename(c)!==".git"||!fs$1.statSync(c).isDirectory())return Lt.set(e,r),r;let l=Zn(fs$1.realpathSync.native(e)),p=Zn(fs$1.realpathSync.native(ce__namespace.dirname(c)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return Lt.set(e,r),r}it();so();Bt();Fs();Ln();ro();gr();var gf=200,hf=200;function _f(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 mf(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=_f(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function Hd(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function kf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ud(t){if(!t)return {};try{let e=JSON.parse(t);return kf(e)?e:{}}catch{return {}}}function on(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Tf=new Set(["workflow","mcp"]),ko=class extends ot{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?ce.join(e.dbRoot,".crewx","crewx.db"):n??ce.join(jo.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 qn({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),s=fs$1.existsSync(ce.join(r,"crewx.yaml"))||fs$1.existsSync(ce.join(r,"crewx.yml")),o=this.inheritWorktreeOwner?Fo(r):r,i=s?Uo(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:_}=this.runnerIdentity,m=_??d.traceId,y=on(d.metadata?.runEpoch),k=g?"runner":"caller",N=d.workspaceId??i,S=g?n.getTask(m):void 0,C=d.pid??null,E={...d.metadata??{provider:d.provider??"cli/claude"},ownership:k,...g&&C!==null?{providerPid:C}:{}},I=JSON.stringify(E);if(g&&S?.status==="running"&&S.pid!==null&&y===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:C,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,securityKey:d.renderedPrompt==null?null:d.securityKey??null,command:u,codingAgentCommand:d.codingAgentCommand??null,workspaceId:N,projectId:d.projectId??null,callerAgentId:c,parentTaskId:l,traceId:p,metadata:I,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:m,runEpoch:y,ownership:k,...g?{providerPid:C}:{},runtime:{model:d.model??null,renderedPrompt:d.renderedPrompt??null,codingAgentCommand:d.codingAgentCommand??null,metadata:E}})?this.recordOwnedTaskRun({taskId:m,runEpoch:y,workspaceId:N,ownership:k}):console.warn("[crewx] task execution metadata not recorded",{taskId:m,runEpoch:y,ownership:k}),Tf.has(d.platform??"cli")||_d(n,{taskId:m,runEpoch:y,onStopRequested:Xr=>this.handleStopRequested(n,Xr)})&&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],Hd(l));}}),e.on("task:run-update",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;let l=on(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,on(l)),Pn(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,_=d.result??null,m=!1,y=d.metadata?.suppressPartialResultRecovery===!0;if(d.error&&!y&&(!_||_.trim()==="")){let k=this.recoverPartialResult(c,d,l);k&&(_=k,m=!0);}n.finishTask({id:c,status:d.error?"failed":"success",result:_,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)Pn(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 Rd(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+=Hd(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>=gf){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));},hf);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"||on(o.run_epoch)!==on(r))return;let i=Ud(o.metadata),u=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!u)return;let d=Or({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()||Ye(c,u)?void 0:c}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let s=on(n.run_epoch),o=Ud(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(Mo(r),d!==void 0){let c;try{c=await qt(d,{signal:Ft});}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:vr(n.stop_requested_at)}),l=e.getTask(r);(c||l?.status!=="running")&&Pn(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=mf(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});}};h();h();h();at();mt();kt();it();St();Cn();h();function $r(t){return t!==null&&t!==""}function wf(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":$r(t.parent_task_id)||$r(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function Fd(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&$r(e)?e:null}}function Hr(t){let e=wf(t),n=$r(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 qd(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?Fd(t.creator_actor_kind,t.creator_actor_id):e?Hr(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?Fd(t.created_by_kind,t.created_by_id):n?Hr(n):void 0}function Wn(t){return xn(t)}function Af({metadata:t,...e}){return {...e,status:ve({...e,metadata:t}),terminalReason:He({...e,metadata:t})??null}}var jn=32,Wd=100,Of=["running","failed"];function bf(t){return t==="running"?0:t==="failed"?1:2}function jd(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 Nf(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function vf(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 Gd(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function To(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function xf(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function wo(t,e,n,r){let s=xf(e);s&&(t[s]+=r,t.total+=r,s==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var Fr=900,zd=20;function Kd(t,e){return (t?.origin??"direct")===e}function Vd(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 an=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function dn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Cf(t){let n=dn(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 Jd(t,e,n){return t.get(drizzleOrm.sql`
|
|
344
344
|
SELECT id
|
|
345
345
|
FROM tasks INDEXED BY idx_tasks_thread_id
|
|
346
346
|
WHERE thread_id = ${e}
|
|
347
347
|
AND id <> ${n}
|
|
348
348
|
LIMIT 1
|
|
349
|
-
`)!==void 0}
|
|
349
|
+
`)!==void 0}function Df(t,e,n){let r=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e),s=t.select({pinned:T.pinned,metadata:T.metadata}).from(T).where(r).get();if(!s)return null;let o=s.pinned?0:1,i=dn(s.metadata);if(o){let u=n?drizzleOrm.and(drizzleOrm.eq(T.pinned,1),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.pinned,1),d=t.select({metadata:T.metadata}).from(T).where(u).all(),c=null;for(let l of d){let p=dn(l.metadata);typeof p.pinOrder=="number"&&(c===null||p.pinOrder<c)&&(c=p.pinOrder);}i.pinOrder=c===null?0:c-1;}else delete i.pinOrder;return t.update(T).set({pinned:o,metadata:Object.keys(i).length>0?JSON.stringify(i):null}).where(r).run(),{pinned:!!o}}function Pf(t,e,n){for(let r=0;r<e.length;r++){let s=n?drizzleOrm.and(drizzleOrm.eq(T.id,e[r]),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e[r]),o=t.select({metadata:T.metadata}).from(T).where(s).get();if(!o)continue;let i=dn(o.metadata);i.pinOrder=r+1,t.update(T).set({metadata:JSON.stringify(i)}).where(s).run();}}var qr=class extends _e{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ce.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=ce.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}else if(!fs$1.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=$(n);if(e)try{Oe(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 drizzleOrm.sql.raw(`NOT EXISTS (
|
|
350
350
|
SELECT 1 FROM ${r}
|
|
351
351
|
WHERE parent.id = ${e}.parent_task_id
|
|
352
352
|
AND parent.thread_id = ${e}.thread_id
|
|
@@ -389,17 +389,17 @@ Message: ${n.message}
|
|
|
389
389
|
)
|
|
390
390
|
)`}findAllThreadsQuery(e,n){let r=[];e&&r.push(drizzleOrm.sql`workspace_id = ${e}`),n&&r.push(drizzleOrm.sql`created_by_kind = ${n}`);let s=r.length>0?drizzleOrm.sql` WHERE ${drizzleOrm.sql.join(r,drizzleOrm.sql` AND `)}`:drizzleOrm.sql``;return drizzleOrm.sql`SELECT * FROM threads${s} ORDER BY updated_at DESC`}findThreadIdsQuery(e){return e?drizzleOrm.sql`SELECT id FROM threads INDEXED BY idx_threads_ws_updated
|
|
391
391
|
WHERE workspace_id = ${e}
|
|
392
|
-
ORDER BY updated_at DESC`:drizzleOrm.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(!fs$1.existsSync(i))continue;let u
|
|
392
|
+
ORDER BY updated_at DESC`:drizzleOrm.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(!fs$1.existsSync(i))continue;let u=$(i);try{let d=u.db.all(this.findThreadIdsQuery(e));for(let c of d)s.has(c.id)||(s.add(c.id),o.push(c.id));}catch(d){throw new f("DB_ERROR",n,d)}finally{u.close();}}return o}findThreadSortKeysQuery(e){return drizzleOrm.sql`SELECT id, updated_at
|
|
393
393
|
FROM threads INDEXED BY idx_threads_ws_updated
|
|
394
|
-
WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!fs$1.existsSync(o))continue;let i
|
|
394
|
+
WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!fs$1.existsSync(o))continue;let i=$(o);try{let u=i.db.all(this.findThreadSortKeysQuery(e));for(let d of u)r.has(d.id)||(r.add(d.id),s.push(d));}catch(u){throw new f("DB_ERROR","Failed to find recent direct threads",u)}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 u of s){if(!fs$1.existsSync(u))continue;let d=$(u);try{for(let c=0;c<e.length;c+=Fr){let l=e.slice(c,c+Fr),p=drizzleOrm.inArray(T.id,l),g=n?drizzleOrm.and(p,drizzleOrm.eq(T.workspace_id,n)):p,_=d.db.select().from(T).where(g).all();for(let m of _)o.has(m.id)||(o.add(m.id),i.push(m));}}catch(c){throw new f("DB_ERROR",r,c)}finally{d.close();}}return i}readThreadRows(e,n,r="Failed to find all threads"){let s=this.resolveDbPaths(),o=new Set,i=[];for(let u of s){if(!fs$1.existsSync(u))continue;let d=$(u);try{let c=d.db.all(this.findAllThreadsQuery(e,n));for(let l of c)o.has(l.id)||(o.add(l.id),i.push(l));}catch(c){throw new f("DB_ERROR",r,c)}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(!fs$1.existsSync(s))continue;let o=$(s);try{return o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findAllThreadsQuery(e,n)}`).map(u=>u.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(!fs$1.existsSync(i))continue;let u=$(i);try{let d=drizzleOrm.or(drizzleOrm.inArray(T.id,e),drizzleOrm.inArray(T.title,e)),c=n?drizzleOrm.and(d,drizzleOrm.eq(T.workspace_id,n)):d,l=u.db.select().from(T).where(c).orderBy(drizzleOrm.desc(T.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{u.close();}}return o}findThreadById(e,n){let r=this.resolveDbPaths();for(let s of r){if(!fs$1.existsSync(s))continue;let o=$(s);try{let i=drizzleOrm.eq(T.id,e),u=n?drizzleOrm.and(i,drizzleOrm.eq(T.workspace_id,n)):i,d=o.db.select().from(T).where(u).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:ee.id}).from(ee).where(drizzleOrm.eq(ee.id,e.workspaceId)).limit(1).get())throw new f("NOT_FOUND","Workspace not found");let o=r.select().from(T).where(drizzleOrm.eq(T.id,e.threadId)).limit(1).get();if(o){let l=dn(o.metadata).appLaunch,p=l&&typeof l=="object"&&!Array.isArray(l)?l.appId:void 0,g=r.get(drizzleOrm.sql`
|
|
395
395
|
SELECT COUNT(*) AS count FROM tasks WHERE thread_id = ${e.threadId}
|
|
396
|
-
`)?.count??0;return o.workspace_id===e.workspaceId&&p===e.appId&&o.message_count===0&&o.first_message===null&&o.last_message===null&&g===0?{status:"existing",thread:o}:{status:"conflict"}}let i=new Date().toISOString(),u=JSON.stringify({appLaunch:{appId:e.appId,...e.initialAgentId===void 0?{}:{initialAgentId:e.initialAgentId}}});r.insert(T).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:u,created_at:i,updated_at:i}).run();let d=r.select().from(T).where(drizzleOrm.eq(T.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(!fs$1.existsSync(s))continue;let o
|
|
396
|
+
`)?.count??0;return o.workspace_id===e.workspaceId&&p===e.appId&&o.message_count===0&&o.first_message===null&&o.last_message===null&&g===0?{status:"existing",thread:o}:{status:"conflict"}}let i=new Date().toISOString(),u=JSON.stringify({appLaunch:{appId:e.appId,...e.initialAgentId===void 0?{}:{initialAgentId:e.initialAgentId}}});r.insert(T).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:u,created_at:i,updated_at:i}).run();let d=r.select().from(T).where(drizzleOrm.eq(T.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(!fs$1.existsSync(s))continue;let o=$(s);try{let i=drizzleOrm.eq(T.id,e),u=n?drizzleOrm.and(i,drizzleOrm.eq(T.workspace_id,n)):i;if(o.db.select({id:T.id}).from(T).where(u).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,u=0,d=0,c=0,l=0,p=0,g=0,_=0,m=new Set;for(let y of r){if(!fs$1.existsSync(y))continue;let k=$(y);try{let N=k.db.get(drizzleOrm.sql`
|
|
397
397
|
SELECT count(*) AS cnt
|
|
398
398
|
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
399
399
|
WHERE child.thread_id = ${e}
|
|
400
400
|
AND ${this.topLevelTaskPredicateSql()}
|
|
401
401
|
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
402
|
-
`);
|
|
402
|
+
`);N&&(s+=N.cnt);let S=k.db.get(drizzleOrm.sql`
|
|
403
403
|
SELECT
|
|
404
404
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
405
405
|
COALESCE(SUM(child.output_tokens), 0) AS total_output,
|
|
@@ -423,7 +423,7 @@ Message: ${n.message}
|
|
|
423
423
|
FROM descendants
|
|
424
424
|
JOIN tasks child INDEXED BY idx_tasks_parent_task_id
|
|
425
425
|
ON child.parent_task_id = descendants.task_id
|
|
426
|
-
WHERE descendants.depth < ${
|
|
426
|
+
WHERE descendants.depth < ${jn}
|
|
427
427
|
),
|
|
428
428
|
delegated_ids(task_id) AS (
|
|
429
429
|
SELECT DISTINCT descendants.task_id
|
|
@@ -449,13 +449,13 @@ Message: ${n.message}
|
|
|
449
449
|
AND child.agent_id != 'workflow'
|
|
450
450
|
AND ${this.topLevelTaskPredicateSql()}
|
|
451
451
|
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
452
|
-
`);for(let I of E)m.add(I.agent_id);}catch(
|
|
452
|
+
`);for(let I of E)m.add(I.agent_id);}catch(N){throw new f("DB_ERROR","Failed to aggregate task stats",N)}finally{k.close();}}return {taskCount:s,inputTokens:o,outputTokens:i,cachedInputTokens:u,costUsd:d,agentIds:Array.from(m),delegated:{taskCount:c,inputTokens:l,outputTokens:p,cachedInputTokens:g,costUsd:_}}}getDescendantSummaryByTaskId(e,n){let r=this.resolveDbPaths(),s={},o=new Date().toISOString();for(let i of r){if(!fs$1.existsSync(i))continue;let u=$(i);try{let d=drizzleOrm.sql`
|
|
453
453
|
SELECT own.id
|
|
454
454
|
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
455
455
|
WHERE own.thread_id = ${e}
|
|
456
456
|
${n?drizzleOrm.sql`AND own.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
457
457
|
`,c=u.db.all(drizzleOrm.sql`
|
|
458
|
-
${this.descendantTraversalSql(d,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,
|
|
458
|
+
${this.descendantTraversalSql(d,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,jn)}
|
|
459
459
|
SELECT
|
|
460
460
|
descendant_ids.root_task_id AS root_task_id,
|
|
461
461
|
task.status AS status,
|
|
@@ -466,7 +466,24 @@ Message: ${n.message}
|
|
|
466
466
|
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
467
467
|
WHERE NOT ${this.descendantSkippedSql("task")}
|
|
468
468
|
GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
|
|
469
|
-
`);for(let l of c){let p=s[l.root_task_id]??=
|
|
469
|
+
`);for(let l of c){let p=s[l.root_task_id]??=To(o);wo(p,ve(l),He(l),l.task_count);}}catch(d){throw new f("DB_ERROR","Failed to aggregate task descendant summaries",d)}finally{u.close();}}return s}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(),u=drizzleOrm.sql.join(r.map(c=>drizzleOrm.sql`${c}`),drizzleOrm.sql`, `),d=drizzleOrm.sql`
|
|
470
|
+
SELECT own.id
|
|
471
|
+
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
472
|
+
WHERE own.thread_id IN (${u})
|
|
473
|
+
${n?drizzleOrm.sql`AND own.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
474
|
+
`;for(let c of this.resolveDbPaths()){if(!fs$1.existsSync(c))continue;let l=$(c);try{let p=l.db.all(drizzleOrm.sql`
|
|
475
|
+
${this.descendantTraversalSql(d,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,jn)}
|
|
476
|
+
SELECT
|
|
477
|
+
descendant_ids.root_task_id AS root_task_id,
|
|
478
|
+
task.status AS status,
|
|
479
|
+
task.error AS error,
|
|
480
|
+
task.metadata AS metadata,
|
|
481
|
+
count(*) AS task_count
|
|
482
|
+
FROM descendant_ids
|
|
483
|
+
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
484
|
+
WHERE NOT ${this.descendantSkippedSql("task")}
|
|
485
|
+
GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
|
|
486
|
+
`);for(let g of p){let _=o[g.root_task_id]??=To(i);wo(_,ve(g),He(g),g.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??Of),o=Gd(r.limit,Wd,Wd),i=Gd(r.maxDepth,jn,jn),u=r.cursor?vf(r.cursor):void 0;for(let d of this.resolveDbPaths()){if(!fs$1.existsSync(d))continue;let c=$(d);try{if(!c.db.get(drizzleOrm.sql`
|
|
470
487
|
SELECT anchor.id FROM tasks anchor
|
|
471
488
|
WHERE anchor.id = ${e} AND anchor.workspace_id = ${n}
|
|
472
489
|
`))continue;let p=drizzleOrm.sql`
|
|
@@ -500,11 +517,11 @@ Message: ${n.message}
|
|
|
500
517
|
FROM descendant_ids
|
|
501
518
|
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
502
519
|
LEFT JOIN tasks parent ON parent.id = task.parent_task_id
|
|
503
|
-
`),_=
|
|
520
|
+
`),_=To(new Date().toISOString()),m=!1,y=[];for(let I of g){if(I.has_deeper&&(m=!0),I.skipped)continue;let b=ve(I);wo(_,b,He(I),1),s.has(b)&&y.push({row:I,key:[bf(b),I.started_at?I.started_at:null,I.task_id]});}y.sort((I,b)=>jd(I.key,b.key));let k=u?y.filter(I=>jd(I.key,u)>0):y,N=k.slice(0,o),S=k.length>N.length?Nf(N[N.length-1].key):null,C=new Map;if(N.length>0){let I=c.db.select(te).from(a).where(drizzleOrm.inArray(a.id,N.map(b=>b.row.task_id))).all();for(let b of I)C.set(b.id,Wn(b));}let E=[];for(let{row:I}of N){let b=C.get(I.task_id);!b||!I.parent_task_id||E.push({task:b,parentTaskId:I.parent_task_id,parentAgentId:I.parent_agent_id,depth:I.depth});}return {rows:E,summary:_,nextCursor:S,traversalTruncated:m}}catch(l){throw l instanceof f?l:new f("DB_ERROR","Failed to list task descendants",l)}finally{c.close();}}}findInterceptedRequests(e){let n=new Map;if(e.length===0)return n;for(let r of this.resolveDbPaths()){if(!fs$1.existsSync(r))continue;let s=$(r);try{let o=s.db.all(drizzleOrm.sql`
|
|
504
521
|
SELECT task_id, input FROM task_provider_inputs
|
|
505
522
|
WHERE run_epoch = 0
|
|
506
523
|
AND task_id IN (${drizzleOrm.sql.join(e.map(i=>drizzleOrm.sql`${i}`),drizzleOrm.sql`, `)})
|
|
507
|
-
`);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?drizzleOrm.sql`(${this.topLevelTaskPredicateSql()} OR child.agent_id = ${s})`:this.topLevelTaskPredicateSql(),u=new Set,d=[];for(let c of o){if(!fs$1.existsSync(c))continue;let l
|
|
524
|
+
`);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?drizzleOrm.sql`(${this.topLevelTaskPredicateSql()} OR child.agent_id = ${s})`:this.topLevelTaskPredicateSql(),u=new Set,d=[];for(let c of o){if(!fs$1.existsSync(c))continue;let l=$(c);try{let p;r!==void 0?p=l.db.all(drizzleOrm.sql`
|
|
508
525
|
SELECT * FROM (
|
|
509
526
|
SELECT child.*,
|
|
510
527
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -521,7 +538,7 @@ Message: ${n.message}
|
|
|
521
538
|
AND ${i}
|
|
522
539
|
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
523
540
|
ORDER BY child.started_at ASC
|
|
524
|
-
`);for(let g of p)u.has(g.id)||(u.add(g.id),d.push(
|
|
541
|
+
`);for(let g of p)u.has(g.id)||(u.add(g.id),d.push(Wn(g)));}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 c=new Map;for(let l of d){let p=l.agent_id??"";c.has(p)||c.set(p,[]),c.get(p).push(l);}d=[];for(let l of c.values())l.sort((p,g)=>(g.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(!fs$1.existsSync(i))continue;let u=$(i);try{let d=drizzleOrm.eq(a.thread_id,e),c=n?drizzleOrm.and(d,drizzleOrm.eq(a.workspace_id,n)):d,l=u.db.select(te).from(a).where(c).orderBy(drizzleOrm.asc(a.started_at)).all();for(let p of l)s.has(p.id)||(s.add(p.id),o.push(Wn(p)));}catch(d){throw new f("DB_ERROR","Failed to find all tasks for thread",d)}finally{u.close();}}return o}findRespondedAgents(e,n){let r=this.resolveDbPaths(),s=new Map;for(let o of r){if(!fs$1.existsSync(o))continue;let i=$(o,{readOnly:true});try{let u=[drizzleOrm.eq(a.thread_id,e),drizzleOrm.sql`${a.completed_at} IS NOT NULL`,drizzleOrm.sql`length(trim(coalesce(${a.result}, ''))) > 0`];n&&u.push(drizzleOrm.eq(a.workspace_id,n));let d=i.db.select({agentId:a.agent_id,lastRepliedAt:drizzleOrm.sql`MAX(${a.completed_at})`}).from(a).where(drizzleOrm.and(...u)).groupBy(a.agent_id).all();for(let c of d){let l=s.get(c.agentId);c.lastRepliedAt&&(!l||c.lastRepliedAt>l)&&s.set(c.agentId,c.lastRepliedAt);}}catch(u){throw new f("DB_ERROR","Failed to find responded agents for thread",u)}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(!fs$1.existsSync(o))continue;let i=$(o);try{let u=drizzleOrm.and(drizzleOrm.eq(a.id,n),drizzleOrm.eq(a.thread_id,e)),d=r?drizzleOrm.and(u,drizzleOrm.eq(a.workspace_id,r)):u,c=i.db.select(te).from(a).where(d).limit(1).get();if(!c)continue;let l=i.db.select(te).from(a).where(drizzleOrm.eq(a.parent_task_id,c.id)).orderBy(drizzleOrm.asc(a.started_at)).all().map(Wn);return {task:Wn(c),children:l}}catch(u){throw new f("DB_ERROR","Failed to find task by id",u)}finally{i.close();}}}batchFetchTasksQuery(e,n){return drizzleOrm.sql`
|
|
525
542
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
526
543
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
527
544
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -531,7 +548,7 @@ Message: ${n.message}
|
|
|
531
548
|
AND ${this.topLevelTaskPredicateSql()}
|
|
532
549
|
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
533
550
|
ORDER BY child.started_at ASC
|
|
534
|
-
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!fs$1.existsSync(o))continue;let i
|
|
551
|
+
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!fs$1.existsSync(o))continue;let i=$(o);try{let u=i.db.all(this.batchFetchTasksQuery(e,n));for(let d of u){let c=d.thread_id;r.has(c)||r.set(c,[]),r.get(c).push(Af(d));}}catch(u){throw new f("DB_ERROR","Failed to batch fetch tasks",u)}finally{i.close();}}return r}findThreadOriginsQuery(e,n){return drizzleOrm.sql`
|
|
535
552
|
WITH root AS (
|
|
536
553
|
SELECT child.thread_id, child.id, child.caller_agent_id, child.parent_task_id,
|
|
537
554
|
CASE
|
|
@@ -583,7 +600,7 @@ Message: ${n.message}
|
|
|
583
600
|
FROM tasks AS child
|
|
584
601
|
LEFT JOIN tasks AS parent ON parent.id = child.parent_task_id
|
|
585
602
|
WHERE child.id IN (${drizzleOrm.sql.join(e.map(n=>drizzleOrm.sql`${n}`),drizzleOrm.sql`, `)})
|
|
586
|
-
`}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!fs$1.existsSync(o))continue;let i
|
|
603
|
+
`}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!fs$1.existsSync(o))continue;let i=$(o);try{for(let u=0;u<e.length;u+=Fr){let d=e.slice(u,u+Fr),l=i.db.all(this.findCreatorPointersQuery(d,n)).filter(S=>!r.has(S.thread_id)),p=l.filter(S=>S.creator_task_id!==null&&S.creator_pointer_unverified===0&&S.creator_actor_kind===null).map(S=>S.creator_task_id),g=p.length>0?i.db.all(this.findTaskOriginLineageQuery(p)):[],_=new Map(g.map(S=>[S.task_id,S])),m=new Map(l.map(S=>[S.thread_id,S])),y=d.filter(S=>{if(r.has(S))return !1;let C=m.get(S);return C?!(C.creator_task_id!==null&&C.creator_pointer_unverified===0)&&C.created_by_kind===null:!0}),k=y.length>0?i.db.all(this.findThreadOriginsQuery(y,n)):[],N=new Map(k.map(S=>[S.thread_id,S]));for(let S of l){if(r.has(S.thread_id))continue;let C=qd(S,S.created_by_task_id!==null?_.get(S.created_by_task_id):void 0,N.get(S.thread_id));C&&r.set(S.thread_id,C);}for(let S of k)r.has(S.thread_id)||m.has(S.thread_id)||r.set(S.thread_id,Hr(S));}}catch(u){throw new f("DB_ERROR","Failed to fetch thread origins",u)}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(u=>Kd(s.get(u),e));return this.readThreadRowsByIds(o,n,"Failed to find threads by origin").sort(Vd)}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(Vd),s=[],o=new Map;for(let c=0;c<r.length;c+=zd){let l=r.slice(c,c+zd),p=this.findThreadOrigins(l.map(g=>g.id),e);for(let[g,_]of p)o.set(g,_);for(let g of l)if(Kd(p.get(g.id),"direct")&&(s.push(g.id),s.length===n))break;if(s.length===n)break}let i=new Map;if(s.length>0){let c=this.readThreadRowsByIds(s,e,"Failed to find recent direct threads");for(let l of c)i.set(l.id,l);}let u=[],d=new Map;for(let c of s){let l=i.get(c);if(!l)continue;u.push(l);let p=o.get(c);p&&d.set(c,p);}return {threads:u,originsByThread:d}}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let s of r){if(!fs$1.existsSync(s))continue;let o=$(s);try{return o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(u=>u.detail)}finally{o.close();}}return []}explainFindThreadOriginsPlan(e,n){if(e.length===0)return [];let r=this.resolveDbPaths();for(let s of r){if(!fs$1.existsSync(s))continue;let o=$(s);try{let i=o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery(e,n)}`),u=o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery(e)}`),d=o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery(e,n)}`);return [...i,...u,...d].map(c=>c.detail)}finally{o.close();}}return []}explainFindThreadsByOriginPlan(e,n){let r=`__thread_origin_${e}_plan__`,s=this.resolveDbPaths();for(let o of s){if(!fs$1.existsSync(o))continue;let i=$(o);try{let u=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadIdsQuery(n)}`),d=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery([r],n)}`),c=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery([r])}`),l=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery([r],n)}`);return [...u,...d,...c,...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=drizzleOrm.eq(T.id,e),i=r?drizzleOrm.and(o,drizzleOrm.eq(T.workspace_id,r)):o;if(!s.db.select({id:T.id}).from(T).where(i).limit(1).get())return;s.db.update(T).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(T.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:ee.id}).from(ee).where(drizzleOrm.eq(ee.id,n.workspaceId)).limit(1).get():void 0)?n.workspaceId:null,u=new Date().toISOString(),d=s.select({id:T.id,message_count:T.message_count,created_by_task_id:T.created_by_task_id}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get();if(d){let c={updated_at:u};n.title!==void 0&&(c.title=n.title),n.titleLocked!==void 0&&(c.title_locked=n.titleLocked?1:0),d.created_by_task_id===null&&n.createdByTaskId!=null&&d.message_count===0&&!Jd(s,e,n.createdByTaskId)&&(c.created_by_task_id=n.createdByTaskId),s.update(T).set(c).where(drizzleOrm.eq(T.id,e)).run();}else s.insert(T).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:u,updated_at:u}).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:ee.id}).from(ee).where(drizzleOrm.eq(ee.id,r)).limit(1).get():void 0)?r:null,c=i.select({id:T.id,platform:T.platform,workspace_id:T.workspace_id,message_count:T.message_count,created_by_task_id:T.created_by_task_id}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get();if(c){let p={};d&&!c.workspace_id&&(p.workspace_id=d),c.created_by_task_id===null&&s?.createdByTaskId!=null&&c.message_count===0&&!Jd(i,e,s.createdByTaskId)&&(p.created_by_task_id=s.createdByTaskId),Object.keys(p).length>0&&i.update(T).set(p).where(drizzleOrm.eq(T.id,e)).run();return}let l=new Date().toISOString();i.insert(T).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(u=>{let c=u.select({message_count:T.message_count}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get()?.message_count===0;return u.run(drizzleOrm.sql`
|
|
587
604
|
UPDATE threads
|
|
588
605
|
SET first_message = COALESCE(first_message, ${n}),
|
|
589
606
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
@@ -591,11 +608,11 @@ Message: ${n.message}
|
|
|
591
608
|
message_count = message_count + 1,
|
|
592
609
|
updated_at = ${o}
|
|
593
610
|
WHERE id = ${e}
|
|
594
|
-
`),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(T).set({last_message:n,updated_at:o}).where(drizzleOrm.eq(T.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(T).set(s).where(drizzleOrm.eq(T.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 on("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(s).some(d=>d!=="priority"&&d!=="state"))return new on("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 on("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 on("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let u=this.openHandle(true);try{let d=r?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,r)):drizzleOrm.eq(T.id,e);return u.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(d).get();if(!l)return null;let p=sn(l.metadata),g=p.threadTitle,_=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};i.priority===null?delete _.priority:i.priority!==void 0&&(_.priority=i.priority),i.state===null?delete _.state:i.state!==void 0&&(_.state=i.state),Object.keys(_).length>0?p.threadTitle=_:delete p.threadTitle;let m=Object.keys(p).length>0?JSON.stringify(p):null,y=new Date().toISOString();c.update(T).set({metadata:m,updated_at:y}).where(d).run();let k=c.select({metadata:T.metadata}).from(T).where(d).get();if(!k)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let v=Rf(k.metadata);return {threadId:e,priority:v.priority,state:v.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{let s=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e);return r.db.transaction(o=>{let i=o.select({pinned:T.pinned,metadata:T.metadata}).from(T).where(s).get();if(!i)return null;let u=i.pinned?0:1,d=sn(i.metadata);if(u){let c=n?drizzleOrm.and(drizzleOrm.eq(T.pinned,1),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.pinned,1),l=o.select({metadata:T.metadata}).from(T).where(c).all(),p=null;for(let g of l){let _=sn(g.metadata);typeof _.pinOrder=="number"&&(p===null||_.pinOrder<p)&&(p=_.pinOrder);}d.pinOrder=p===null?0:p-1;}else delete d.pinOrder;return o.update(T).set({pinned:u,metadata:Object.keys(d).length>0?JSON.stringify(d):null}).where(s).run(),{pinned:!!u}},{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=>{for(let o=0;o<e.length;o++){let i=n?drizzleOrm.and(drizzleOrm.eq(T.id,e[o]),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e[o]),u=s.select({metadata:T.metadata}).from(T).where(i).get();if(!u)continue;let d=sn(u.metadata);d.pinOrder=o+1,s.update(T).set({metadata:JSON.stringify(d)}).where(i).run();}},{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?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e),o=r.db.select({starred:T.starred}).from(T).where(s).get();if(!o)return null;let i=o.starred?0:1;return r.db.update(T).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof 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?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e);return i.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(u).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},g=p.overdrive??{},_=s?.defaultTurns??g.defaultTurns??3,m=s?.updatedBy??"ui",y=new Date().toISOString(),k,v,S,C;switch(r){case "enable-count":{let E=s?.turns??_,I=s?.consumeCurrent?Math.max(E-1,0):E;k=I>0?"count":"off",v=I,S=!0,C="count";break}case "enable-latch":{k="latch",v=0,S=!0,C="latch";break}case "disable":{k="off",v=0,S=!1;break}default:{let E=g.state??"off",I=typeof g.remaining=="number"?g.remaining:0;if(E==="count"&&I>0){let b=I-1;b<=0?(k="off",v=0):(k="count",v=b),S=!0,C="count";}else E==="latch"?(k="latch",v=0,S=!0,C="latch"):(k="off",v=0,S=!1);break}}return p.overdrive={state:k,remaining:v,defaultTurns:_,updatedAt:y,updatedBy:m},c.update(T).set({metadata:JSON.stringify(p),updated_at:y}).where(u).run(),{applied:S,appliedMode:C,state:k,remaining:v}},{behavior:"immediate"})}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to resolve overdrive",u)}finally{i.close();}}};h();it();_t();mt();ot();h();var go="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Sf(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let s=e[r];s<248&&(n+=go[s%62]);}for(;n.length<t;)n+=go[crypto.randomBytes(1)[0]%62];return n}function Fn(t){return `${t}_${Sf(8)}`}function Bd(t,e){let{createHash:n}=Ct("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+=go[i%62];return `${t}_${o}`}Et();h();var If=["urgent","high","medium","low"],Af=["investigating","in-progress","in-review","on-hold","done"],Wd="custom:";var Of=new Set(If),bf=new Set(Af);function ho(t){return typeof t=="string"&&Of.has(t)}function _o(t){if(typeof t!="string")return false;if(bf.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Wd))return false;let e=t.slice(Wd.length);return e.length>=1&&e.length<=20}function jd(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 mo(t){let e=jd(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,s={};return ho(r.priority)&&(s.priority=r.priority),_o(r.state)&&(s.state=r.state),s}function Gd(t,e){let n=jd(t)??{},r={...mo(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)}bn();var Df="regeneration_replaced";var Pf="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Lf="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",wo=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;}},Kn=class extends wo{},yo=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;}},Mf=new Set(Si),$f=new Set(Ri),Hf=new Set(Ii),Uf=new Set(Ai),Ff=50,Kd=100,Vd=280,Jd=40,qf=new Set(Oi),Hr=["queued","running"];function To(t){return qf.has(t)}function j(t){throw new f("VALIDATION",t)}function qe(t){throw new f("NOT_FOUND",t)}function M(t,e){(typeof t!="string"||t.trim().length===0)&&j(`${e} is required`);}function Bn(t={}){let e=t.actor??t,n=e.actorType??"system";return Mf.has(n)||j(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&j("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Bf(t){M(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&M(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&j("title must not be empty"),t.title.length>120&&j("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!ho(t.priority)&&j(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!_o(t.state)&&j(`invalid state: ${String(t.state)}`);}function Wf(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&j("beforeSeq and afterSeq cannot be used together");for(let[n,r]of [["beforeSeq",t.beforeSeq],["afterSeq",t.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&j(`${n} must be a non-negative integer`);let e=t.limit??Ff;return (!Number.isInteger(e)||e<1||e>Kd)&&j(`limit must be between 1 and ${Kd}`),e}function Eo(t){typeof t!="string"&&j("text is required");let e=t.trim();return e.length===0&&j("text must not be empty"),e.length>Vd&&j(`text must be at most ${Vd} characters`),e}function rt(t,e){return M(t??"",e),t}function Ro(t){Uf.has(t)||j(`invalid highlight kind: ${String(t)}`);}function jf(t){Hf.has(t)||j(`invalid highlight source: ${String(t)}`);}function Gf(t){M(t.threadId,"threadId"),M(t.workspaceId,"workspaceId");let e=t.source??"manual";jf(e),Ro(t.kind);let n=Eo(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=rt(l,"taskId");return (r!==p||s!==p)&&j("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let o=rt(r,"coversFromTaskId"),i=rt(s,"coversToTaskId"),u=t.sourceTaskId??o,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return rt(u??void 0,"sourceTaskId"),rt(d??void 0,"detectorVersion"),rt(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 zf(t,e){(!t||typeof t!="object")&&j(`candidates[${e}] is required`),Ro(t.kind);let n=Eo(t.text),r=rt(t.anchorTaskId,`candidates[${e}].anchorTaskId`),s=rt(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),o=rt(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Bd("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o}));return M(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o,contentFingerprint:i}}function Kf(t){Array.isArray(t)||j("candidates must be an array"),t.length>Jd&&j(`candidates must contain at most ${Jd} items`);let e=new Map;for(let[n,r]of t.entries()){let s=zf(r,n);e.set(s.contentFingerprint,s);}return [...e.values()]}function zn(t){let e=mo(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 Vf(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&j("event payload must be a JSON object"),e}catch(e){throw new f("VALIDATION","event payload must be JSON serializable",e)}}function Wn(t,e){return t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.thread_id,e)).get()?.maxSeq??0}function jn(t,e){return !!t.select({id:B.id}).from(B).where(drizzleOrm.eq(B.thread_id,e)).limit(1).get()}function xt(t,e){$f.has(e.type)||j(`invalid thread event type: ${String(e.type)}`);let n=Fn("the");t.insert(B).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:Vf(e.payload),created_at:e.createdAt}).run();let r=t.select().from(B).where(drizzleOrm.eq(B.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function Gn(t,e,n,r,s){let o=zn(e);xt(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 Fr(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 Ur(t,e,n,r,s,o,i){let u=s==="thread.highlight.created"?Fr(e):{before:i?Fr({...e,...i,id:e.id}):void 0,after:Fr(e)};return xt(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 Jf(t,e,n,r,s,o){return xt(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:Fr(e),...o??{}}})}var qr=class extends ge{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=de.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs$1.existsSync(n))throw new f("NOT_FOUND","Database not found");if(e){let s=de.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}let r=H(n);if(e)try{Ie(r.db,n);}catch(s){throw r.close(),s}return r}findThread(e,n,r){let s=drizzleOrm.eq(T.id,n),o=r===void 0?s:r===null?drizzleOrm.and(s,drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(s,drizzleOrm.eq(T.workspace_id,r));return e.select().from(T).where(o).limit(1).get()}findRegenerationRun(e,n,r){let s=e.select().from(U).where(drizzleOrm.eq(U.id,n)).limit(1).get();if(s&&!(r!==void 0&&!this.findThread(e,s.thread_id,r)))return s}resolveWorkspaceId(e){if(M(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:T.workspace_id}).from(T).where(drizzleOrm.eq(T.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(M(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let s=this.findThread(r.db,e,n);return s?zn(s):null}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read thread snapshot",s)}finally{r.close();}}updateSnapshot(e){Bf(e);let n=Bn(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||qe(`Thread ${e.threadId} not found`);let u=zn(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,_=c||p||g;if(!_&&!l)return u;let m=i.metadata;(p||g)&&(m=Gd(i.metadata,{priority:e.priority,state:e.state}));let y={};if(_&&(y.metadata=m,y.updated_at=r),c&&(y.title=e.title),d&&(y.title_locked=1),o.update(T).set(y).where(e.workspaceId===void 0?drizzleOrm.eq(T.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.eq(T.workspace_id,e.workspaceId))).run(),!_){let S={...i,title_locked:1};return zn(S)}let k=Wn(o,i.id)+1;jn(o,i.id)||(Gn(o,i,n,r,k),k+=1),c&&(xt(o,{threadId:i.id,seq:k,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.title,after:e.title}}),k+=1),p&&(xt(o,{threadId:i.id,seq:k,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.priority,after:e.priority}}),k+=1),g&&xt(o,{threadId:i.id,seq:k,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.state,after:e.state}});let v={...i,title:c?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return zn(v)},{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(M(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.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(M(e,"threadId"),M(n,"workspaceId"),!fs$1.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(drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,[...An]),drizzleOrm.or(drizzleOrm.isNull(a.parent_task_id),drizzleOrm.eq(a.parent_task_id,"")),drizzleOrm.sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.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){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.requestId,"requestId"),M(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&M(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||qe(`Thread ${e.threadId} not found`);let i=s.select().from(U).where(drizzleOrm.and(drizzleOrm.eq(U.thread_id,o.id),drizzleOrm.eq(U.request_id,e.requestId))).orderBy(drizzleOrm.desc(U.requested_at),drizzleOrm.desc(U.id)).limit(1).get();if(i)return {run:i,created:!1};let u=s.select().from(U).where(drizzleOrm.and(drizzleOrm.eq(U.thread_id,o.id),drizzleOrm.inArray(U.status,Hr))).orderBy(drizzleOrm.asc(U.requested_at),drizzleOrm.asc(U.id)).limit(1).get();if(u)throw new yo(u);let d=e.runId??Fn("thr");s.insert(U).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(U).where(drizzleOrm.eq(U.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(M(e,"runId"),n!==void 0&&M(n,"workspaceId"),!fs$1.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(M(e,"threadId"),M(n,"workspaceId"),M(r,"requestId"),!fs$1.existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{return this.findThread(s.db,e,n)?s.db.select().from(U).where(drizzleOrm.and(drizzleOrm.eq(U.thread_id,e),drizzleOrm.eq(U.request_id,r))).orderBy(drizzleOrm.desc(U.requested_at),drizzleOrm.desc(U.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){M(e,"runId"),n!==void 0&&M(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||qe(`Highlight regeneration run ${e} not found`),To(i.status)||j(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;o.update(U).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq(U.id,i.id),drizzleOrm.eq(U.status,"queued"))).run();let u=o.select().from(U).where(drizzleOrm.eq(U.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){M(e.runId,"runId"),M(e.errorCode,"errorCode"),e.workspaceId!==void 0&&M(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||qe(`Highlight regeneration run ${e.runId} not found`),To(o.status)||j(`invalid highlight regeneration status: ${o.status}`),o.status==="completed"||o.status==="failed")return o;s.update(U).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq(U.id,o.id),drizzleOrm.inArray(U.status,Hr))).run();let i=s.select().from(U).where(drizzleOrm.eq(U.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=Pf){M(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>s.update(U).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray(U.status,Hr)).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){M(e.runId,"runId"),M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.detectorVersion,"detectorVersion");let n=Kf(e.candidates),r=Bn(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)&&qe(`Highlight regeneration run ${e.runId} not found`),To(u.status)||j(`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||qe(`Thread ${e.threadId} not found`),u.detector_version!==e.detectorVersion&&j("detectorVersion does not match the regeneration run");let c=i.select().from($).where(drizzleOrm.eq($.thread_id,d.id)).orderBy(drizzleOrm.asc($.created_at),drizzleOrm.asc($.id)).all(),l=new Set(n.map(b=>b.contentFingerprint)),p=c.filter(b=>b.source==="auto"&&b.status==="active"&&b.revision===0&&!l.has(b.content_fingerprint??"")),g=c.filter(b=>b.source==="auto"&&b.status==="active").length,_=new Set(c.filter(b=>!p.includes(b)&&b.content_fingerprint).map(b=>b.content_fingerprint)),m=n.filter(b=>!_.has(b.contentFingerprint)),y=new Date().toISOString(),k=Wn(i,d.id)+1;jn(i,d.id)||(Gn(i,d,r,y,k),k+=1);for(let b of p)i.delete($).where(drizzleOrm.eq($.id,b.id)).run(),Jf(i,b,r,y,k,{runId:e.runId,reason:Df}),k+=1;let v=0,S=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let b of m){let Q=Fn("thl");i.insert($).values({id:Q,thread_id:d.id,source:"auto",kind:b.kind,status:"active",text:b.text,covers_from_task_id:b.coversFromTaskId,covers_to_task_id:b.coversToTaskId,revision:0,created_at:y,updated_at:y,agent_id:S,source_task_id:b.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:b.contentFingerprint,dismissed_at:null}).run();let fe=i.select().from($).where(drizzleOrm.eq($.id,Q)).get();if(!fe)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");Ur(i,fe,r,y,"thread.highlight.created",k),k+=1,v+=1;}let E=i.select().from($).where(drizzleOrm.eq($.thread_id,d.id)).all().filter(b=>b.source==="auto"&&b.status==="active").length;xt(i,{threadId:d.id,seq:k,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:y,payload:{runId:u.id,detectorVersion:e.detectorVersion,previousAutoCount:g,newAutoCount:E,deletedCount:p.length,createdCount:v}}),i.update(U).set({status:"completed",started_at:u.started_at??y,completed_at:y,error_code:null,previous_auto_count:g,new_auto_count:E}).where(drizzleOrm.and(drizzleOrm.eq(U.id,u.id),drizzleOrm.inArray(U.status,Hr))).run();let I=i.select().from(U).where(drizzleOrm.eq(U.id,u.id)).get();if(!I)throw new f("DB_ERROR","Highlight regeneration completion did not return a row");return {run:I,deletedCount:p.length,createdCount:v,previousAutoCount:g,newAutoCount:E}},{behavior:"immediate"})}catch(i){if(o)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Lf});}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;M(s.threadId,"threadId"),M(s.workspaceId,"workspaceId");let o=Wf(s);if(!fs$1.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:drizzleOrm.sql`COALESCE(MAX(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.thread_id,s.threadId)).get()?.maxSeq??0,d;s.beforeSeq!==void 0?d=i.db.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.lt(B.seq,s.beforeSeq))).orderBy(drizzleOrm.desc(B.seq)).limit(o+1).all().reverse():s.afterSeq!==void 0?d=i.db.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.sql`${B.seq} > ${s.afterSeq}`)).orderBy(drizzleOrm.asc(B.seq)).limit(o+1).all():d=i.db.select().from(B).where(drizzleOrm.eq(B.thread_id,s.threadId)).orderBy(drizzleOrm.desc(B.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:B.id}).from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.lt(B.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=Gf(e),r=Bn(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||qe(`Thread ${e.threadId} not found`),n.source==="auto"){let g=i.select().from($).where(drizzleOrm.and(drizzleOrm.eq($.thread_id,e.threadId),drizzleOrm.eq($.source_task_id,n.sourceTaskId),drizzleOrm.eq($.detector_version,n.detectorVersion),drizzleOrm.eq($.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc($.created_at),drizzleOrm.asc($.id)).limit(1).get();if(g)return g}let d=e.id??Fn("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($).values(c).run();let l=i.select().from($).where(drizzleOrm.eq($.id,d)).get();if(!l)throw new f("DB_ERROR","Highlight insert did not return a row");let p=Wn(i,u.id)+1;return jn(i,u.id)||(Gn(i,u,r,s,p),p+=1),Ur(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){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&j("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&j("highlight update requires at least one field"),e.kind!==void 0&&Ro(e.kind);let n=e.text===void 0?void 0:Eo(e.text),r=Bn(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||qe(`Thread ${e.threadId} not found`);let d=i.select().from($).where(drizzleOrm.and(drizzleOrm.eq($.id,e.highlightId),drizzleOrm.eq($.thread_id,u.id))).limit(1).get();if(d||qe(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new Kn(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new Kn(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)&&j("highlight projection is incomplete");let _=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"&&_?"manual":d.source;if(!(_||m!==d.source))return d;let k=d.revision+1;i.update($).set({source:m,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:g,revision:k,updated_at:s}).where(drizzleOrm.and(drizzleOrm.eq($.id,d.id),drizzleOrm.eq($.revision,d.revision))).run();let v=i.select().from($).where(drizzleOrm.eq($.id,d.id)).get();if(!v)throw new f("DB_ERROR","Highlight update did not return a row");let S=Wn(i,u.id)+1;return jn(i,u.id)||(Gn(i,u,r,s,S),S+=1),Ur(i,v,r,s,"thread.highlight.updated",S,d),v},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to update thread highlight",i)}finally{o.close();}}dismissHighlight(e){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&j("expectedRevision must be a non-negative integer");let n=Bn(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||qe(`Thread ${e.threadId} not found`);let u=o.select().from($).where(drizzleOrm.and(drizzleOrm.eq($.id,e.highlightId),drizzleOrm.eq($.thread_id,i.id))).limit(1).get();if(u||qe(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new Kn(i.id,u.id,e.expectedRevision,u.revision);if(u.status==="dismissed")return u;let d=u.revision+1;o.update($).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq($.id,u.id),drizzleOrm.eq($.revision,u.revision))).run();let c=o.select().from($).where(drizzleOrm.eq($.id,u.id)).get();if(!c)throw new f("DB_ERROR","Highlight dismissal did not return a row");let l=Wn(o,i.id)+1;return jn(o,i.id)||(Gn(o,i,n,r,l),l+=1),Ur(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(M(e,"threadId"),M(n,"workspaceId"),r.taskId!==void 0&&M(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&M(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&M(r.coversToTaskId,"coversToTaskId"),!fs$1.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($).where(drizzleOrm.and(drizzleOrm.eq($.thread_id,e),drizzleOrm.eq($.status,"active"))).orderBy(drizzleOrm.asc($.created_at),drizzleOrm.asc($.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let u=s.db.all(drizzleOrm.sql`
|
|
611
|
+
`),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(T).set({last_message:n,updated_at:o}).where(drizzleOrm.eq(T.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(T).set(s).where(drizzleOrm.eq(T.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 an("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(s).some(d=>d!=="priority"&&d!=="state"))return new an("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 an("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 an("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let u=this.openHandle(true);try{let d=r?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,r)):drizzleOrm.eq(T.id,e);return u.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(d).get();if(!l)return null;let p=dn(l.metadata),g=p.threadTitle,_=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};i.priority===null?delete _.priority:i.priority!==void 0&&(_.priority=i.priority),i.state===null?delete _.state:i.state!==void 0&&(_.state=i.state),Object.keys(_).length>0?p.threadTitle=_:delete p.threadTitle;let m=Object.keys(p).length>0?JSON.stringify(p):null,y=new Date().toISOString();c.update(T).set({metadata:m,updated_at:y}).where(d).run();let k=c.select({metadata:T.metadata}).from(T).where(d).get();if(!k)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let N=Cf(k.metadata);return {threadId:e,priority:N.priority,state:N.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=>Df(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=>Pf(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?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e),o=r.db.select({starred:T.starred}).from(T).where(s).get();if(!o)return null;let i=o.starred?0:1;return r.db.update(T).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof 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?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e);return i.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(u).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},g=p.overdrive??{},_=s?.defaultTurns??g.defaultTurns??3,m=s?.updatedBy??"ui",y=new Date().toISOString(),k,N,S,C;switch(r){case "enable-count":{let E=s?.turns??_,I=s?.consumeCurrent?Math.max(E-1,0):E;k=I>0?"count":"off",N=I,S=!0,C="count";break}case "enable-latch":{k="latch",N=0,S=!0,C="latch";break}case "disable":{k="off",N=0,S=!1;break}default:{let E=g.state??"off",I=typeof g.remaining=="number"?g.remaining:0;if(E==="count"&&I>0){let b=I-1;b<=0?(k="off",N=0):(k="count",N=b),S=!0,C="count";}else E==="latch"?(k="latch",N=0,S=!0,C="latch"):(k="off",N=0,S=!1);break}}return p.overdrive={state:k,remaining:N,defaultTurns:_,updatedAt:y,updatedBy:m},c.update(T).set({metadata:JSON.stringify(p),updated_at:y}).where(u).run(),{applied:S,appliedMode:C,state:k,remaining:N}},{behavior:"immediate"})}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to resolve overdrive",u)}finally{i.close();}}};h();at();mt();kt();it();h();var yo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Lf(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let s=e[r];s<248&&(n+=yo[s%62]);}for(;n.length<t;)n+=yo[crypto.randomBytes(1)[0]%62];return n}function Gn(t){return `${t}_${Lf(8)}`}function Yd(t,e){let{createHash:n}=Pt("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+=yo[i%62];return `${t}_${o}`}St();h();var Mf=["urgent","high","medium","low"],$f=["investigating","in-progress","in-review","on-hold","done"],Qd="custom:";var Hf=new Set(Mf),Uf=new Set($f);function Eo(t){return typeof t=="string"&&Hf.has(t)}function Ro(t){if(typeof t!="string")return false;if(Uf.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Qd))return false;let e=t.slice(Qd.length);return e.length>=1&&e.length<=20}function Zd(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 So(t){let e=Zd(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,s={};return Eo(r.priority)&&(s.priority=r.priority),Ro(r.state)&&(s.state=r.state),s}function eu(t,e){let n=Zd(t)??{},r={...So(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)}Cn();var jf="regeneration_replaced";var Gf="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var zf="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Oo=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;}},Qn=class extends Oo{},bo=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;}},Kf=new Set(xi),Vf=new Set(vi),Jf=new Set(Ci),Xf=new Set(Di),Yf=50,nu=100,ru=280,su=40,Qf=new Set(Pi),Br=["queued","running"];function Ao(t){return Qf.has(t)}function j(t){throw new f("VALIDATION",t)}function We(t){throw new f("NOT_FOUND",t)}function M(t,e){(typeof t!="string"||t.trim().length===0)&&j(`${e} is required`);}function Kn(t={}){let e=t.actor??t,n=e.actorType??"system";return Kf.has(n)||j(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&j("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Zf(t){M(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&M(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&j("title must not be empty"),t.title.length>120&&j("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!Eo(t.priority)&&j(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Ro(t.state)&&j(`invalid state: ${String(t.state)}`);}function eg(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&j("beforeSeq and afterSeq cannot be used together");for(let[n,r]of [["beforeSeq",t.beforeSeq],["afterSeq",t.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&j(`${n} must be a non-negative integer`);let e=t.limit??Yf;return (!Number.isInteger(e)||e<1||e>nu)&&j(`limit must be between 1 and ${nu}`),e}function No(t){typeof t!="string"&&j("text is required");let e=t.trim();return e.length===0&&j("text must not be empty"),e.length>ru&&j(`text must be at most ${ru} characters`),e}function st(t,e){return M(t??"",e),t}function vo(t){Xf.has(t)||j(`invalid highlight kind: ${String(t)}`);}function tg(t){Jf.has(t)||j(`invalid highlight source: ${String(t)}`);}function ng(t){M(t.threadId,"threadId"),M(t.workspaceId,"workspaceId");let e=t.source??"manual";tg(e),vo(t.kind);let n=No(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=st(l,"taskId");return (r!==p||s!==p)&&j("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let o=st(r,"coversFromTaskId"),i=st(s,"coversToTaskId"),u=t.sourceTaskId??o,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return st(u??void 0,"sourceTaskId"),st(d??void 0,"detectorVersion"),st(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 rg(t,e){(!t||typeof t!="object")&&j(`candidates[${e}] is required`),vo(t.kind);let n=No(t.text),r=st(t.anchorTaskId,`candidates[${e}].anchorTaskId`),s=st(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),o=st(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Yd("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o}));return M(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o,contentFingerprint:i}}function sg(t){Array.isArray(t)||j("candidates must be an array"),t.length>su&&j(`candidates must contain at most ${su} items`);let e=new Map;for(let[n,r]of t.entries()){let s=rg(r,n);e.set(s.contentFingerprint,s);}return [...e.values()]}function Yn(t){let e=So(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 og(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&j("event payload must be a JSON object"),e}catch(e){throw new f("VALIDATION","event payload must be JSON serializable",e)}}function Vn(t,e){return t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.thread_id,e)).get()?.maxSeq??0}function Jn(t,e){return !!t.select({id:B.id}).from(B).where(drizzleOrm.eq(B.thread_id,e)).limit(1).get()}function Dt(t,e){Vf.has(e.type)||j(`invalid thread event type: ${String(e.type)}`);let n=Gn("the");t.insert(B).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:og(e.payload),created_at:e.createdAt}).run();let r=t.select().from(B).where(drizzleOrm.eq(B.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function Xn(t,e,n,r,s){let o=Yn(e);Dt(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 jr(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 Wr(t,e,n,r,s,o,i){let u=s==="thread.highlight.created"?jr(e):{before:i?jr({...e,...i,id:e.id}):void 0,after:jr(e)};return Dt(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 ig(t,e,n,r,s,o){return Dt(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:jr(e),...o??{}}})}var Gr=class extends _e{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ce.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs$1.existsSync(n))throw new f("NOT_FOUND","Database not found");if(e){let s=ce.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}let r=$(n);if(e)try{Oe(r.db,n);}catch(s){throw r.close(),s}return r}findThread(e,n,r){let s=drizzleOrm.eq(T.id,n),o=r===void 0?s:r===null?drizzleOrm.and(s,drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(s,drizzleOrm.eq(T.workspace_id,r));return e.select().from(T).where(o).limit(1).get()}findRegenerationRun(e,n,r){let s=e.select().from(U).where(drizzleOrm.eq(U.id,n)).limit(1).get();if(s&&!(r!==void 0&&!this.findThread(e,s.thread_id,r)))return s}resolveWorkspaceId(e){if(M(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:T.workspace_id}).from(T).where(drizzleOrm.eq(T.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(M(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let s=this.findThread(r.db,e,n);return s?Yn(s):null}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read thread snapshot",s)}finally{r.close();}}updateSnapshot(e){Zf(e);let n=Kn(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||We(`Thread ${e.threadId} not found`);let u=Yn(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,_=c||p||g;if(!_&&!l)return u;let m=i.metadata;(p||g)&&(m=eu(i.metadata,{priority:e.priority,state:e.state}));let y={};if(_&&(y.metadata=m,y.updated_at=r),c&&(y.title=e.title),d&&(y.title_locked=1),o.update(T).set(y).where(e.workspaceId===void 0?drizzleOrm.eq(T.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.eq(T.workspace_id,e.workspaceId))).run(),!_){let S={...i,title_locked:1};return Yn(S)}let k=Vn(o,i.id)+1;Jn(o,i.id)||(Xn(o,i,n,r,k),k+=1),c&&(Dt(o,{threadId:i.id,seq:k,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.title,after:e.title}}),k+=1),p&&(Dt(o,{threadId:i.id,seq:k,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.priority,after:e.priority}}),k+=1),g&&Dt(o,{threadId:i.id,seq:k,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.state,after:e.state}});let N={...i,title:c?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return Yn(N)},{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(M(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.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(M(e,"threadId"),M(n,"workspaceId"),!fs$1.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(drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,[...vn]),drizzleOrm.or(drizzleOrm.isNull(a.parent_task_id),drizzleOrm.eq(a.parent_task_id,"")),drizzleOrm.sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.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){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.requestId,"requestId"),M(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&M(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||We(`Thread ${e.threadId} not found`);let i=s.select().from(U).where(drizzleOrm.and(drizzleOrm.eq(U.thread_id,o.id),drizzleOrm.eq(U.request_id,e.requestId))).orderBy(drizzleOrm.desc(U.requested_at),drizzleOrm.desc(U.id)).limit(1).get();if(i)return {run:i,created:!1};let u=s.select().from(U).where(drizzleOrm.and(drizzleOrm.eq(U.thread_id,o.id),drizzleOrm.inArray(U.status,Br))).orderBy(drizzleOrm.asc(U.requested_at),drizzleOrm.asc(U.id)).limit(1).get();if(u)throw new bo(u);let d=e.runId??Gn("thr");s.insert(U).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(U).where(drizzleOrm.eq(U.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(M(e,"runId"),n!==void 0&&M(n,"workspaceId"),!fs$1.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(M(e,"threadId"),M(n,"workspaceId"),M(r,"requestId"),!fs$1.existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{return this.findThread(s.db,e,n)?s.db.select().from(U).where(drizzleOrm.and(drizzleOrm.eq(U.thread_id,e),drizzleOrm.eq(U.request_id,r))).orderBy(drizzleOrm.desc(U.requested_at),drizzleOrm.desc(U.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){M(e,"runId"),n!==void 0&&M(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||We(`Highlight regeneration run ${e} not found`),Ao(i.status)||j(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;o.update(U).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq(U.id,i.id),drizzleOrm.eq(U.status,"queued"))).run();let u=o.select().from(U).where(drizzleOrm.eq(U.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){M(e.runId,"runId"),M(e.errorCode,"errorCode"),e.workspaceId!==void 0&&M(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||We(`Highlight regeneration run ${e.runId} not found`),Ao(o.status)||j(`invalid highlight regeneration status: ${o.status}`),o.status==="completed"||o.status==="failed")return o;s.update(U).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq(U.id,o.id),drizzleOrm.inArray(U.status,Br))).run();let i=s.select().from(U).where(drizzleOrm.eq(U.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=Gf){M(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>s.update(U).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray(U.status,Br)).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){M(e.runId,"runId"),M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.detectorVersion,"detectorVersion");let n=sg(e.candidates),r=Kn(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)&&We(`Highlight regeneration run ${e.runId} not found`),Ao(u.status)||j(`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||We(`Thread ${e.threadId} not found`),u.detector_version!==e.detectorVersion&&j("detectorVersion does not match the regeneration run");let c=i.select().from(H).where(drizzleOrm.eq(H.thread_id,d.id)).orderBy(drizzleOrm.asc(H.created_at),drizzleOrm.asc(H.id)).all(),l=new Set(n.map(b=>b.contentFingerprint)),p=c.filter(b=>b.source==="auto"&&b.status==="active"&&b.revision===0&&!l.has(b.content_fingerprint??"")),g=c.filter(b=>b.source==="auto"&&b.status==="active").length,_=new Set(c.filter(b=>!p.includes(b)&&b.content_fingerprint).map(b=>b.content_fingerprint)),m=n.filter(b=>!_.has(b.contentFingerprint)),y=new Date().toISOString(),k=Vn(i,d.id)+1;Jn(i,d.id)||(Xn(i,d,r,y,k),k+=1);for(let b of p)i.delete(H).where(drizzleOrm.eq(H.id,b.id)).run(),ig(i,b,r,y,k,{runId:e.runId,reason:jf}),k+=1;let N=0,S=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let b of m){let Q=Gn("thl");i.insert(H).values({id:Q,thread_id:d.id,source:"auto",kind:b.kind,status:"active",text:b.text,covers_from_task_id:b.coversFromTaskId,covers_to_task_id:b.coversToTaskId,revision:0,created_at:y,updated_at:y,agent_id:S,source_task_id:b.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:b.contentFingerprint,dismissed_at:null}).run();let he=i.select().from(H).where(drizzleOrm.eq(H.id,Q)).get();if(!he)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");Wr(i,he,r,y,"thread.highlight.created",k),k+=1,N+=1;}let E=i.select().from(H).where(drizzleOrm.eq(H.thread_id,d.id)).all().filter(b=>b.source==="auto"&&b.status==="active").length;Dt(i,{threadId:d.id,seq:k,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:y,payload:{runId:u.id,detectorVersion:e.detectorVersion,previousAutoCount:g,newAutoCount:E,deletedCount:p.length,createdCount:N}}),i.update(U).set({status:"completed",started_at:u.started_at??y,completed_at:y,error_code:null,previous_auto_count:g,new_auto_count:E}).where(drizzleOrm.and(drizzleOrm.eq(U.id,u.id),drizzleOrm.inArray(U.status,Br))).run();let I=i.select().from(U).where(drizzleOrm.eq(U.id,u.id)).get();if(!I)throw new f("DB_ERROR","Highlight regeneration completion did not return a row");return {run:I,deletedCount:p.length,createdCount:N,previousAutoCount:g,newAutoCount:E}},{behavior:"immediate"})}catch(i){if(o)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:zf});}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;M(s.threadId,"threadId"),M(s.workspaceId,"workspaceId");let o=eg(s);if(!fs$1.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:drizzleOrm.sql`COALESCE(MAX(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.thread_id,s.threadId)).get()?.maxSeq??0,d;s.beforeSeq!==void 0?d=i.db.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.lt(B.seq,s.beforeSeq))).orderBy(drizzleOrm.desc(B.seq)).limit(o+1).all().reverse():s.afterSeq!==void 0?d=i.db.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.sql`${B.seq} > ${s.afterSeq}`)).orderBy(drizzleOrm.asc(B.seq)).limit(o+1).all():d=i.db.select().from(B).where(drizzleOrm.eq(B.thread_id,s.threadId)).orderBy(drizzleOrm.desc(B.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:B.id}).from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.lt(B.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=ng(e),r=Kn(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||We(`Thread ${e.threadId} not found`),n.source==="auto"){let g=i.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.thread_id,e.threadId),drizzleOrm.eq(H.source_task_id,n.sourceTaskId),drizzleOrm.eq(H.detector_version,n.detectorVersion),drizzleOrm.eq(H.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc(H.created_at),drizzleOrm.asc(H.id)).limit(1).get();if(g)return g}let d=e.id??Gn("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(H).values(c).run();let l=i.select().from(H).where(drizzleOrm.eq(H.id,d)).get();if(!l)throw new f("DB_ERROR","Highlight insert did not return a row");let p=Vn(i,u.id)+1;return Jn(i,u.id)||(Xn(i,u,r,s,p),p+=1),Wr(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){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&j("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&j("highlight update requires at least one field"),e.kind!==void 0&&vo(e.kind);let n=e.text===void 0?void 0:No(e.text),r=Kn(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||We(`Thread ${e.threadId} not found`);let d=i.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.id,e.highlightId),drizzleOrm.eq(H.thread_id,u.id))).limit(1).get();if(d||We(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new Qn(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new Qn(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)&&j("highlight projection is incomplete");let _=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"&&_?"manual":d.source;if(!(_||m!==d.source))return d;let k=d.revision+1;i.update(H).set({source:m,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:g,revision:k,updated_at:s}).where(drizzleOrm.and(drizzleOrm.eq(H.id,d.id),drizzleOrm.eq(H.revision,d.revision))).run();let N=i.select().from(H).where(drizzleOrm.eq(H.id,d.id)).get();if(!N)throw new f("DB_ERROR","Highlight update did not return a row");let S=Vn(i,u.id)+1;return Jn(i,u.id)||(Xn(i,u,r,s,S),S+=1),Wr(i,N,r,s,"thread.highlight.updated",S,d),N},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to update thread highlight",i)}finally{o.close();}}dismissHighlight(e){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&j("expectedRevision must be a non-negative integer");let n=Kn(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||We(`Thread ${e.threadId} not found`);let u=o.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.id,e.highlightId),drizzleOrm.eq(H.thread_id,i.id))).limit(1).get();if(u||We(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new Qn(i.id,u.id,e.expectedRevision,u.revision);if(u.status==="dismissed")return u;let d=u.revision+1;o.update(H).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(H.id,u.id),drizzleOrm.eq(H.revision,u.revision))).run();let c=o.select().from(H).where(drizzleOrm.eq(H.id,u.id)).get();if(!c)throw new f("DB_ERROR","Highlight dismissal did not return a row");let l=Vn(o,i.id)+1;return Jn(o,i.id)||(Xn(o,i,n,r,l),l+=1),Wr(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(M(e,"threadId"),M(n,"workspaceId"),r.taskId!==void 0&&M(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&M(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&M(r.coversToTaskId,"coversToTaskId"),!fs$1.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(H).where(drizzleOrm.and(drizzleOrm.eq(H.thread_id,e),drizzleOrm.eq(H.status,"active"))).orderBy(drizzleOrm.asc(H.created_at),drizzleOrm.asc(H.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let u=s.db.all(drizzleOrm.sql`
|
|
595
612
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
596
613
|
ORDER BY started_at ASC, id ASC
|
|
597
|
-
`),d=new Map(u.map((g,_)=>[g.id,_])),c=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(g=>{let _=d.get(g.covers_from_task_id),m=d.get(g.covers_to_task_id);if(_===void 0||m===void 0)return !1;let y=Math.min(_,m),k=Math.max(_,m);return !(c!==void 0&&(c<y||c>k)||l!==void 0&&k<l||p!==void 0&&y>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)}};h();it();_t();mt();ot();Et();cs();var X=class extends f{reason;constructor(e,n="VALIDATION",r=e,s){super(n,r,s),this.name="CommonCodeRepositoryError",this.reason=e;}},Yd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function sg(){let t=crypto.randomBytes(16),e="";for(let n of t)e+=Yd[n%Yd.length];return e.slice(0,12)}function Qd(){return `c_${sg()}`}function og(t){return typeof t=="string"&&ds.includes(t)}function ig(t){return typeof t=="string"&&us.includes(t)}function cn(t){if(!og(t))throw new X("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Zd(t){if(!ig(t))throw new X("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function eu(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new X("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function ln(t){if(typeof t!="string"||t.trim().length===0)throw new X("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Br(t){if(typeof t!="string"||t.trim().length===0)throw new X("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function gt(t,e){return drizzleOrm.and(drizzleOrm.eq(x.code_group,t),drizzleOrm.or(drizzleOrm.isNull(x.workspace_id),drizzleOrm.eq(x.workspace_id,e)))}var Wr=class extends ge{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=de.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs$1.existsSync(n))throw new f("NOT_FOUND","Database not found");e&&fs$1.mkdirSync(de.dirname(n),{recursive:true});let r=H(n);if(e)try{Ie(r.db,n);}catch(s){throw r.close(),s}return r}listSelectable(e,n){if(cn(e),ln(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(x).where(drizzleOrm.and(gt(e,n),drizzleOrm.eq(x.is_archived,0))).orderBy(drizzleOrm.asc(x.sort_order),drizzleOrm.asc(x.code)).all()}catch(s){throw new f("DB_ERROR","Failed to list selectable common codes",s)}finally{r.close();}}listForHistory(e,n){if(cn(e),ln(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(x).where(gt(e,n)).orderBy(drizzleOrm.asc(x.sort_order),drizzleOrm.asc(x.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(cn(n),ln(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new X("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let s of e.codes)Br(s);if(new Set(e.codes).size!==e.codes.length)throw new X("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new X("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(x).where(gt(n,e.workspaceId)).all(),i=o.filter(_=>_.is_archived===0),u=new Set(o.map(_=>_.code)),d=new Set(i.map(_=>_.code)),c=e.codes.find(_=>!u.has(_));if(c)throw new X("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${c}`);if(e.codes.length!==i.length||e.codes.some(_=>!d.has(_)))throw new X("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let l=new Map(i.map(_=>[_.code,_])),p=e.codes.map(_=>{let m=l.get(_);if(!m)throw new X("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${_}`);return m}),g;for(let[_,m]of p.entries())m.sort_order!==_&&(g??=new Date().toISOString(),s.update(x).set({sort_order:_,updated_at:g}).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,n),drizzleOrm.eq(x.code,m.code))).run());return s.select().from(x).where(gt(n,e.workspaceId)).orderBy(drizzleOrm.asc(x.sort_order),drizzleOrm.asc(x.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(cn(e),Br(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e),drizzleOrm.eq(x.code,n))).limit(1).get()??null}catch(s){throw new f("DB_ERROR","Failed to resolve common code",s)}finally{r.close();}}createThreadState(e){ln(e.workspaceId);let n=eu(e.name);Zd(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{if(s.select({code:x.code}).from(x).where(drizzleOrm.and(gt("THREAD_STATE",e.workspaceId),drizzleOrm.eq(x.is_archived,0),drizzleOrm.eq(x.code_name,n))).limit(1).get())throw new X("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=s.select({maxSortOrder:drizzleOrm.sql`max(${x.sort_order})`}).from(x).where(gt("THREAD_STATE",e.workspaceId)).get(),u=new Date().toISOString(),d=Qd();for(;s.select({code:x.code}).from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,"THREAD_STATE"),drizzleOrm.eq(x.code,d))).limit(1).get();)d=Qd();s.insert(x).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:u,updated_at:u}).run();let c=s.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,"THREAD_STATE"),drizzleOrm.eq(x.code,d))).limit(1).get();if(!c)throw new f("DB_ERROR","Created common code could not be read back");return c},{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(cn(e.group),Br(e.code),ln(e.workspaceId),e.name===void 0&&e.color===void 0)throw new X("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:eu(e.name);e.color!==void 0&&Zd(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{let o=s.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e.group),drizzleOrm.eq(x.code,e.code))).limit(1).get();if(!o)throw new X("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 X("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&o.is_archived===0){let d=drizzleOrm.and(gt(e.group,e.workspaceId),drizzleOrm.eq(x.is_archived,0));if(s.select({code:x.code}).from(x).where(drizzleOrm.and(d,drizzleOrm.eq(x.code_name,n),drizzleOrm.sql`${x.code} <> ${e.code}`)).limit(1).get())throw new X("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(x).set(i).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e.group),drizzleOrm.eq(x.code,e.code))).run();let u=s.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e.group),drizzleOrm.eq(x.code,e.code))).limit(1).get();if(!u)throw new f("DB_ERROR","Updated common code could not be read back");return u},{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(cn(e),Br(n),ln(r),typeof s!="boolean")throw new X("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let o=this.openHandle(true);try{return o.db.transaction(i=>{let u=i.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e),drizzleOrm.eq(x.code,n))).limit(1).get();if(!u)throw new X("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(u.is_builtin===1)throw new X("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(u,r),!s&&u.code_name!==null&&i.select({code:x.code}).from(x).where(drizzleOrm.and(gt(e,r),drizzleOrm.eq(x.is_archived,0),drizzleOrm.eq(x.code_name,u.code_name),drizzleOrm.ne(x.code,n))).limit(1).get())throw new X("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${u.code_name}`);i.update(x).set({is_archived:s?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e),drizzleOrm.eq(x.code,n))).run();let d=i.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e),drizzleOrm.eq(x.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 X("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};Ft();bn();h();var Be={threadContext:"crewx_thread_context",apps:"apps",appsGuidance:"apps_guidance",availableApps:"available_apps",crewxUiState:"crewx_ui_state"};function ug(t){return t.replace(new RegExp(`<${Be.threadContext}\\b[^>]*>[\\s\\S]*?<\\/${Be.threadContext}>`,"g"),"").replace(new RegExp(`<${Be.apps}\\b[^>]*>[\\s\\S]*?<\\/${Be.apps}>`,"g"),"").replace(new RegExp(`<${Be.appsGuidance}\\b[^>]*>[\\s\\S]*?<\\/${Be.appsGuidance}>`,"g"),"").replace(new RegExp(`<${Be.availableApps}\\b[^>]*>[\\s\\S]*?<\\/${Be.availableApps}>`,"g"),"").replace(new RegExp(`<${Be.crewxUiState}\\b[^>]*>[\\s\\S]*?<\\/${Be.crewxUiState}>`,"g"),"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
614
|
+
`),d=new Map(u.map((g,_)=>[g.id,_])),c=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(g=>{let _=d.get(g.covers_from_task_id),m=d.get(g.covers_to_task_id);if(_===void 0||m===void 0)return !1;let y=Math.min(_,m),k=Math.max(_,m);return !(c!==void 0&&(c<y||c>k)||l!==void 0&&k<l||p!==void 0&&y>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)}};h();at();mt();kt();it();St();fs();var X=class extends f{reason;constructor(e,n="VALIDATION",r=e,s){super(n,r,s),this.name="CommonCodeRepositoryError",this.reason=e;}},iu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function hg(){let t=crypto.randomBytes(16),e="";for(let n of t)e+=iu[n%iu.length];return e.slice(0,12)}function au(){return `c_${hg()}`}function _g(t){return typeof t=="string"&&ls.includes(t)}function mg(t){return typeof t=="string"&&ps.includes(t)}function pn(t){if(!_g(t))throw new X("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function du(t){if(!mg(t))throw new X("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function uu(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new X("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function fn(t){if(typeof t!="string"||t.trim().length===0)throw new X("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function zr(t){if(typeof t!="string"||t.trim().length===0)throw new X("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function ht(t,e){return drizzleOrm.and(drizzleOrm.eq(x.code_group,t),drizzleOrm.or(drizzleOrm.isNull(x.workspace_id),drizzleOrm.eq(x.workspace_id,e)))}var Kr=class extends _e{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ce.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs$1.existsSync(n))throw new f("NOT_FOUND","Database not found");e&&fs$1.mkdirSync(ce.dirname(n),{recursive:true});let r=$(n);if(e)try{Oe(r.db,n);}catch(s){throw r.close(),s}return r}listSelectable(e,n){if(pn(e),fn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(x).where(drizzleOrm.and(ht(e,n),drizzleOrm.eq(x.is_archived,0))).orderBy(drizzleOrm.asc(x.sort_order),drizzleOrm.asc(x.code)).all()}catch(s){throw new f("DB_ERROR","Failed to list selectable common codes",s)}finally{r.close();}}listForHistory(e,n){if(pn(e),fn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(x).where(ht(e,n)).orderBy(drizzleOrm.asc(x.sort_order),drizzleOrm.asc(x.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(pn(n),fn(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new X("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let s of e.codes)zr(s);if(new Set(e.codes).size!==e.codes.length)throw new X("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new X("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(x).where(ht(n,e.workspaceId)).all(),i=o.filter(_=>_.is_archived===0),u=new Set(o.map(_=>_.code)),d=new Set(i.map(_=>_.code)),c=e.codes.find(_=>!u.has(_));if(c)throw new X("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${c}`);if(e.codes.length!==i.length||e.codes.some(_=>!d.has(_)))throw new X("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let l=new Map(i.map(_=>[_.code,_])),p=e.codes.map(_=>{let m=l.get(_);if(!m)throw new X("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${_}`);return m}),g;for(let[_,m]of p.entries())m.sort_order!==_&&(g??=new Date().toISOString(),s.update(x).set({sort_order:_,updated_at:g}).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,n),drizzleOrm.eq(x.code,m.code))).run());return s.select().from(x).where(ht(n,e.workspaceId)).orderBy(drizzleOrm.asc(x.sort_order),drizzleOrm.asc(x.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(pn(e),zr(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e),drizzleOrm.eq(x.code,n))).limit(1).get()??null}catch(s){throw new f("DB_ERROR","Failed to resolve common code",s)}finally{r.close();}}createThreadState(e){fn(e.workspaceId);let n=uu(e.name);du(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{if(s.select({code:x.code}).from(x).where(drizzleOrm.and(ht("THREAD_STATE",e.workspaceId),drizzleOrm.eq(x.is_archived,0),drizzleOrm.eq(x.code_name,n))).limit(1).get())throw new X("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=s.select({maxSortOrder:drizzleOrm.sql`max(${x.sort_order})`}).from(x).where(ht("THREAD_STATE",e.workspaceId)).get(),u=new Date().toISOString(),d=au();for(;s.select({code:x.code}).from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,"THREAD_STATE"),drizzleOrm.eq(x.code,d))).limit(1).get();)d=au();s.insert(x).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:u,updated_at:u}).run();let c=s.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,"THREAD_STATE"),drizzleOrm.eq(x.code,d))).limit(1).get();if(!c)throw new f("DB_ERROR","Created common code could not be read back");return c},{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(pn(e.group),zr(e.code),fn(e.workspaceId),e.name===void 0&&e.color===void 0)throw new X("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:uu(e.name);e.color!==void 0&&du(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{let o=s.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e.group),drizzleOrm.eq(x.code,e.code))).limit(1).get();if(!o)throw new X("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 X("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&o.is_archived===0){let d=drizzleOrm.and(ht(e.group,e.workspaceId),drizzleOrm.eq(x.is_archived,0));if(s.select({code:x.code}).from(x).where(drizzleOrm.and(d,drizzleOrm.eq(x.code_name,n),drizzleOrm.sql`${x.code} <> ${e.code}`)).limit(1).get())throw new X("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(x).set(i).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e.group),drizzleOrm.eq(x.code,e.code))).run();let u=s.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e.group),drizzleOrm.eq(x.code,e.code))).limit(1).get();if(!u)throw new f("DB_ERROR","Updated common code could not be read back");return u},{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(pn(e),zr(n),fn(r),typeof s!="boolean")throw new X("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let o=this.openHandle(true);try{return o.db.transaction(i=>{let u=i.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e),drizzleOrm.eq(x.code,n))).limit(1).get();if(!u)throw new X("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(u.is_builtin===1)throw new X("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(u,r),!s&&u.code_name!==null&&i.select({code:x.code}).from(x).where(drizzleOrm.and(ht(e,r),drizzleOrm.eq(x.is_archived,0),drizzleOrm.eq(x.code_name,u.code_name),drizzleOrm.ne(x.code,n))).limit(1).get())throw new X("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${u.code_name}`);i.update(x).set({is_archived:s?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e),drizzleOrm.eq(x.code,n))).run();let d=i.select().from(x).where(drizzleOrm.and(drizzleOrm.eq(x.code_group,e),drizzleOrm.eq(x.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 X("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};Bt();Cn();h();var je={threadContext:"crewx_thread_context",apps:"apps",appsGuidance:"apps_guidance",availableApps:"available_apps",crewxUiState:"crewx_ui_state"};function wg(t){return t.replace(new RegExp(`<${je.threadContext}\\b[^>]*>[\\s\\S]*?<\\/${je.threadContext}>`,"g"),"").replace(new RegExp(`<${je.apps}\\b[^>]*>[\\s\\S]*?<\\/${je.apps}>`,"g"),"").replace(new RegExp(`<${je.appsGuidance}\\b[^>]*>[\\s\\S]*?<\\/${je.appsGuidance}>`,"g"),"").replace(new RegExp(`<${je.availableApps}\\b[^>]*>[\\s\\S]*?<\\/${je.availableApps}>`,"g"),"").replace(new RegExp(`<${je.crewxUiState}\\b[^>]*>[\\s\\S]*?<\\/${je.crewxUiState}>`,"g"),"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
598
615
|
`).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(`
|
|
599
|
-
`).trim()}function
|
|
600
|
-
`):s&&typeof s=="object"&&s.result!==void 0&&(r=s.result||"");}catch{r=
|
|
601
|
-
`)[0]??"":"";if(e){let r=
|
|
616
|
+
`).trim()}function yg(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 Eg(t,e,n){if(!t||e&&Ye(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(`
|
|
617
|
+
`):s&&typeof s=="object"&&s.result!==void 0&&(r=s.result||"");}catch{r=wg(r);}return r}var Rg=new Set(["success","failed","stopped","running"]),Sg=new Set(["failed","stopped"]),Ig={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"},Vr=200;function cu(t){if(t.length<=Vr)return t;let e=t.charCodeAt(Vr-1),n=e>=55296&&e<=56319?Vr-1:Vr;return t.slice(0,n)}function Ag(t){let e=He(t),n=typeof t.error=="string"?t.error.split(`
|
|
618
|
+
`)[0]??"":"";if(e){let r=Ig[e];return cu(n?`${r}; ${n}`:r)}return n?cu(n):void 0}var Jr=class{dbPath;constructor(e){this.dbPath=e??ce.join(jo.homedir(),".crewx","crewx.db");}getThreadRepo(){return new qr({dbPath:this.dbPath})}getThreadHistoryRepo(){return new Gr({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),u=new Set(["queued","cancelled"]),d=n?.currentTraceId;i=i.filter(_=>(!_.status||!u.has(_.status))&&(!d||_.trace_id!==d&&_.id!==d));let c=s.findInterceptedRequests(i.map(_=>_.id));c.size>0&&(i=i.map(_=>c.has(_.id)?{..._,prompt:c.get(_.id)}:_));let l=o?.platform??"cli",p=this.rowsToMessages(i),g=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,o?.workspace_id??null);return {threadId:e,platform:l,messages:p,...g?{highlights:g}:{},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 Kr({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?ve(s):void 0,i=yg(r.metadata),u=Eg(r.result,o!==void 0&&Sg.has(o),i);if(u||o!==void 0&&Rg.has(o)){let d={agent_id:r.agent_id,task_id:r.id};if(o&&o!=="success"){d.status=o;let c=Ag(s);c&&(d.reason=c);}n.push({id:`${r.id}-assistant`,text:u,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:d});}}return n}};var xo=class extends ot{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new Jr(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?.();}};exports.ConversationPlugin=xo;exports.FileLoggerPlugin=Qr;exports.SqliteTracingPlugin=ko;
|