@crewx/sdk 0.9.0-rc.86 → 0.9.0-rc.87
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 +110 -103
- package/dist/esm/plugins/index.js +53 -52
- package/dist/index.d.ts +3 -2
- package/dist/index.js +113 -106
- package/dist/plugins/index.js +57 -56
- package/dist/provider/cli/adapter.types.d.ts +1 -0
- package/dist/provider/cli/protocol-envelope.d.ts +2 -0
- package/dist/utils/crewx-executable.d.ts +19 -1
- package/package.json +1 -1
- package/templates/agents/default.yaml +5 -5
package/dist/plugins/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
'use strict';var fs=require('fs'),
|
|
1
|
+
'use strict';var fs=require('fs'),Re=require('path'),Fo=require('os'),crypto=require('crypto'),drizzleOrm=require('drizzle-orm'),sqliteCore=require('drizzle-orm/sqlite-core');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 Re__namespace=/*#__PURE__*/_interopNamespace(Re);var Fo__default=/*#__PURE__*/_interopDefault(Fo);var lt=(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 Me=class{detach(e){}};function Gn(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 en(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var tn=class extends Me{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(e){super(),this.logsDir=Re.join(e?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=e?.version??"unknown";}attach(e){this.unsubs.push(e.on("task:start",n=>{try{fs.existsSync(this.logsDir)||fs.mkdirSync(this.logsDir,{recursive:!0});let r=Gn(n.timestamp),o=Re.join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,o);let s=`=== TASK LOG: ${n.traceId} ===
|
|
2
2
|
CrewX Version: ${this.version}
|
|
3
3
|
Mode: ${n.mode}
|
|
4
4
|
Agent: ${n.agentRef}
|
|
5
|
-
Started: ${
|
|
5
|
+
Started: ${en(n.timestamp)}
|
|
6
6
|
Message: ${n.message}
|
|
7
7
|
|
|
8
8
|
`;fs.writeFileSync(o,s,{encoding:"utf8",mode:384});}catch{}}),e.on("task:output",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=new Date().toISOString();fs.appendFileSync(r,`[${o}] STDOUT: ${n.output}
|
|
9
|
-
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=
|
|
9
|
+
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=en(new Date),s=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${o}] INFO: Task ${s} in ${n.durationMs}ms
|
|
10
10
|
[${o}] INFO: Process closed with exit code: ${n.error?1:0}
|
|
11
|
-
`;fs.appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};function
|
|
11
|
+
`;fs.appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};function $o(t){let e=Re__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 Jn(t){let e=$o(t);return crypto.createHash("sha256").update(e).digest("hex")}var p=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);}};var te=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:Re.join(Fo__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return fs.existsSync(e??this.resolveDbPath())}};var Bo=32*1024*1024;function L(t){let e=lt("better-sqlite3"),{drizzle:n}=lt("drizzle-orm/better-sqlite3"),r=new e(t);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${Bo}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),{db:n(r),runRaw:(o,s=[])=>r.prepare(o).run(...s),close:()=>r.close()}}var Kn=new Set,jo={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"};function nn(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Go(t,e){if(e>0||!nn(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,s]of Object.entries(jo))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var Wo={"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"}};function zo(t,e,n){if(!nn(t,"__drizzle_migrations")||!nn(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(fs.readFileSync(Re__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=Wo[i.tag];if(!a)continue;let l=Re__namespace.default.join(e,`${i.tag}.sql`);if(!fs.existsSync(l))continue;let c=fs.readFileSync(l,"utf-8"),u=crypto.createHash("sha256").update(c).digest("hex");if(o.has(u))continue;let g=t.all("PRAGMA table_info(tasks)"),h=new Set(g.map(m=>m.name));for(let[m,S]of Object.entries(a))h.has(m)||(t.run(`ALTER TABLE tasks ADD COLUMN ${m} ${S}`),h.add(m));}}function Vo(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(fs.readFileSync(Re__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=Re__namespace.default.join(e,`${i.tag}.sql`);if(!fs.existsSync(a))continue;let l=fs.readFileSync(a,"utf-8"),c=crypto.createHash("sha256").update(l).digest("hex");if(o.has(c))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,g=[],h;for(;(h=u.exec(l))!==null;)g.push({table:h[1],column:h[2]});if(g.length===0||!l.split(/-->\s*statement-breakpoint/).map(I=>I.trim()).filter(Boolean).every(I=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(I)))continue;g.every(({table:I,column:v})=>t.all(`PRAGMA table_info("${I}")`).some(B=>B.name===v))&&t.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function Jo(t){let{migrate:e}=lt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=lt("drizzle-orm"),r=[Re__namespace.default.join(__dirname,"../migrations"),Re__namespace.default.join(__dirname,"migrations"),Re__namespace.default.join(__dirname,"../../../../drizzle/migrations"),Re__namespace.default.join(process.cwd(),"drizzle/migrations")],o=r.find(c=>fs.existsSync(Re__namespace.default.join(c,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
12
12
|
${r.join(`
|
|
13
|
-
`)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),$o(t,i),s?.cnt&&(Fo(t,o,n),Uo(t,o,n)),e(t,{migrationsFolder:o});let l=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function pe(t,e){Vn.has(e)||(qo(t),Vn.add(e));}var Ye=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 d=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_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"),rendered_prompt:sqliteCore.text("rendered_prompt"),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"),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)},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),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_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_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)}));var ge=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>d.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 Xo="json_extract(metadata, '$.threadTitle.state')",Qo="json_extract(metadata, '$.threadTitle.priority')",f=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Ye.id,{onDelete:"set null"}),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_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(Xo)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(Qo))}));var ts=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>d.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>ts.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)}));sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>d.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)}));sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>f.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)}));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)}));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)}));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)}));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]})}));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)}));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(),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("[]"),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`),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'`),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)}));sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),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')`),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`(
|
|
13
|
+
`)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Go(t,i),s?.cnt&&(Vo(t,o,n),zo(t,o,n)),e(t,{migrationsFolder:o});let l=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function ge(t,e){Kn.has(e)||(Jo(t),Kn.add(e));}var Xe=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 d=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_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"),rendered_prompt:sqliteCore.text("rendered_prompt"),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"),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)},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),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_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_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)}));var fe=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>d.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 os="json_extract(metadata, '$.threadTitle.state')",ss="json_extract(metadata, '$.threadTitle.priority')",f=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Xe.id,{onDelete:"set null"}),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_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(os)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(ss))}));var ds=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>d.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>ds.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)}));sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>d.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)}));sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>f.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)}));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)}));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)}));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)}));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]})}));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)}));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(),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("[]"),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`),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'`),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)}));sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),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')`),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`(
|
|
14
14
|
(${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
|
|
15
15
|
OR
|
|
16
16
|
(${t.status} = 'settled' AND ${t.after_revision} IS NOT NULL AND ${t.outcome} IS NOT NULL AND ${t.settled_at} IS NOT NULL)
|
|
17
|
-
)`),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 ar=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(()=>ar.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(()=>ar.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 ln=["THREAD_STATE","THREAD_PRIORITY"],cn=["gray","blue","violet","green","amber","orange","red","pink"],_=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 dr=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],lr=["user","agent","system"],cr=["auto","manual"],ur=["decision","judgment","issue","result","pivot"];var pr=["queued","running","completed","failed"],b=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>f.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)})),v=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>f.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)})),w=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>f.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'`)}));function gr(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 kr(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new p("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new p("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function mr(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new p("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new p("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>kr(r,o))}catch(r){throw r instanceof p?new p("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Tr(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new p("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new p("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new p("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function _r(t){return {taskId:t.id,source:Tr(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Ns(t){if(!Number.isInteger(t)||t<0)throw new p("VALIDATION","Task log tail limit must be a non-negative integer")}var Mt=class extends te{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ee.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ee.dirname(n);fs.existsSync(o)||fs.mkdirSync(o,{recursive:true});}else if(!fs.existsSync(n))throw new p("NOT_FOUND","Database not found");let r=P(n);if(e)try{pe(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:d.id,log_storage:d.log_storage,last_log_seq:d.last_log_seq,log_revision:d.log_revision,logs:d.logs}).from(d).where(drizzleOrm.eq(d.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:d.id,log_storage:d.log_storage,last_log_seq:d.last_log_seq,log_revision:d.log_revision,logs:d.logs}).from(d).where(drizzleOrm.eq(d.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new p("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,i)=>kr(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new p("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let a=this.requireStateRowInTransaction(i,e),l=Tr(a);if(l==="blob"){let h=mr(e,a.logs);if(i.update(d).set({logs:JSON.stringify([...h,...r]),log_revision:drizzleOrm.sql`${d.log_revision} + 1`}).where(drizzleOrm.eq(d.id,e)).run().changes!==1)throw new p("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:a.log_revision+1,lastSeq:a.last_log_seq}}let c=a.last_log_seq+1,u=a.last_log_seq+r.length;if(i.insert(ge).values(r.map((h,m)=>({task_id:e,seq:c+m,timestamp:h.timestamp,level:h.level,message:h.message}))).run(),i.update(d).set({last_log_seq:u,log_revision:drizzleOrm.sql`${d.log_revision} + 1`}).where(drizzleOrm.eq(d.id,e)).run().changes!==1)throw new p("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:a.log_revision+1,lastSeq:u}},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?_r(r):void 0}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return Ns(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=_r(s);if(i.source==="blob"){let u=mr(e,s.logs);return {...i,entries:n===void 0?u:u.slice(Math.max(0,u.length-n))}}let a=o.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?a.all():a.limit(n).all()).map(({timestamp:u,level:g,message:h})=>({timestamp:u,level:g,message:h}));return n!==void 0&&c.reverse(),{...i,entries:c}},{behavior:"deferred"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};var gn=40,xe="2026-05-09",Hs="0.8.9-rc.13",Oe=10,be=parseInt(Hs.split("rc.")[1]);function yr(){let t=drizzleOrm.sql`
|
|
17
|
+
)`),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 lr=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(()=>lr.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(()=>lr.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 un=["THREAD_STATE","THREAD_PRIORITY"],pn=["gray","blue","violet","green","amber","orange","red","pink"],_=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 cr=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],ur=["user","agent","system"],pr=["auto","manual"],gr=["decision","judgment","issue","result","pivot"];var fr=["queued","running","completed","failed"],C=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>f.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)})),A=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>f.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)})),w=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>f.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'`)}));function hr(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 yr(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new p("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new p("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function kr(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new p("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new p("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>yr(r,o))}catch(r){throw r instanceof p?new p("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function wr(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new p("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new p("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new p("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Tr(t){return {taskId:t.id,source:wr(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Us(t){if(!Number.isInteger(t)||t<0)throw new p("VALIDATION","Task log tail limit must be a non-negative integer")}var $t=class extends te{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Re.dirname(n);fs.existsSync(o)||fs.mkdirSync(o,{recursive:true});}else if(!fs.existsSync(n))throw new p("NOT_FOUND","Database not found");let r=L(n);if(e)try{ge(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:d.id,log_storage:d.log_storage,last_log_seq:d.last_log_seq,log_revision:d.log_revision,logs:d.logs}).from(d).where(drizzleOrm.eq(d.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:d.id,log_storage:d.log_storage,last_log_seq:d.last_log_seq,log_revision:d.log_revision,logs:d.logs}).from(d).where(drizzleOrm.eq(d.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new p("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,i)=>yr(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new p("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let a=this.requireStateRowInTransaction(i,e),l=wr(a);if(l==="blob"){let h=kr(e,a.logs);if(i.update(d).set({logs:JSON.stringify([...h,...r]),log_revision:drizzleOrm.sql`${d.log_revision} + 1`}).where(drizzleOrm.eq(d.id,e)).run().changes!==1)throw new p("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:a.log_revision+1,lastSeq:a.last_log_seq}}let c=a.last_log_seq+1,u=a.last_log_seq+r.length;if(i.insert(fe).values(r.map((h,m)=>({task_id:e,seq:c+m,timestamp:h.timestamp,level:h.level,message:h.message}))).run(),i.update(d).set({last_log_seq:u,log_revision:drizzleOrm.sql`${d.log_revision} + 1`}).where(drizzleOrm.eq(d.id,e)).run().changes!==1)throw new p("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:a.log_revision+1,lastSeq:u}},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?Tr(r):void 0}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return Us(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=Tr(s);if(i.source==="blob"){let u=kr(e,s.logs);return {...i,entries:n===void 0?u:u.slice(Math.max(0,u.length-n))}}let a=o.select({seq:fe.seq,timestamp:fe.timestamp,level:fe.level,message:fe.message}).from(fe).where(drizzleOrm.eq(fe.task_id,e)).orderBy(n===void 0?drizzleOrm.asc(fe.seq):drizzleOrm.desc(fe.seq)),c=(n===void 0?a.all():a.limit(n).all()).map(({timestamp:u,level:g,message:h})=>({timestamp:u,level:g,message:h}));return n!==void 0&&c.reverse(),{...i,entries:c}},{behavior:"deferred"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};var hn=40,Oe="2026-05-09",Ws="0.8.9-rc.13",Ce=10,be=parseInt(Ws.split("rc.")[1]);function Er(){let t=drizzleOrm.sql`
|
|
18
18
|
CASE
|
|
19
19
|
WHEN ${d.model} LIKE 'claude-%' OR ${d.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
20
20
|
WHEN ${d.model} LIKE 'gpt-%' OR ${d.model} LIKE 'codex-%' THEN 'codex'
|
|
@@ -43,14 +43,14 @@ ${r.join(`
|
|
|
43
43
|
WHEN trim(${o}) = '' THEN 'unknown'
|
|
44
44
|
ELSE ${o}
|
|
45
45
|
END
|
|
46
|
-
`}var
|
|
46
|
+
`}var zs=new Set(["workflow","mcp"]),mn="usageByEpoch";function _n(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Rr(t){if(!t)return {};try{let e=JSON.parse(t);return _n(e)?{...e}:{}}catch{return {}}}function oe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ir(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Vs(t){return {inputTokens:oe(t.inputTokens??0),outputTokens:oe(t.outputTokens??0),cachedInputTokens:oe(t.cachedInputTokens??0),costUsd:oe(t.costUsd??0)}}function Js(t){if(_n(t))return {inputTokens:oe(t.inputTokens),outputTokens:oe(t.outputTokens),cachedInputTokens:oe(t.cachedInputTokens),costUsd:oe(t.costUsd)}}function Ks(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=Js(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function Ys(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}var vr=600*1e3,Ut=class extends te{dbPath;taskLogRepository;pidNullObservedSince=new Map;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new $t({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Re.dirname(n);fs.existsSync(o)||fs.mkdirSync(o,{recursive:true});}else if(!fs.existsSync(n))throw new p("NOT_FOUND","Database not found");let r=L(n);if(e)try{ge(r.db,n);}catch(o){throw r.close(),o}return r}startTask(e){let n=this.openHandle(true);try{let r={id:e.id,agent_id:e.agentId,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,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,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},o=s=>{n.db.insert(d).values(s).onConflictDoUpdate({target:d.id,set:{pid:drizzleOrm.sql`COALESCE(excluded.pid, ${d.pid})`},setWhere:drizzleOrm.eq(d.status,"running")}).run();};try{o(r);}catch(s){let i=s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s);if(!/log_storage/i.test(i)||!/no such column|no column named/i.test(i))throw s;n.runRaw(`INSERT INTO tasks (
|
|
47
47
|
id, agent_id, prompt, mode, status, started_at, pid,
|
|
48
48
|
parent_task_id, caller_agent_id, trace_id, command, metadata,
|
|
49
49
|
workspace_id, project_id, platform, crewx_version, thread_id,
|
|
50
50
|
model, rendered_prompt, coding_agent_command
|
|
51
51
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
52
52
|
ON CONFLICT(id) DO UPDATE SET pid = COALESCE(excluded.pid, tasks.pid)
|
|
53
|
-
WHERE tasks.status = 'running'`,[r.id,r.agent_id,r.prompt,r.mode,r.status,r.started_at,r.pid,r.parent_task_id,r.caller_agent_id,r.trace_id,r.command,r.metadata,r.workspace_id,r.project_id,r.platform,r.crewx_version,r.thread_id,r.model,r.rendered_prompt,r.coding_agent_command]);}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to start task",r)}finally{n.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(d).where(drizzleOrm.eq(d.project_id,e)).orderBy(drizzleOrm.desc(d.started_at)).all()}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true);try{n.db.transaction(r=>{let o=r.select({status:d.status,run_epoch:d.run_epoch,started_at:d.started_at,metadata:d.metadata}).from(d).where(drizzleOrm.eq(d.id,e.id)).limit(1).get();if(!o)return;let s=
|
|
53
|
+
WHERE tasks.status = 'running'`,[r.id,r.agent_id,r.prompt,r.mode,r.status,r.started_at,r.pid,r.parent_task_id,r.caller_agent_id,r.trace_id,r.command,r.metadata,r.workspace_id,r.project_id,r.platform,r.crewx_version,r.thread_id,r.model,r.rendered_prompt,r.coding_agent_command]);}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to start task",r)}finally{n.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(d).where(drizzleOrm.eq(d.project_id,e)).orderBy(drizzleOrm.desc(d.started_at)).all()}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true);try{n.db.transaction(r=>{let o=r.select({status:d.status,run_epoch:d.run_epoch,started_at:d.started_at,metadata:d.metadata}).from(d).where(drizzleOrm.eq(d.id,e.id)).limit(1).get();if(!o)return;let s=Ir(o.run_epoch),i=Ir(e.runEpoch),a=o.status==="running"&&s===i,l=s>0||i>0||e.runEpoch!==void 0&&e.runEpoch!==null||s!==i,c={},u;if(l){u=Rr(o.metadata);let g=_n(u[mn])?{...u[mn]}:{};g[String(i)]=Vs(e),u[mn]=g;let h=Ks(g);c.metadata=JSON.stringify(u),c.input_tokens=h.inputTokens,c.output_tokens=h.outputTokens,c.cached_input_tokens=h.cachedInputTokens,c.cost_usd=h.costUsd;}else a&&(c.input_tokens=oe(e.inputTokens??0),c.output_tokens=oe(e.outputTokens??0),c.cached_input_tokens=oe(e.cachedInputTokens??0),c.cost_usd=oe(e.costUsd??0));a&&e.model!==void 0&&e.model!==null&&(c.model=e.model),e.partialResultRecovered===!0&&a&&(u??=Rr(o.metadata),u.partialResultRecovered=!0,c.metadata=JSON.stringify(u)),a&&(c.status=e.status,c.result=e.result??null,c.error=e.error??null,c.completed_at=e.completedAt,c.duration_ms=s>0?Ys(o.started_at,e.completedAt,e.durationMs):e.durationMs??null,c.exit_code=e.exitCode??null),Object.keys(c).length>0&&r.update(d).set(c).where(drizzleOrm.eq(d.id,e.id)).run();},{behavior:"immediate"});}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to finish task",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().from(d).where(drizzleOrm.eq(d.status,"running")).orderBy(drizzleOrm.desc(d.started_at)).all()}catch(n){throw new p("DB_ERROR","Failed to get running tasks",n)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(d).orderBy(drizzleOrm.desc(d.started_at)).limit(100).all()}catch(n){throw new p("DB_ERROR","Failed to get all tasks",n)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(d).where(drizzleOrm.eq(d.id,e)).limit(1).get()??void 0}catch(r){throw new p("DB_ERROR","Failed to get task",r)}finally{n.close();}}killTask(e){if(!this.dbExists())return {killed:false};let n=this.openHandle(true);try{let r=n.db.select({id:d.id,status:d.status,pid:d.pid}).from(d).where(drizzleOrm.eq(d.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return n.db.update(d).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(d.id,e),drizzleOrm.eq(d.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to kill task",r)}finally{n.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let n=e.db.select({id:d.id,pid:d.pid,platform:d.platform,run_epoch:d.run_epoch}).from(d).where(drizzleOrm.eq(d.status,"running")).all(),r=Date.now(),o=new Set,s=0;for(let i of n){if(i.pid){let c=!1;try{process.kill(i.pid,0),c=!0;}catch{}c||(e.db.update(d).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(d.id,i.id),drizzleOrm.eq(d.status,"running"))).run(),s++);continue}if(zs.has(i.platform??"cli"))continue;let a=`${i.id}:${i.run_epoch??0}`;o.add(a);let l=this.pidNullObservedSince.get(a);if(l===void 0){this.pidNullObservedSince.set(a,r);continue}r-l>=vr&&(e.db.update(d).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(d.id,i.id),drizzleOrm.eq(d.status,"running"))).run(),s++,this.pidNullObservedSince.delete(a));}for(let i of Array.from(this.pidNullObservedSince.keys()))o.has(i)||this.pidNullObservedSince.delete(i);return s}finally{e.close();}}reapRunningWorkflowTasks(e=vr){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString();return n.db.update(d).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(d.status,"running"),drizzleOrm.eq(d.platform,"workflow"),drizzleOrm.isNull(d.pid),drizzleOrm.lt(d.started_at,r),drizzleOrm.or(drizzleOrm.isNull(d.metadata),drizzleOrm.and(drizzleOrm.notLike(d.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(d.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let o of r){if(!fs.existsSync(o))continue;let s=L(o);try{let i=n?drizzleOrm.eq(d.workspace_id,n):void 0,a=i?drizzleOrm.and(drizzleOrm.eq(d.id,e),i):drizzleOrm.eq(d.id,e),l=s.db.select().from(d).where(a).limit(1).get()??void 0;if(!l){let c=i?drizzleOrm.and(drizzleOrm.eq(d.thread_id,e),i):drizzleOrm.eq(d.thread_id,e);l=s.db.select().from(d).where(c).orderBy(drizzleOrm.desc(d.started_at)).limit(1).get()??void 0;}if(l)return l}catch(i){throw new p("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!fs.existsSync(i))continue;let a=L(i);try{let l=n?drizzleOrm.and(drizzleOrm.eq(d.parent_task_id,e),drizzleOrm.eq(d.workspace_id,n)):drizzleOrm.eq(d.parent_task_id,e),c=a.db.select().from(d).where(l).orderBy(drizzleOrm.asc(d.started_at)).all();for(let u of c)o.has(u.id)||(o.add(u.id),s.push(u));}catch(l){throw new p("DB_ERROR","Failed to find child tasks",l)}finally{a.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?drizzleOrm.sql`
|
|
54
54
|
SELECT
|
|
55
55
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
56
56
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -71,7 +71,7 @@ ${r.join(`
|
|
|
71
71
|
FROM tasks
|
|
72
72
|
GROUP BY workspace_id
|
|
73
73
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
74
|
-
`)}catch(r){throw new p("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,i=0,a=0;for(let l of r){if(!fs.existsSync(l))continue;let c=
|
|
74
|
+
`)}catch(r){throw new p("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,i=0,a=0;for(let l of r){if(!fs.existsSync(l))continue;let c=L(l);try{let u=drizzleOrm.eq(d.thread_id,e),g=n?drizzleOrm.and(u,drizzleOrm.eq(d.workspace_id,n)):u,h=c.db.select({id:d.id,input_tokens:d.input_tokens,output_tokens:d.output_tokens,cost_usd:d.cost_usd}).from(d).where(g).all();for(let m of h)o.has(m.id)||(o.add(m.id),s+=m.input_tokens??0,i+=m.output_tokens??0,a+=m.cost_usd??0);}catch(u){throw new p("DB_ERROR","Failed to get thread token usage",u)}finally{c.close();}}return {inputTokens:s,outputTokens:i,costUsd:a}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[],a=r?.projection==="activity-log";for(let l of o){if(!fs.existsSync(l))continue;let c=L(l);try{let u=drizzleOrm.eq(d.thread_id,e),g=n?drizzleOrm.and(u,drizzleOrm.eq(d.workspace_id,n)):u,h=a?c.db.select({id:d.id,thread_id:d.thread_id,agent_id:d.agent_id,parent_task_id:d.parent_task_id,started_at:d.started_at,completed_at:d.completed_at}).from(d).where(g).orderBy(drizzleOrm.asc(d.started_at)).all():c.db.select().from(d).where(g).orderBy(drizzleOrm.asc(d.started_at)).all();for(let m of h)s.has(m.id)||(s.add(m.id),i.push(m));}catch(u){throw new p("DB_ERROR","Failed to find tasks by thread",u)}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.existsSync(n))continue;let r=L(n);try{e.push(...r.db.select({id:d.id,agent_id:d.agent_id,thread_id:d.thread_id,workspace_id:d.workspace_id,platform:d.platform,status:d.status,error:d.error,completed_at:d.completed_at,duration_ms:d.duration_ms,started_at:d.started_at,metadata:d.metadata}).from(d).where(drizzleOrm.and(drizzleOrm.eq(d.platform,"workflow"),drizzleOrm.or(drizzleOrm.like(d.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(d.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(drizzleOrm.desc(d.started_at)).all());}catch(o){throw new p("DB_ERROR","Failed to find workflow parent tasks",o)}finally{r.close();}}return e}batchFetchWorkflowCards(e,n){let r=new Map;if(e.length===0)return r;let o=new Set(e),s=new Map,i=n?drizzleOrm.eq(d.workspace_id,n):void 0,a=(l,c)=>{if(!l)return;let u=s.get(l);if(u&&c.started_at<=u)return;let g=this.parseWorkflowCardMetadata(c.metadata);g.kind!=="workflow_card"&&g.kind!=="workflow_ui_instance"||(s.set(l,c.started_at),r.set(l,{taskId:c.id,workflowRunId:g.workflowRunId,raw:c.result??void 0}));};for(let l of this.resolveDbPaths()){if(!fs.existsSync(l))continue;let c=L(l);try{let u=drizzleOrm.and(drizzleOrm.inArray(d.thread_id,e),drizzleOrm.or(drizzleOrm.like(d.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(d.metadata,'%"kind":"workflow_ui_instance"%'))),g=c.db.select({id:d.id,thread_id:d.thread_id,metadata:d.metadata,result:d.result,started_at:d.started_at}).from(d).where(i?drizzleOrm.and(u,i):u).all();for(let S of g)a(S.thread_id,S);let h=drizzleOrm.and(drizzleOrm.isNull(d.thread_id),drizzleOrm.or(drizzleOrm.like(d.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(d.metadata,'%"kind":"workflow_ui_instance"%'))),m=c.db.select({id:d.id,command:d.command,metadata:d.metadata,result:d.result,started_at:d.started_at}).from(d).where(i?drizzleOrm.and(h,i):h).all();for(let S of m){let I=this.extractThreadIdFromCommand(S.command);!I||!o.has(I)||a(I,S);}}catch(u){throw new p("DB_ERROR","Failed to batch fetch workflow cards",u)}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(d.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&r.push(drizzleOrm.inArray(d.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&r.push(drizzleOrm.inArray(d.status,s));let i=e.q??e.search;i&&r.push(drizzleOrm.like(d.prompt,`%${i}%`)),e.from&&r.push(drizzleOrm.gte(d.started_at,e.from)),e.to&&r.push(drizzleOrm.lt(d.started_at,e.to));let a=r.length>0?drizzleOrm.and(...r):void 0,l=n.db.select({count:drizzleOrm.sql`count(*)`}).from(d).where(a).get(),c=(e.sortDir??"DESC")==="ASC"?drizzleOrm.asc(d.started_at):drizzleOrm.desc(d.started_at);return {rows:n.db.select().from(d).where(a).orderBy(c).limit(e.limit).offset(e.offset).all(),total:l?.count??0}}catch(r){throw new p("DB_ERROR","Failed to find all tasks",r)}finally{n.close();}}getAgentUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.all(r?drizzleOrm.sql`
|
|
75
75
|
SELECT
|
|
76
76
|
t.agent_id,
|
|
77
77
|
t.workspace_id,
|
|
@@ -79,11 +79,11 @@ ${r.join(`
|
|
|
79
79
|
COALESCE(SUM(
|
|
80
80
|
COALESCE(t.input_tokens, 0)
|
|
81
81
|
+ CASE
|
|
82
|
-
WHEN t.started_at >= ${
|
|
82
|
+
WHEN t.started_at >= ${Oe}
|
|
83
83
|
AND (
|
|
84
84
|
t.crewx_version IS NULL
|
|
85
85
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
86
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
86
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ce}) AS INTEGER) < ${be})
|
|
87
87
|
)
|
|
88
88
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
89
89
|
ELSE 0
|
|
@@ -102,11 +102,11 @@ ${r.join(`
|
|
|
102
102
|
COALESCE(SUM(
|
|
103
103
|
COALESCE(t.input_tokens, 0)
|
|
104
104
|
+ CASE
|
|
105
|
-
WHEN t.started_at >= ${
|
|
105
|
+
WHEN t.started_at >= ${Oe}
|
|
106
106
|
AND (
|
|
107
107
|
t.crewx_version IS NULL
|
|
108
108
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
109
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
109
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ce}) AS INTEGER) < ${be})
|
|
110
110
|
)
|
|
111
111
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
112
112
|
ELSE 0
|
|
@@ -122,11 +122,11 @@ ${r.join(`
|
|
|
122
122
|
COALESCE(SUM(
|
|
123
123
|
COALESCE(t.input_tokens, 0)
|
|
124
124
|
+ CASE
|
|
125
|
-
WHEN t.started_at >= ${
|
|
125
|
+
WHEN t.started_at >= ${Oe}
|
|
126
126
|
AND (
|
|
127
127
|
t.crewx_version IS NULL
|
|
128
128
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
129
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
129
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ce}) AS INTEGER) < ${be})
|
|
130
130
|
)
|
|
131
131
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
132
132
|
ELSE 0
|
|
@@ -144,11 +144,11 @@ ${r.join(`
|
|
|
144
144
|
COALESCE(SUM(
|
|
145
145
|
COALESCE(t.input_tokens, 0)
|
|
146
146
|
+ CASE
|
|
147
|
-
WHEN t.started_at >= ${
|
|
147
|
+
WHEN t.started_at >= ${Oe}
|
|
148
148
|
AND (
|
|
149
149
|
t.crewx_version IS NULL
|
|
150
150
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
151
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
151
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ce}) AS INTEGER) < ${be})
|
|
152
152
|
)
|
|
153
153
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
154
154
|
ELSE 0
|
|
@@ -163,11 +163,11 @@ ${r.join(`
|
|
|
163
163
|
COALESCE(SUM(
|
|
164
164
|
COALESCE(t.input_tokens, 0)
|
|
165
165
|
+ CASE
|
|
166
|
-
WHEN t.started_at >= ${
|
|
166
|
+
WHEN t.started_at >= ${Oe}
|
|
167
167
|
AND (
|
|
168
168
|
t.crewx_version IS NULL
|
|
169
169
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
170
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
170
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ce}) AS INTEGER) < ${be})
|
|
171
171
|
)
|
|
172
172
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
173
173
|
ELSE 0
|
|
@@ -190,11 +190,11 @@ ${r.join(`
|
|
|
190
190
|
COALESCE(SUM(
|
|
191
191
|
COALESCE(t.input_tokens, 0)
|
|
192
192
|
+ CASE
|
|
193
|
-
WHEN t.started_at >= ${
|
|
193
|
+
WHEN t.started_at >= ${Oe}
|
|
194
194
|
AND (
|
|
195
195
|
t.crewx_version IS NULL
|
|
196
196
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
197
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
197
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ce}) AS INTEGER) < ${be})
|
|
198
198
|
)
|
|
199
199
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
200
200
|
ELSE 0
|
|
@@ -209,14 +209,14 @@ ${r.join(`
|
|
|
209
209
|
AND t.started_at < ${n}
|
|
210
210
|
GROUP BY date(t.started_at), t.agent_id
|
|
211
211
|
ORDER BY date(t.started_at) ASC
|
|
212
|
-
`).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new p("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(d).where(drizzleOrm.and(drizzleOrm.eq(d.id,e),drizzleOrm.eq(d.workspace_id,n))).limit(1).get()??void 0}catch(o){throw new p("DB_ERROR","Failed to find task for stop",o)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:d.id,thread_id:d.thread_id,status:d.status,result:d.result,error:d.error,started_at:d.started_at,completed_at:d.completed_at,metadata:d.metadata}).from(d).where(drizzleOrm.and(drizzleOrm.eq(d.agent_id,e.agentId),drizzleOrm.eq(d.workspace_id,e.workspaceId),drizzleOrm.sql`${d.metadata} IS NOT NULL AND json_valid(${d.metadata}) AND json_extract(${d.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(drizzleOrm.desc(d.started_at)).limit(1).get()??null}catch(r){throw new p("DB_ERROR","Failed to find latest task by metadata",r)}finally{n.close();}}markTaskFailed(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString(),i=r?drizzleOrm.and(drizzleOrm.eq(d.id,e),drizzleOrm.eq(d.status,"running"),drizzleOrm.eq(d.workspace_id,r)):drizzleOrm.and(drizzleOrm.eq(d.id,e),drizzleOrm.eq(d.status,"running"));o.db.update(d).set({status:"failed",error:n,completed_at:s}).where(i).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to mark task failed",s)}finally{o.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!fs.existsSync(i))continue;let a=
|
|
212
|
+
`).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new p("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(d).where(drizzleOrm.and(drizzleOrm.eq(d.id,e),drizzleOrm.eq(d.workspace_id,n))).limit(1).get()??void 0}catch(o){throw new p("DB_ERROR","Failed to find task for stop",o)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:d.id,thread_id:d.thread_id,status:d.status,result:d.result,error:d.error,started_at:d.started_at,completed_at:d.completed_at,metadata:d.metadata}).from(d).where(drizzleOrm.and(drizzleOrm.eq(d.agent_id,e.agentId),drizzleOrm.eq(d.workspace_id,e.workspaceId),drizzleOrm.sql`${d.metadata} IS NOT NULL AND json_valid(${d.metadata}) AND json_extract(${d.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(drizzleOrm.desc(d.started_at)).limit(1).get()??null}catch(r){throw new p("DB_ERROR","Failed to find latest task by metadata",r)}finally{n.close();}}markTaskFailed(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString(),i=r?drizzleOrm.and(drizzleOrm.eq(d.id,e),drizzleOrm.eq(d.status,"running"),drizzleOrm.eq(d.workspace_id,r)):drizzleOrm.and(drizzleOrm.eq(d.id,e),drizzleOrm.eq(d.status,"running"));o.db.update(d).set({status:"failed",error:n,completed_at:s}).where(i).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to mark task failed",s)}finally{o.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!fs.existsSync(i))continue;let a=L(i);try{let l=n?drizzleOrm.and(drizzleOrm.like(d.prompt,`%${e}%`),drizzleOrm.eq(d.workspace_id,n)):drizzleOrm.like(d.prompt,`%${e}%`),c=a.db.select().from(d).where(l).orderBy(drizzleOrm.asc(d.started_at)).all();for(let u of c)o.has(u.id)||(o.add(u.id),s.push(u));}catch(l){throw new p("DB_ERROR","Failed to find tasks by prompt hint",l)}finally{a.close();}}return s}getProviderUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Er(),i=drizzleOrm.sql`
|
|
213
213
|
COALESCE(${d.input_tokens}, 0)
|
|
214
214
|
+ CASE
|
|
215
|
-
WHEN ${d.started_at} >= ${
|
|
215
|
+
WHEN ${d.started_at} >= ${Oe}
|
|
216
216
|
AND (
|
|
217
217
|
${d.crewx_version} IS NULL
|
|
218
218
|
OR (${d.crewx_version} LIKE '0.8.%' AND ${d.crewx_version} NOT LIKE '0.8.9%')
|
|
219
|
-
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${
|
|
219
|
+
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${Ce}) AS INTEGER) < ${be})
|
|
220
220
|
)
|
|
221
221
|
THEN COALESCE(${d.cached_input_tokens}, 0)
|
|
222
222
|
ELSE 0
|
|
@@ -235,14 +235,14 @@ ${r.join(`
|
|
|
235
235
|
${a}
|
|
236
236
|
GROUP BY ${s}
|
|
237
237
|
ORDER BY (COALESCE(SUM(${i}), 0) + COALESCE(SUM(${d.output_tokens}), 0)) DESC
|
|
238
|
-
`).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new p("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=
|
|
238
|
+
`).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new p("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Er(),i=drizzleOrm.sql`
|
|
239
239
|
COALESCE(${d.input_tokens}, 0)
|
|
240
240
|
+ CASE
|
|
241
|
-
WHEN ${d.started_at} >= ${
|
|
241
|
+
WHEN ${d.started_at} >= ${Oe}
|
|
242
242
|
AND (
|
|
243
243
|
${d.crewx_version} IS NULL
|
|
244
244
|
OR (${d.crewx_version} LIKE '0.8.%' AND ${d.crewx_version} NOT LIKE '0.8.9%')
|
|
245
|
-
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${
|
|
245
|
+
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${Ce}) AS INTEGER) < ${be})
|
|
246
246
|
)
|
|
247
247
|
THEN COALESCE(${d.cached_input_tokens}, 0)
|
|
248
248
|
ELSE 0
|
|
@@ -261,7 +261,7 @@ ${r.join(`
|
|
|
261
261
|
FROM ${d}
|
|
262
262
|
${a}
|
|
263
263
|
GROUP BY ${d.model}, ${s}
|
|
264
|
-
`),c=new Map;for(let u of l){let g=
|
|
264
|
+
`),c=new Map;for(let u of l){let g=hr(u.model??""),h=JSON.stringify([u.provider,g]),m=c.get(h);m?(m.totalTasks+=u.total_tasks,m.inputTokens+=u.input_tokens,m.outputTokens+=u.output_tokens,m.cachedInputTokens+=u.cached_input_tokens,m.costUsd+=u.cost_usd,m.totalTokens+=u.input_tokens+u.output_tokens,m.activeDurationMs+=u.active_duration_ms??0,u.last_active_at&&(!m.lastActiveAt||u.last_active_at>m.lastActiveAt)&&(m.lastActiveAt=u.last_active_at)):c.set(h,{model:g,provider:u.provider,totalTasks:u.total_tasks,inputTokens:u.input_tokens,outputTokens:u.output_tokens,cachedInputTokens:u.cached_input_tokens,costUsd:u.cost_usd,totalTokens:u.input_tokens+u.output_tokens,activeDurationMs:u.active_duration_ms??0,lastActiveAt:u.last_active_at??null});}return Array.from(c.values()).sort((u,g)=>g.costUsd-u.costUsd)}catch(s){throw new p("DB_ERROR","Failed to get model usage",s)}finally{o.close();}}getTasksForReport(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=r?drizzleOrm.sql`WHERE ${d.started_at} >= ${e} AND ${d.started_at} < ${n} AND ${d.workspace_id} = ${r}`:drizzleOrm.sql`WHERE ${d.started_at} >= ${e} AND ${d.started_at} < ${n}`;return o.db.all(drizzleOrm.sql`
|
|
265
265
|
SELECT
|
|
266
266
|
${d.thread_id} AS thread_id,
|
|
267
267
|
${d.agent_id} AS agent_id,
|
|
@@ -275,11 +275,11 @@ ${r.join(`
|
|
|
275
275
|
`).map(a=>({threadId:a.thread_id,agentId:a.agent_id,startedAt:a.started_at,status:a.status,error:a.error,exitCode:a.exit_code}))}catch(s){throw new p("DB_ERROR","Failed to get tasks for report",s)}finally{o.close();}}getDelegationMatrix(e,n,r){if(!this.dbExists())return {edges:[],truncated:false};let o=this.openHandle(false);try{let s=drizzleOrm.sql`
|
|
276
276
|
COALESCE(${d.input_tokens}, 0)
|
|
277
277
|
+ CASE
|
|
278
|
-
WHEN ${d.started_at} >= ${
|
|
278
|
+
WHEN ${d.started_at} >= ${Oe}
|
|
279
279
|
AND (
|
|
280
280
|
${d.crewx_version} IS NULL
|
|
281
281
|
OR (${d.crewx_version} LIKE '0.8.%' AND ${d.crewx_version} NOT LIKE '0.8.9%')
|
|
282
|
-
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${
|
|
282
|
+
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${Ce}) AS INTEGER) < ${be})
|
|
283
283
|
)
|
|
284
284
|
THEN COALESCE(${d.cached_input_tokens}, 0)
|
|
285
285
|
ELSE 0
|
|
@@ -295,30 +295,31 @@ ${r.join(`
|
|
|
295
295
|
${i}
|
|
296
296
|
GROUP BY ${d.caller_agent_id}, ${d.agent_id}
|
|
297
297
|
ORDER BY task_count DESC, ${d.caller_agent_id} ASC, ${d.agent_id} ASC
|
|
298
|
-
LIMIT ${
|
|
299
|
-
`),l=a.length>
|
|
298
|
+
LIMIT ${hn+1}
|
|
299
|
+
`),l=a.length>hn;return {edges:a.slice(0,hn).map(u=>({callerAgentId:u.caller_agent_id??null,agentId:u.agent_id,taskCount:u.task_count,totalTokens:u.input_tokens+u.output_tokens,outputTokens:u.output_tokens})),truncated:l}}catch(s){throw new p("DB_ERROR","Failed to get delegation matrix",s)}finally{o.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(drizzleOrm.eq(d.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(drizzleOrm.inArray(d.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(drizzleOrm.inArray(d.status,e.statuses)),e.from&&r.push(drizzleOrm.gte(d.started_at,e.from)),e.to&&r.push(drizzleOrm.lt(d.started_at,e.to));let o=r.length>0?drizzleOrm.and(...r):void 0,s=(e.order??"DESC")==="ASC"?drizzleOrm.asc(d.started_at):drizzleOrm.desc(d.started_at),i={id:d.id,agent_id:d.agent_id,status:d.status,prompt:d.prompt,started_at:d.started_at,completed_at:d.completed_at,thread_id:d.thread_id};return e.limit?n.db.select(i).from(d).where(o).orderBy(s).limit(e.limit).all():n.db.select(i).from(d).where(o).orderBy(s).all()}catch(r){throw new p("DB_ERROR","Failed to find task evidence",r)}finally{n.close();}}findThreadChains(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=e.maxThreads??8,o=e.maxTurnsPerThread??4,s=[drizzleOrm.isNotNull(d.thread_id),drizzleOrm.isNull(d.parent_task_id),drizzleOrm.isNull(d.caller_agent_id),drizzleOrm.or(drizzleOrm.isNull(d.platform),drizzleOrm.ne(d.platform,"workflow")),drizzleOrm.or(drizzleOrm.isNull(d.metadata),drizzleOrm.and(drizzleOrm.notLike(d.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(d.metadata,'%"kind":"workflow_ui_instance"%'))),drizzleOrm.or(drizzleOrm.isNull(d.metadata),drizzleOrm.notLike(d.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(drizzleOrm.eq(d.workspace_id,e.workspaceId)),e.from&&s.push(drizzleOrm.gte(d.started_at,e.from)),e.to&&s.push(drizzleOrm.lt(d.started_at,e.to));let i=n.db.select({id:d.id,agent_id:d.agent_id,status:d.status,prompt:d.prompt,started_at:d.started_at,completed_at:d.completed_at,thread_id:d.thread_id}).from(d).where(drizzleOrm.and(...s)).orderBy(drizzleOrm.asc(d.started_at),drizzleOrm.asc(d.id)).all(),a=new Map;for(let c of i){if(!c.thread_id)continue;let u={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},g=a.get(c.thread_id);g?g.push(u):a.set(c.thread_id,[u]);}let l=[];for(let[c,u]of a){let g=u.filter(h=>h.agentId===e.targetAgentId).length;g<2||l.push({threadId:c,targetAgentTurnCount:g,turns:u});}return l.sort((c,u)=>{let g=c.turns[c.turns.length-1].startedAt,h=u.turns[u.turns.length-1].startedAt;return g<h?1:g>h?-1:0}),l.slice(0,r).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-o)}))}catch(r){throw new p("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}};var W=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs;}providerStr;code;kind;retryAfterMs;stdout};var Ne=class extends W{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};function Te(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function ye(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 Ar="[[crewx:delegation-result ",Xs="[[crewx:delegation-result";var Qs=new Set(["schema","taskId","agentId","isError"]);function Zs(t){let e=ei(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>ni(s.value)),r=ti(e);return {result:n.length===1&&n[0].index===r?ri(n[0].line.value):null,resultPreview:ii(e,n),hasReservedLine:n.length>0}}function De(t,e){let n=Zs(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function ei(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
300
300
|
`&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
|
|
301
301
|
`?`\r
|
|
302
|
-
`:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function Ks(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Js(t){return t.trimStart().startsWith(Gs)}function Ys(t){let e=t.trim();if(!e.startsWith(Ir)||!e.endsWith("]]"))return null;let n=e.slice(Ir.length,-2);if(!n)return null;try{return Xs(JSON.parse(n))}catch{return null}}function Xs(t){return Qs(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Qs(t){if(!ei(t)||Object.keys(t).some(r=>!Ws.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?Ar(t.taskId)&&Ar(t.agentId):t.isError===true}function Zs(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function Ar(t){return typeof t=="string"&&t.trim().length>0}function ei(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ye(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 mn={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",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{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-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":{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-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship",recommended:true},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindowTokens:4e5,tier:"speed"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",contextWindowTokens:4e5,tier:"flagship"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",contextWindowTokens:128e3,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-5.6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["minimal","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"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"}],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.5-flash",name:"Gemini 3.5 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.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship",recommended:true},{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.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(mn).map(([t,e])=>[t,e.models]));var ti=[{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]"}],ni={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};function _n(t){return ni[t]??t}var ri=new Map(ti.map(({baseModelId:t,catalogModelId:e})=>[t,e]));function oi(t){return ri.get(t)??t}var si=[{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"}],ii=new Map(si.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));function kn(t){if(!t)return {};let e=ii.get(t);return e?{...e}:{model:t}}function Tn(t,e){return t==="antigravity"||t==="cli/antigravity"?kn(e):e===void 0?{}:{model:oi(e)}}var ai={};function di(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function qe(t){return Ut(t).models}function Ut(t){return ai[t]??mn[t]??di()}function ft(t,e){let n=Ut(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Tn(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function vr(t){return Ut(t).modelOverrides}function Sr(){return qe("claude")}function xr(){return qe("codex")}function Or(){return qe("copilot")}function br(){return qe("antigravity")}var li={auto:"default"};function Cr(t){return li[t]??t}var ci=new Set(["minimal","low","medium","high","xhigh","max"]);function Be(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return ci.has(n)?{model:e[1],effort:e[2]}:{model:t}}return {model:t}}function Nr(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 ["--sandbox","workspace-write"];default:return []}}function Dr(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 Lr(t){return t?["-c",`model_reasoning_effort=${t}`]:[]}function Pr(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Cr(t);return e.has(n)?["--permission-mode",n]:[]}function Mr(t){return t?new Set(["low","medium","high","xhigh","max"]).has(t)?["--effort",t]:[]:[]}var ui=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);function $r(t){return t==="default"?[]:t&&ui.has(t)?["--permission-mode",t]:[]}function Hr(t){return t===true?["--always-approve"]:[]}function Ur(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 Fr(t){return t?new Set(["low","medium","high","xhigh"]).has(t)?["--effort",t]:[]:[]}function qr(t){if(!t)return [];switch(_n(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Br(t){return t?new Set(["low","medium","high"]).has(t)?["--effort",t]:[]:[]}function pi(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),o="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,s="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:i}}function gi(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,a="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,l=i!==void 0?i:a??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:l}}function fi(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function jr(t){let e=new Map,n;for(let s of t.split(`
|
|
303
|
-
`))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let a=i.message,l=a?.id,c=a?.usage;if(typeof l!="string"||!c)continue;let u=Number(c.input_tokens??0),g=Number(c.cache_read_input_tokens??0);e.set(l,{inputTokens:u+g,cachedInputTokens:g});let h=a?.model;typeof h=="string"&&h&&(n=h);}catch{}if(e.size===0)return;let r=0,o=0;for(let s of e.values())r+=s.inputTokens,o+=s.cachedInputTokens;return {inputTokens:r,cachedInputTokens:o,model:n}}function
|
|
304
|
-
`))if(r.trim())try{let o=JSON.parse(r),s=
|
|
305
|
-
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}
|
|
306
|
-
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,i=s?{inputTokens:Number(s.input_tokens??0)+Number(s.cache_read_input_tokens??0),outputTokens:Number(s.output_tokens??0),cachedInputTokens:Number(s.cache_read_input_tokens??0),costUsd:Number(o.total_cost_usd??0)}:null,a=o.modelUsage,l=a?Object.keys(a)[0]??null:null;return {usage:i,model:l}}}catch{}let n=
|
|
302
|
+
`:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function ti(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function ni(t){return t.trimStart().startsWith(Xs)}function ri(t){let e=t.trim();if(!e.startsWith(Ar)||!e.endsWith("]]"))return null;let n=e.slice(Ar.length,-2);if(!n)return null;try{return oi(JSON.parse(n))}catch{return null}}function oi(t){return si(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function si(t){if(!ai(t)||Object.keys(t).some(r=>!Qs.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?Sr(t.taskId)&&Sr(t.agentId):t.isError===true}function ii(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function Sr(t){return typeof t=="string"&&t.trim().length>0}function ai(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function we(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return JSON.stringify(t??{});let e=t;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var kn={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",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{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-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":{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-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship",recommended:true},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindowTokens:4e5,tier:"speed"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",contextWindowTokens:4e5,tier:"flagship"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",contextWindowTokens:128e3,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-5.6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["minimal","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"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"}],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.5-flash",name:"Gemini 3.5 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.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship",recommended:true},{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.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(kn).map(([t,e])=>[t,e.models]));var di=[{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]"}],li={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};function Tn(t){return li[t]??t}var ci=new Map(di.map(({baseModelId:t,catalogModelId:e})=>[t,e]));function ui(t){return ci.get(t)??t}var pi=[{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"}],gi=new Map(pi.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));function yn(t){if(!t)return {};let e=gi.get(t);return e?{...e}:{model:t}}function wn(t,e){return t==="antigravity"||t==="cli/antigravity"?yn(e):e===void 0?{}:{model:ui(e)}}var fi={};function hi(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function Be(t){return Ft(t).models}function Ft(t){return fi[t]??kn[t]??hi()}function ht(t,e){let n=Ft(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=wn(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function xr(t){return Ft(t).modelOverrides}function Or(){return Be("claude")}function Cr(){return Be("codex")}function br(){return Be("copilot")}function Nr(){return Be("antigravity")}var mi={auto:"default"};function Dr(t){return mi[t]??t}var _i=new Set(["minimal","low","medium","high","xhigh","max"]);function je(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return _i.has(n)?{model:e[1],effort:e[2]}:{model:t}}return {model:t}}function Pr(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 ["--sandbox","workspace-write"];default:return []}}function Lr(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 Mr(t){return t?["-c",`model_reasoning_effort=${t}`]:[]}function $r(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Dr(t);return e.has(n)?["--permission-mode",n]:[]}function Hr(t){return t?new Set(["low","medium","high","xhigh","max"]).has(t)?["--effort",t]:[]:[]}var ki=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);function Ur(t){return t==="default"?[]:t&&ki.has(t)?["--permission-mode",t]:[]}function Fr(t){return t===true?["--always-approve"]:[]}function qr(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 Br(t){return t?new Set(["low","medium","high","xhigh"]).has(t)?["--effort",t]:[]:[]}function jr(t){if(!t)return [];switch(Tn(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Gr(t){return t?new Set(["low","medium","high"]).has(t)?["--effort",t]:[]:[]}function Ti(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),o="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,s="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:i}}function yi(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,a="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,l=i!==void 0?i:a??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:l}}function wi(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function Wr(t){let e=new Map,n;for(let s of t.split(`
|
|
303
|
+
`))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let a=i.message,l=a?.id,c=a?.usage;if(typeof l!="string"||!c)continue;let u=Number(c.input_tokens??0),g=Number(c.cache_read_input_tokens??0);e.set(l,{inputTokens:u+g,cachedInputTokens:g});let h=a?.model;typeof h=="string"&&h&&(n=h);}catch{}if(e.size===0)return;let r=0,o=0;for(let s of e.values())r+=s.inputTokens,o+=s.cachedInputTokens;return {inputTokens:r,cachedInputTokens:o,model:n}}function Ze(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
|
|
304
|
+
`))if(r.trim())try{let o=JSON.parse(r),s=wi(o);if(s){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=s.inputTokens,n.outputTokens+=s.outputTokens,n.cachedInputTokens+=s.cachedInputTokens;continue}let i=Ti(o)??yi(o);i&&(e=i);}catch{}return n||(e??void 0)}var Ei=new Set(["tool_progress"]);function zr(t){let e=t.split(`
|
|
305
|
+
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var En={command:"claude",meta:{displayName:"Claude",models:Or(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=je(e.model),s=e.effort??o,i=$r(e.mode),a=Hr(s),l=r?["--model",r]:[],c=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let g=[...e.additionalArgs];return g.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...c,...i,...a,...l,...g],stdinMessage:t}:{args:["--output-format","stream-json","--verbose",...c,...i,...a,...l,...g],stdinMessage:t}}return {args:["-p","--output-format","stream-json","--verbose",...c,...i,...a,...l],stdinMessage:t}},extractText(t){return zr(t)??t.trim()},extractPartialText(t){return zr(t)},extractFailure(t){try{let e=JSON.parse(t);if(e.type==="rate_limit_event"){let n=e.rate_limit_info??{};if(n.status==="rejected")return new Ne(`Claude rate limit: ${n.rateLimitType??"unknown"} (status: ${n.status})`)}if(e.error==="rate_limit"){let n=Ri(e);return new Ne(n?`Claude rate limit: ${n}`:"Claude rate limit")}if(e.type==="result"&&e.is_error===!0){let n=typeof e.result=="string"?e.result:"";if(Ii(n))return new Ne(`Claude rate limit: ${n}`)}}catch{}return null},parseResultMeta(t){let e=t.split(`
|
|
306
|
+
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,i=s?{inputTokens:Number(s.input_tokens??0)+Number(s.cache_read_input_tokens??0),outputTokens:Number(s.output_tokens??0),cachedInputTokens:Number(s.cache_read_input_tokens??0),costUsd:Number(o.total_cost_usd??0)}:null,a=o.modelUsage,l=a?Object.keys(a)[0]??null:null;return {usage:i,model:l}}}catch{}let n=Wr(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 [];if(r!=="assistant"&&r!=="user")return [];let s=n.message?.content;if(!Array.isArray(s))return [];let i=e??new Date().toISOString(),a=[];for(let l of s){let c=vi(i,l);c&&a.push(c);}return a},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Ei.has(r):!1}catch{return false}}};function Ri(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
307
307
|
|
|
308
|
-
`):""}function
|
|
309
|
-
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...
|
|
310
|
-
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}
|
|
311
|
-
`).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}return n.length>0?n[n.length-1]:r||t.trim()},parseResultMeta(t){let e=Qe(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=Ei(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let a=i.type;if(!a||!a.startsWith("item.")&&!a.startsWith("turn.")&&!a.startsWith("thread."))continue;let l=i.item;if(l){if(a==="item.started"){r.push(...Ii(n,l));continue}if(a==="item.completed"){let c=Ai(n,l);c&&r.push(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?wi.has(r):!1}catch{return false}}};function Ii(t,e){let n=e.type;if(n==="command_execution"){let r=String(e.command||"");return ke(r)?[Te(t,r)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:r}]}return n==="web_search"?[]:n==="file_change"?[]:[]}function Ai(t,e){let n=e.type;if(n==="message"||n==="text"){let r=e.content;if(Array.isArray(r))for(let o of r){let s=vi(t,o);if(s)return s}if(typeof e.text=="string")return {timestamp:t,type:"text",content:e.text}}if(n==="agent_message"&&typeof e.text=="string")return {timestamp:t,type:"text",content:e.text};if(n==="reasoning"){let r=typeof e.text=="string"?e.text.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="command_execution"){let r=String(e.aggregated_output||e.output||""),o=!!e.is_error;return {timestamp:t,type:"tool_result",...Ne(r,o)}}if(n==="tool_use"){let r=String(e.name||e.tool_name||""),o=e.input,s=ye(o);return r==="Bash"&&ke(s)?Te(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}if(n==="tool_result"){let r=!!e.is_error,o=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...Ne(o,r)}}if(n==="web_search"){let r=e.action,o;if(r?.type==="search"){let s=r.queries;o=String(r.query||"")||(s?.length?s.join(", "):"")||String(e.query||"");}else o=e.query?"open: "+String(e.query):"";return o?{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:o}:null}if(n==="file_change"){let r=e.changes;if(!Array.isArray(r)||r.length===0)return null;let o=r.map(i=>String(i.path||"")).filter(Boolean);if(o.length===0)return null;let s=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:s}}return null}function vi(t,e){let n=e.type;if(n==="text")return {timestamp:t,type:"text",content:String(e.text||"")};if(n==="tool_use"){let r=String(e.name||""),o=e.input,s=ye(o);return r==="Bash"&&ke(s)?Te(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var Si=new Set(["step_start","step_finish"]),Ze="cli/opencode",zr="OpenCode provider error",Vr=240,xi={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};function Oi(t){return t?xi[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Ft(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Kr(t){let e=[],n=0,r=false,o=false,s=0;for(let a=0;a<t.length;a++){let l=t[a];if(o){o=false;continue}if(l==="\\"&&r){o=true;continue}if(l==='"'){r=!r;continue}if(!r){if(l==="{")n++;else if(l==="}"&&(n--,n===0)){let c=t.slice(s,a+1).trim();c&&e.push(c),s=a+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function et(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bi(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let i=JSON.parse(o);et(i)?e.push(i):n=!0;continue}catch{}let s=Kr(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of s)try{let a=JSON.parse(i);et(a)?e.push(a):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Ve(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,Vr).trim()}function Jr(t){let e=et(t.error)?t.error:void 0,n=e&&et(e.data)?e.data:void 0,r=Ve(e?.name),o=Ve(n?.message)??Ve(e?.message)??Ve(t.message)??Ve(t.errorMessage)??Ve(t.error),s=Ve(t.ref),i=r&&o&&r!==o?`${r}: ${o}`:r??o??zr;return (s?`${i} (ref: ${s})`:i).slice(0,Vr)}function Gr(t){let e=bi(t),n=[],r=null,o=0,s=[],i,a=false;for(let l of e.events){let c=typeof l.type=="string"?l.type:void 0;if(c){if(c==="text"){let u=et(l.part)?l.part:void 0,g=typeof u?.text=="string"?u.text:void 0;g?.trim()&&n.push(g.trim());continue}if(c==="result"){typeof l.result=="string"&&(r=l.result);continue}if(c==="tool_use"){o++;continue}if(c==="error"){s.push(Jr(l));continue}if(c==="step_finish"){a=true;let u=et(l.part)?l.part:void 0;i=typeof u?.reason=="string"?u.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorMessages:s,terminalReason:i,hasTerminal:a}}function Yr(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function qt(){return new W("OpenCode returned no assistant output.",Ze,{code:"EMPTY_OUTPUT",kind:"transient"})}function Ci(){return new W("OpenCode emitted malformed JSON output.",Ze,{code:"PROVIDER_CRASHED",kind:"transient"})}function Wr(t,e){switch(Yr(t)){case "length":return new W("OpenCode stopped because the context window was exceeded.",Ze,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new W("OpenCode stopped because the content filter blocked the response.",Ze,{code:"UNKNOWN",kind:"permanent"});case "error":return new W(e?`OpenCode error: ${e}`:`${zr} while generating a response.`,Ze,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var Rn={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Ft(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=Oi(e.mode);Ft(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!Ft(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!Ft(o,"--variant")&&o.push("--variant",e.effort),e.model&&o.push("--model",e.model);let a;return !n&&!i&&!e.env?.OPENCODE_PERMISSION&&(a={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:o,stdinMessage:t,env:a}},extractText(t){let e=Gr(t),n=e.errorMessages[0];if(n){let i=Wr("error",n);if(i)throw i}let r=Wr(e.terminalReason??"",void 0);if(r)throw r;let o=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(o!==void 0){if(!e.hasTerminal)throw qt();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw qt();return e.resultText}if(e.malformed)throw Ci();if(!e.hasTerminal)throw qt();let s=Yr(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw qt()},interpretExit(t,e,n=""){if(t===0)return null;let o=Gr(n).errorMessages[0];return o?new W(`OpenCode error: ${o}`,Ze,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=Qe(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=Kr(t),o.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let a=i.type;if(a){if(a==="text"){let c=i.part?.text;c&&r.push({timestamp:n,type:"text",content:c});continue}if(a==="tool_use"){let l=i.part;if(!l)continue;let c=String(l.tool||""),u=String(l.callID||""),g=l.state,h=String(g?.status||""),m=g?.input,S=ye(m);if(r.push({timestamp:n,type:"tool_use",toolName:c,toolUseId:u,toolInput:S}),h==="completed"&&g?.output!==void 0){let I=g.output,A=typeof I=="string"?I:JSON.stringify(I);r.push({timestamp:n,type:"tool_result",toolUseId:u,resultPreview:A,isError:false});}else h==="error"&&r.push({timestamp:n,type:"tool_result",toolUseId:u,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(a==="error"){let l=Jr(i);r.push({timestamp:n,type:"error",content:l,errorMessage:l});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?Si.has(r):!1}catch{return false}}};var In="antigravity";function ht(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ni(t,e){if(!(t?qe(In).some(s=>s.id===t):false)||!t)return e;let r=ft(In,t),o=vr(In)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var An={command:"agy",meta:{displayName:"Antigravity",models:br(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=Be(e.model),s=kn(r),i=s.model,a=e.effort??o??s.effort,l=Ni(i,a),c=e.additionalArgs??[],u=i&&!ht(c,"--model")?["--model",i]:[],g=ht(c,"--effort")?[]:Br(l),h=ht(c,"--mode")||ht(c,"--dangerously-skip-permissions")?[]:qr(e.mode),m=ht(c,"--print")?[]:["--print",t];return {args:[...u,...g,...h,...c,...m]}},extractText(t){let e=t.trim();if(!e)throw new W("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 Bt="cli/grok",Li=new Set(["available_commands","usage","end"]),Pi=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,Mi=/\u001b\[[0-?]*[ -/]*[@-~]/g,Xr=20,Qr=4e3,Zr="\u2026";function tt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function jt(t){return tt(t)?t:void 0}function J(t){return typeof t=="string"?t:void 0}function Ke(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function $i(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let a=t[i];if(n===-1){(a==="{"||a==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(a==="\\"&&o){s=true;continue}if(a==='"'){o=!o;continue}o||(a==="{"||a==="["?r+=1:(a==="}"||a==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function mt(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return tt(n)?[n]:[]}catch{return $i(e).flatMap(n=>{try{let r=JSON.parse(n);return tt(r)?[r]:[]}catch{return []}})}}function _t(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function kt(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(kt).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
312
|
-
`):void 0}if(
|
|
313
|
-
`).flatMap(
|
|
314
|
-
`),o=r.length>
|
|
315
|
-
`).flatMap(
|
|
316
|
-
`).flatMap(
|
|
317
|
-
`)
|
|
308
|
+
`):""}function Ii(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function vi(t,e){let n=e.type;if(n==="text"){let r=String(e.text||"");return r?{timestamp:t,type:"text",content:r}:null}if(n==="thinking"){let r=typeof e.thinking=="string"?e.thinking.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="tool_use"){let r=String(e.name||""),o=e.id,s=e.input,i=we(s);return r==="Bash"&&Te(i)?ye(t,i,o):{timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:i}}if(n==="tool_result"){let r=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(`
|
|
309
|
+
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...De(i,r)}}return null}var Ai=new Set(["interactive","plan","autopilot"]),Si=new Set(["none","low","medium","high","xhigh","max"]);function Vr(t){let e=t.split(`
|
|
310
|
+
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var Rn={command:"copilot",meta:{displayName:"Copilot",models:br()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&Ai.has(e.mode)&&r.push("--mode",e.mode),e.effort&&Si.has(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){return Vr(t)??t.trim()},extractPartialText(t){return Vr(t)},parseResultMeta(t){let e=Ze(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];if(!r.startsWith("tool.execution")&&!r.startsWith("assistant.")&&r!=="user.message")return [];let o=n.data;if(!o)return [];let s=e??new Date().toISOString(),i=o.toolCallId;if(r==="tool.execution_start"){let a=String(o.toolName||""),l=o.arguments,c=we(l);return (a==="bash"||a==="Bash")&&Te(c)?[ye(s,c,i)]:[{timestamp:s,type:"tool_use",toolName:a,toolInput:c,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let a=o.error;if(a)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...De(String(a.message||""),true)}];let l=o.result,c=String(l?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...De(c,false)}]}if(r==="assistant.message"){let a=String(o.content||"");return a?[{timestamp:s,type:"text",content:a}]:[]}return []}};var xi=new Set(["turn.started","turn.completed","item.updated"]);function Oi(t){let e=[],n=0,r=false,o=false,s=0;for(let a=0;a<t.length;a++){let l=t[a];if(o){o=false;continue}if(l==="\\"&&r){o=true;continue}if(l==='"'){r=!r;continue}if(!r){if(l==="{")n++;else if(l==="}"&&(n--,n===0)){let c=t.slice(s,a+1).trim();c&&e.push(c),s=a+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function Ci(t){return t[0]==="exec"?t.slice(1):t}function Jr(t){let e=t.split(`
|
|
311
|
+
`).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var In={command:"codex",meta:{displayName:"Codex",models:Cr(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=je(e.model),s=e.effort??o,i=e.resumeSessionId?Lr(e.mode):Pr(e.mode),a=Mr(s),l=r?["-m",r]:[],c=Ci(e.additionalArgs??[]),g=c.includes("--json")||c.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...g,...i,...a,...l,...c,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...g,...i,...a,...l,...c],stdinMessage:t}},extractText(t){return Jr(t)??t.trim()},extractPartialText(t){return Jr(t)},parseResultMeta(t){let e=Ze(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=Oi(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let a=i.type;if(!a||!a.startsWith("item.")&&!a.startsWith("turn.")&&!a.startsWith("thread."))continue;let l=i.item;if(l){if(a==="item.started"){r.push(...bi(n,l));continue}if(a==="item.completed"){let c=Ni(n,l);c&&r.push(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?xi.has(r):!1}catch{return false}}};function bi(t,e){let n=e.type;if(n==="command_execution"){let r=String(e.command||"");return Te(r)?[ye(t,r)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:r}]}return n==="web_search"?[]:n==="file_change"?[]:[]}function Ni(t,e){let n=e.type;if(n==="message"||n==="text"){let r=e.content;if(Array.isArray(r))for(let o of r){let s=Di(t,o);if(s)return s}if(typeof e.text=="string")return {timestamp:t,type:"text",content:e.text}}if(n==="agent_message"&&typeof e.text=="string")return {timestamp:t,type:"text",content:e.text};if(n==="reasoning"){let r=typeof e.text=="string"?e.text.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="command_execution"){let r=String(e.aggregated_output||e.output||""),o=!!e.is_error;return {timestamp:t,type:"tool_result",...De(r,o)}}if(n==="tool_use"){let r=String(e.name||e.tool_name||""),o=e.input,s=we(o);return r==="Bash"&&Te(s)?ye(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}if(n==="tool_result"){let r=!!e.is_error,o=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...De(o,r)}}if(n==="web_search"){let r=e.action,o;if(r?.type==="search"){let s=r.queries;o=String(r.query||"")||(s?.length?s.join(", "):"")||String(e.query||"");}else o=e.query?"open: "+String(e.query):"";return o?{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:o}:null}if(n==="file_change"){let r=e.changes;if(!Array.isArray(r)||r.length===0)return null;let o=r.map(i=>String(i.path||"")).filter(Boolean);if(o.length===0)return null;let s=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:s}}return null}function Di(t,e){let n=e.type;if(n==="text")return {timestamp:t,type:"text",content:String(e.text||"")};if(n==="tool_use"){let r=String(e.name||""),o=e.input,s=we(o);return r==="Bash"&&Te(s)?ye(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var Pi=new Set(["step_start","step_finish"]),et="cli/opencode",Xr="OpenCode provider error",Qr=240,Li={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};function Mi(t){return t?Li[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function qt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Zr(t){let e=[],n=0,r=false,o=false,s=0;for(let a=0;a<t.length;a++){let l=t[a];if(o){o=false;continue}if(l==="\\"&&r){o=true;continue}if(l==='"'){r=!r;continue}if(!r){if(l==="{")n++;else if(l==="}"&&(n--,n===0)){let c=t.slice(s,a+1).trim();c&&e.push(c),s=a+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function tt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function $i(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let i=JSON.parse(o);tt(i)?e.push(i):n=!0;continue}catch{}let s=Zr(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of s)try{let a=JSON.parse(i);tt(a)?e.push(a):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Je(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,Qr).trim()}function eo(t){let e=tt(t.error)?t.error:void 0,n=e&&tt(e.data)?e.data:void 0,r=Je(e?.name),o=Je(n?.message)??Je(e?.message)??Je(t.message)??Je(t.errorMessage)??Je(t.error),s=Je(t.ref),i=r&&o&&r!==o?`${r}: ${o}`:r??o??Xr;return (s?`${i} (ref: ${s})`:i).slice(0,Qr)}function Kr(t){let e=$i(t),n=[],r=null,o=0,s=[],i,a=false;for(let l of e.events){let c=typeof l.type=="string"?l.type:void 0;if(c){if(c==="text"){let u=tt(l.part)?l.part:void 0,g=typeof u?.text=="string"?u.text:void 0;g?.trim()&&n.push(g.trim());continue}if(c==="result"){typeof l.result=="string"&&(r=l.result);continue}if(c==="tool_use"){o++;continue}if(c==="error"){s.push(eo(l));continue}if(c==="step_finish"){a=true;let u=tt(l.part)?l.part:void 0;i=typeof u?.reason=="string"?u.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorMessages:s,terminalReason:i,hasTerminal:a}}function to(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Bt(){return new W("OpenCode returned no assistant output.",et,{code:"EMPTY_OUTPUT",kind:"transient"})}function Hi(){return new W("OpenCode emitted malformed JSON output.",et,{code:"PROVIDER_CRASHED",kind:"transient"})}function Yr(t,e){switch(to(t)){case "length":return new W("OpenCode stopped because the context window was exceeded.",et,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new W("OpenCode stopped because the content filter blocked the response.",et,{code:"UNKNOWN",kind:"permanent"});case "error":return new W(e?`OpenCode error: ${e}`:`${Xr} while generating a response.`,et,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var vn={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];qt(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=Mi(e.mode);qt(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!qt(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!qt(o,"--variant")&&o.push("--variant",e.effort),e.model&&o.push("--model",e.model);let a;return !n&&!i&&!e.env?.OPENCODE_PERMISSION&&(a={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:o,stdinMessage:t,env:a}},extractText(t){let e=Kr(t),n=e.errorMessages[0];if(n){let i=Yr("error",n);if(i)throw i}let r=Yr(e.terminalReason??"",void 0);if(r)throw r;let o=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(o!==void 0){if(!e.hasTerminal)throw Bt();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw Bt();return e.resultText}if(e.malformed)throw Hi();if(!e.hasTerminal)throw Bt();let s=to(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw Bt()},interpretExit(t,e,n=""){if(t===0)return null;let o=Kr(n).errorMessages[0];return o?new W(`OpenCode error: ${o}`,et,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=Ze(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=Zr(t),o.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let a=i.type;if(a){if(a==="text"){let c=i.part?.text;c&&r.push({timestamp:n,type:"text",content:c});continue}if(a==="tool_use"){let l=i.part;if(!l)continue;let c=String(l.tool||""),u=String(l.callID||""),g=l.state,h=String(g?.status||""),m=g?.input,S=we(m);if(r.push({timestamp:n,type:"tool_use",toolName:c,toolUseId:u,toolInput:S}),h==="completed"&&g?.output!==void 0){let I=g.output,v=typeof I=="string"?I:JSON.stringify(I);r.push({timestamp:n,type:"tool_result",toolUseId:u,resultPreview:v,isError:false});}else h==="error"&&r.push({timestamp:n,type:"tool_result",toolUseId:u,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(a==="error"){let l=eo(i);r.push({timestamp:n,type:"error",content:l,errorMessage:l});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?Pi.has(r):!1}catch{return false}}};var An="antigravity";function mt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ui(t,e){if(!(t?Be(An).some(s=>s.id===t):false)||!t)return e;let r=ht(An,t),o=xr(An)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var Sn={command:"agy",meta:{displayName:"Antigravity",models:Nr(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=je(e.model),s=yn(r),i=s.model,a=e.effort??o??s.effort,l=Ui(i,a),c=e.additionalArgs??[],u=i&&!mt(c,"--model")?["--model",i]:[],g=mt(c,"--effort")?[]:Gr(l),h=mt(c,"--mode")||mt(c,"--dangerously-skip-permissions")?[]:jr(e.mode),m=mt(c,"--print")?[]:["--print",t];return {args:[...u,...g,...h,...c,...m]}},extractText(t){let e=t.trim();if(!e)throw new W("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 jt="cli/grok",qi=new Set(["available_commands","usage","end"]),Bi=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,ji=/\u001b\[[0-?]*[ -/]*[@-~]/g,no=20,ro=4e3,oo="\u2026";function nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Gt(t){return nt(t)?t:void 0}function K(t){return typeof t=="string"?t:void 0}function Ke(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Gi(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let a=t[i];if(n===-1){(a==="{"||a==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(a==="\\"&&o){s=true;continue}if(a==='"'){o=!o;continue}o||(a==="{"||a==="["?r+=1:(a==="}"||a==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function _t(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return nt(n)?[n]:[]}catch{return Gi(e).flatMap(n=>{try{let r=JSON.parse(n);return nt(r)?[r]:[]}catch{return []}})}}function kt(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function Tt(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(Tt).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
312
|
+
`):void 0}if(nt(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=Tt(t[e]);if(n!==void 0)return n}}}function Wi(t){if(t.rawOutput!==null&&t.rawOutput!==void 0)return Tt(t.rawOutput)??kt(t.rawOutput);if(t.content!==null&&t.content!==void 0)return Tt(t.content)??kt(t.content);if(t.result!==null&&t.result!==void 0)return Tt(t.result)??kt(t.result)}function io(t){let e=Gt(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?ao(n):"Grok CLI reported an error."}function ao(t){return (t.replace(ji,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function so(t){return Bi.test(t)}function zi(t){let e=Gt(t.modelUsage);return e?Object.keys(e)[0]??null:null}function Vi(t){let e=Gt(t.usage);if(!e)return null;let n=Ke(e.cache_read_input_tokens);return {inputTokens:Ke(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Ke(e.output_tokens),costUsd:Ke(t.total_cost_usd)}}function Ji(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
|
|
313
|
+
`).flatMap(_t)){if(i.type!=="usage")continue;let a=Gt(i.usage);if(!a)continue;let l=K(i.signature);if(l&&l.length>0){let u=`signature:${l}`;if(s.has(u))continue;s.add(u);}let c=Ke(a.cache_read_input_tokens);e+=Ke(a.input_tokens)+c,n+=c,r+=Ke(a.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function Ki(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,no)){if(!nt(s))continue;let i=K(s.content)?.trim();if(!i)continue;let a=K(s.status)?.trim(),l=K(s.priority)?.trim(),c=[a?`status=${a}`:void 0,l?`priority=${l}`:void 0].filter(g=>!!g),u=c.length>0?` (${c.join(", ")})`:"";n.push(`- ${i}${u}`);}if(n.length===0)return [];e.entries.length>no&&n.push(oo);let r=n.join(`
|
|
314
|
+
`),o=r.length>ro?`${r.slice(0,ro-1)}${oo}`:r;return [{timestamp:t,type:"info",content:o}]}function Yi(t,e){let n=K(e.type);if(n==="thought"){let r=K(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=K(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return Ki(t,e);if(n==="tool_call"){let r=K(e.toolCallId),o=K(e.toolName)??K(e.title),s=e.rawInput===void 0?void 0:kt(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:o,toolInput:s}]}if(n==="tool_call_update"){let r=K(e.status);return r!=="completed"&&r!=="failed"&&r!=="error"?[]:[{timestamp:t,type:"tool_result",toolUseId:K(e.toolCallId),toolName:K(e.toolName)??K(e.title),resultPreview:Wi(e),isError:r!=="completed"||e.isError===true}]}if(n==="error"){let r=io(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}var xn={command:"grok",createSessionId:()=>crypto.randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=je(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],a=n?Be("grok").some(ae=>ae.id===n):false,l=n&&a?ht("grok",n):[],c=!o||l.length===0||l.includes(o)?o:void 0,u=Br(c),g=e.additionalArgs??[],h=ae=>g.some(ee=>ee===ae||ee.startsWith(`${ae}=`)),m=e.providerOptions,S=m?.alwaysApprove,I=m?.sandbox,v=h("--permission-mode")?[]:Ur(e.mode),$=h("--always-approve")?[]:Fr(S),B=h("--sandbox")?[]:qr(I);return {args:["--no-auto-update",...s,"--single",t,"--output-format","streaming-json","--no-alt-screen",...i,...u,...v,...$,...B,...g]}},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
315
|
+
`).flatMap(_t))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 _t(t))if(e.type==="error"){let n=io(e);return so(kt(e))?new Ne(n,jt):new W(n,jt)}return null},interpretExit(t,e){if(t===0)return null;let n=ao(e)||`Grok CLI exited with code ${t}.`;return so(e)?new Ne(n,jt):new W(n,jt)},parseResultMeta(t){let n=t.split(`
|
|
316
|
+
`).flatMap(_t).find(r=>r.type==="end");return n?{usage:Vi(n),model:zi(n)}:{usage:Ji(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return _t(t).flatMap(r=>Yi(n,r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return nt(n)&&typeof n.type=="string"?qi.has(n.type):!1}catch{return false}}};var lo={codex:In,claude:En,opencode:vn,antigravity:Sn,copilot:Rn,grok:xn};function co(t){if(t.startsWith("cli/"))return lo[t.slice(4)]}function Xi(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let o=r.type;if(typeof o!="string")return false;let s=e?sa[e]:void 0;return s?s(r,o):Object.values(po).some(i=>i(r,o))}function Wt(t,e){let n=t.split(`
|
|
317
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>Xi(r,e))}function se(t){return typeof t=="object"&&t!==null}function uo(t,e){if(e==="assistant"||e==="user"){let n=t.message;return se(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||se(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?se(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function Qi(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:uo(t,e)}function Zi(t,e){if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return se(n)&&typeof n.type=="string"}return false}function ea(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||se(t.part):e==="text"||e==="tool_use"?se(t.part):e==="result"?typeof t.result=="string":false}function ta(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||se(t.part)||e==="result"&&typeof t.result=="string")}function na(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?se(t.data):e==="result"?typeof t.result=="string":false}function ra(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 oa(t,e){return e==="available_commands"?se(t.tools)||se(t.commands):e==="usage"?se(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||se(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var po={claude:uo,codex:Zi,opencode:ea,copilot:na,gemini:ra},sa={...po,claude:Qi,opencode:ta,grok:oa,antigravity:()=>false};var aa=200,da=200;function la(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 ca(t){let e=t instanceof p?t.code:void 0,n=t instanceof p?t.cause:t,r=la(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function fo(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function ua(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pa(t){if(!t)return {};try{let e=JSON.parse(t);return ua(e)?e:{}}catch{return {}}}function ho(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Cn=class extends Me{name="sqlite-tracing";unsubs=[];dbPath;version;taskRepo;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super(),this.dbPath=Re.join(e?.dbRoot??Fo.homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown";}attach(e){let n=new Ut({dbPath:this.dbPath});this.taskRepo=n;let r=process.cwd(),s=fs.existsSync(Re.join(r,"crewx.yaml"))||fs.existsSync(Re.join(r,"crewx.yml"))?Jn(r):null,i=process.argv.join(" ");this.unsubs.push(e.on("task:start",a=>{try{let l=a.callerAgentId??null,c=a.parentTaskId??null,u=a.rootTraceId??a.traceId,g=a.metadata?JSON.stringify(a.metadata):JSON.stringify({provider:a.provider??"cli/claude"});n.startTask({id:a.traceId,agentId:a.agentRef.replace(/^@/,""),prompt:a.message,mode:a.mode,status:"running",pid:a.pid??null,startedAt:a.timestamp.toISOString(),crewxVersion:this.version,platform:a.platform??"cli",model:a.model??null,renderedPrompt:a.renderedPrompt??null,command:i,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??s,projectId:a.projectId??null,callerAgentId:l,parentTaskId:c,traceId:u,metadata:g,threadId:a.threadId??null});}catch{}}),e.on("task:output",a=>{try{this.enqueueLog(a.traceId,{timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output});}catch(l){let c={timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output};this.recordAppendFailure(l,[c],fo(c));}}),e.on("task:end",a=>{try{this.flushTaskLogs(a.traceId);let l=typeof a.metadata?.runEpoch=="number"?a.metadata.runEpoch:null,c=a.error?JSON.stringify({code:a.error.code,message:a.error.message,...a.error.providerCode?{providerCode:a.error.providerCode}:{}}):null,u=a.result??null,g=!1;if(a.error&&(!u||u.trim()==="")){let h=this.recoverPartialResult(a.traceId,a,l);h&&(u=h,g=!0);}n.finishTask({id:a.traceId,status:a.error?"failed":"success",result:u,error:c,completedAt:a.timestamp.toISOString(),durationMs:a.durationMs,exitCode:a.exitCode??null,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cachedInputTokens:a.cachedInputTokens??0,costUsd:a.costUsd??0,model:a.model??null,runEpoch:l,partialResultRecovered:g});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.taskRepo=void 0;}}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}}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+=fo(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>=aa){this.flushTaskLogs(e);return}if(!r.timer){let o=setTimeout(()=>{let s=this.queues.get(e);!s||s.timer!==o||(s.timer=void 0,this.flushTaskLogs(e));},da);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo?.getTask(e);if(!o||o.status!=="running"||ho(o.run_epoch)!==ho(r))return;let s=pa(o.metadata),i=typeof s.provider=="string"?s.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!i)return;let a=co(i);if(!a?.extractPartialText)return;let c=this.taskRepo?.readLogs(e)?.entries.filter(g=>g.level==="stdout").map(g=>g.message).join(`
|
|
318
|
+
`)??"";if(!c.trim())return;let u=a.extractPartialText(c);return !u||!u.trim()||Wt(u,i)?void 0:u}catch{return}}flushTaskLogs(e){let n=this.queues.get(e);if(!n||n.entries.length===0){n?.timer&&clearTimeout(n.timer),this.queues.delete(e);return}n.timer&&(clearTimeout(n.timer),n.timer=void 0);let r=n.entries,o=n.bytes;n.entries=[],n.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(i){this.recordAppendFailure(i,r,o);}let s=this.queues.get(e);s&&s.entries.length===0&&(s.timer&&clearTimeout(s.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,n,r){let o=ca(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=n.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[o.code]=(this.metrics.appendFailureByCode[o.code]??0)+1,this.metrics.appendFailureByCause[o.cause]=(this.metrics.appendFailureByCause[o.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:o.code,cause:o.cause,pendingEntries:n.length,pendingBytes:r});}};var rt=class extends p{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function yt(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function _a(t){let n=yt(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}}var zt=class extends te{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Re.dirname(n);fs.existsSync(o)||fs.mkdirSync(o,{recursive:true});}else if(!fs.existsSync(n))throw new p("NOT_FOUND","Database not found");let r=L(n);if(e)try{ge(r.db,n);}catch(o){throw r.close(),o}return r}validateWorkspaceId(e,n){return e.db.select({id:Xe.id}).from(Xe).where(drizzleOrm.eq(Xe.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(e="child"){return drizzleOrm.sql.raw(`NOT EXISTS (
|
|
318
319
|
SELECT 1 FROM tasks parent
|
|
319
320
|
WHERE parent.id = ${e}.parent_task_id
|
|
320
321
|
AND parent.thread_id = ${e}.thread_id
|
|
321
|
-
)`)}findAllThreads(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!fs.existsSync(s))continue;let i=
|
|
322
|
+
)`)}findAllThreads(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!fs.existsSync(s))continue;let i=L(s);try{let a=e?drizzleOrm.eq(f.workspace_id,e):void 0,l=i.db.select().from(f).where(a).orderBy(drizzleOrm.desc(f.updated_at)).all();for(let c of l)r.has(c.id)||(r.add(c.id),o.push(c));}catch(a){throw new p("DB_ERROR","Failed to find all threads",a)}finally{i.close();}}return o}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!fs.existsSync(i))continue;let a=L(i);try{let l=drizzleOrm.or(drizzleOrm.inArray(f.id,e),drizzleOrm.inArray(f.title,e)),c=n?drizzleOrm.and(l,drizzleOrm.eq(f.workspace_id,n)):l,u=a.db.select().from(f).where(c).orderBy(drizzleOrm.desc(f.updated_at)).all();for(let g of u)o.has(g.id)||(o.add(g.id),s.push(g));}catch(l){throw new p("DB_ERROR","Failed to find threads by ids or titles",l)}finally{a.close();}}return s}findThreadById(e,n){let r=this.resolveDbPaths();for(let o of r){if(!fs.existsSync(o))continue;let s=L(o);try{let i=drizzleOrm.eq(f.id,e),a=n?drizzleOrm.and(i,drizzleOrm.eq(f.workspace_id,n)):i,l=s.db.select().from(f).where(a).limit(1).get()??void 0;if(l)return l}catch(i){throw new p("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(e,n){let r=this.resolveDbPaths();for(let o of r){if(!fs.existsSync(o))continue;let s=L(o);try{let i=drizzleOrm.eq(f.id,e),a=n?drizzleOrm.and(i,drizzleOrm.eq(f.workspace_id,n)):i;if(s.db.select({id:f.id}).from(f).where(a).limit(1).get())return !0}catch(i){throw new p("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),o=0,s=0,i=0,a=0,l=0,c=new Set;for(let u of r){if(!fs.existsSync(u))continue;let g=L(u);try{let h=g.db.get(drizzleOrm.sql`
|
|
322
323
|
SELECT
|
|
323
324
|
count(*) AS cnt,
|
|
324
325
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -335,7 +336,7 @@ ${r.join(`
|
|
|
335
336
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
336
337
|
AND ${this.topLevelTaskPredicateSql()}
|
|
337
338
|
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
338
|
-
`);for(let S of m)c.add(S.agent_id);}catch(h){throw new p("DB_ERROR","Failed to aggregate task stats",h)}finally{g.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:a,costUsd:l,agentIds:Array.from(c)}}findTopLevelTasks(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[];for(let a of o){if(!fs.existsSync(a))continue;let l=
|
|
339
|
+
`);for(let S of m)c.add(S.agent_id);}catch(h){throw new p("DB_ERROR","Failed to aggregate task stats",h)}finally{g.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:a,costUsd:l,agentIds:Array.from(c)}}findTopLevelTasks(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[];for(let a of o){if(!fs.existsSync(a))continue;let l=L(a);try{let c;r!==void 0?c=l.db.all(drizzleOrm.sql`
|
|
339
340
|
SELECT * FROM (
|
|
340
341
|
SELECT child.*,
|
|
341
342
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -352,7 +353,7 @@ ${r.join(`
|
|
|
352
353
|
AND ${this.topLevelTaskPredicateSql()}
|
|
353
354
|
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
354
355
|
ORDER BY child.started_at ASC
|
|
355
|
-
`);for(let u of c)s.has(u.id)||(s.add(u.id),i.push(u));}catch(c){throw new p("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}if(r!==void 0&&o.length>1){let a=new Map;for(let l of i){let c=l.agent_id??"";a.has(c)||a.set(c,[]),a.get(c).push(l);}i=[];for(let l of a.values())l.sort((c,u)=>(u.started_at??"").localeCompare(c.started_at??"")),i.push(...l.slice(0,r));i.sort((l,c)=>(l.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!fs.existsSync(i))continue;let a=
|
|
356
|
+
`);for(let u of c)s.has(u.id)||(s.add(u.id),i.push(u));}catch(c){throw new p("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}if(r!==void 0&&o.length>1){let a=new Map;for(let l of i){let c=l.agent_id??"";a.has(c)||a.set(c,[]),a.get(c).push(l);}i=[];for(let l of a.values())l.sort((c,u)=>(u.started_at??"").localeCompare(c.started_at??"")),i.push(...l.slice(0,r));i.sort((l,c)=>(l.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!fs.existsSync(i))continue;let a=L(i);try{let l=drizzleOrm.eq(d.thread_id,e),c=n?drizzleOrm.and(l,drizzleOrm.eq(d.workspace_id,n)):l,u=a.db.select().from(d).where(c).orderBy(drizzleOrm.asc(d.started_at)).all();for(let g of u)o.has(g.id)||(o.add(g.id),s.push(g));}catch(l){throw new p("DB_ERROR","Failed to find all tasks for thread",l)}finally{a.close();}}return s}findTaskById(e,n,r){let o=this.resolveDbPaths();for(let s of o){if(!fs.existsSync(s))continue;let i=L(s);try{let a=drizzleOrm.and(drizzleOrm.eq(d.id,n),drizzleOrm.eq(d.thread_id,e)),l=r?drizzleOrm.and(a,drizzleOrm.eq(d.workspace_id,r)):a,c=i.db.select().from(d).where(l).limit(1).get();if(!c)continue;let u=i.db.select().from(d).where(drizzleOrm.eq(d.parent_task_id,c.id)).orderBy(drizzleOrm.asc(d.started_at)).all();return {task:c,children:u}}catch(a){throw new p("DB_ERROR","Failed to find task by id",a)}finally{i.close();}}}batchFetchTasksQuery(e,n){return drizzleOrm.sql`
|
|
356
357
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
357
358
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
358
359
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -362,7 +363,7 @@ ${r.join(`
|
|
|
362
363
|
AND ${this.topLevelTaskPredicateSql()}
|
|
363
364
|
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
364
365
|
ORDER BY child.started_at ASC
|
|
365
|
-
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!fs.existsSync(s))continue;let i=
|
|
366
|
+
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!fs.existsSync(s))continue;let i=L(s);try{let a=i.db.all(this.batchFetchTasksQuery(e,n));for(let l of a){let c=l.thread_id;r.has(c)||r.set(c,[]),r.get(c).push(l);}}catch(a){throw new p("DB_ERROR","Failed to batch fetch tasks",a)}finally{i.close();}}return r}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!fs.existsSync(o))continue;let s=L(o);try{return s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(a=>a.detail)}finally{s.close();}}return []}updateThreadTitle(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=drizzleOrm.eq(f.id,e),i=r?drizzleOrm.and(s,drizzleOrm.eq(f.workspace_id,r)):s;if(!o.db.select({id:f.id}).from(f).where(i).limit(1).get())return;o.db.update(f).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(f.id,e)).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,n){let r=this.openHandle(true);try{let o=n.workspaceId?this.validateWorkspaceId(r,n.workspaceId):null,s=new Date().toISOString();if(r.db.select({id:f.id,message_count:f.message_count}).from(f).where(drizzleOrm.eq(f.id,e)).limit(1).get()){let a={updated_at:s};n.title!==void 0&&(a.title=n.title),n.titleLocked!==void 0&&(a.title_locked=n.titleLocked?1:0),r.db.update(f).set(a).where(drizzleOrm.eq(f.id,e)).run();}else r.db.insert(f).values({id:e,platform:n.platform,workspace_id:o,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to upsert thread",o)}finally{r.close();}}ensureThread(e,n,r){let o=this.openHandle(true);try{let s=r?this.validateWorkspaceId(o,r):null,i=o.db.select({id:f.id,platform:f.platform,workspace_id:f.workspace_id}).from(f).where(drizzleOrm.eq(f.id,e)).limit(1).get();if(i){s&&!i.workspace_id&&o.db.update(f).set({workspace_id:s}).where(drizzleOrm.eq(f.id,e)).run();return}let a=new Date().toISOString();o.db.insert(f).values({id:e,platform:n,workspace_id:s,message_count:0,created_at:a,updated_at:a}).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to ensure thread",s)}finally{o.close();}}saveUserMessage(e,n,r){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:o.db.transaction(a=>{let c=a.select({message_count:f.message_count}).from(f).where(drizzleOrm.eq(f.id,e)).limit(1).get()?.message_count===0;return a.run(drizzleOrm.sql`
|
|
366
367
|
UPDATE threads
|
|
367
368
|
SET first_message = COALESCE(first_message, ${n}),
|
|
368
369
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
@@ -370,11 +371,11 @@ ${r.join(`
|
|
|
370
371
|
message_count = message_count + 1,
|
|
371
372
|
updated_at = ${s}
|
|
372
373
|
WHERE id = ${e}
|
|
373
|
-
`),c},{behavior:"immediate"})}}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(f).set({last_message:n,updated_at:s}).where(drizzleOrm.eq(f.id,e)).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};n.title!==void 0&&(o.title=n.title,o.title_locked=1),n.titleLocked!==void 0&&(o.title_locked=n.titleLocked?1:0),r.db.update(f).set(o).where(drizzleOrm.eq(f.id,e)).run();}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let o=n;if(!o||typeof o!="object"||Array.isArray(o))return new nt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new nt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new nt("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let l of [i.priority,i.state])if(l!=null&&(typeof l!="string"||l.length===0))return new nt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let a=this.openHandle(true);try{let l=r?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,r)):drizzleOrm.eq(f.id,e);return a.db.transaction(c=>{let u=c.select({metadata:f.metadata}).from(f).where(l).get();if(!u)return null;let g=Tt(u.metadata),h=g.threadTitle,m=h&&typeof h=="object"&&!Array.isArray(h)?{...h}:{};i.priority===null?delete m.priority:i.priority!==void 0&&(m.priority=i.priority),i.state===null?delete m.state:i.state!==void 0&&(m.state=i.state),Object.keys(m).length>0?g.threadTitle=m:delete g.threadTitle;let S=Object.keys(g).length>0?JSON.stringify(g):null,I=new Date().toISOString();c.update(f).set({metadata:S,updated_at:I}).where(l).run();let A=c.select({metadata:f.metadata}).from(f).where(l).get();if(!A)throw new p("DB_ERROR","Thread-title metadata update could not be read back");let $=ta(A.metadata);return {threadId:e,priority:$.priority,state:$.state}},{behavior:"immediate"})}catch(l){throw l instanceof p?l:new p("DB_ERROR","Failed to patch thread-title metadata",l)}finally{a.close();}}togglePin(e,n){let r=this.openHandle(true);try{let o=n?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,n)):drizzleOrm.eq(f.id,e);return r.db.transaction(s=>{let i=s.select({pinned:f.pinned,metadata:f.metadata}).from(f).where(o).get();if(!i)return null;let a=i.pinned?0:1,l=Tt(i.metadata);if(a){let c=n?drizzleOrm.and(drizzleOrm.eq(f.pinned,1),drizzleOrm.eq(f.workspace_id,n)):drizzleOrm.eq(f.pinned,1),u=s.select({metadata:f.metadata}).from(f).where(c).all(),g=null;for(let h of u){let m=Tt(h.metadata);typeof m.pinOrder=="number"&&(g===null||m.pinOrder<g)&&(g=m.pinOrder);}l.pinOrder=g===null?0:g-1;}else delete l.pinOrder;return s.update(f).set({pinned:a,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(o).run(),{pinned:!!a}},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>{for(let s=0;s<e.length;s++){let i=n?drizzleOrm.and(drizzleOrm.eq(f.id,e[s]),drizzleOrm.eq(f.workspace_id,n)):drizzleOrm.eq(f.id,e[s]),a=o.select({metadata:f.metadata}).from(f).where(i).get();if(!a)continue;let l=Tt(a.metadata);l.pinOrder=s+1,o.update(f).set({metadata:JSON.stringify(l)}).where(i).run();}},{behavior:"immediate"});}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,n)):drizzleOrm.eq(f.id,e),s=r.db.select({starred:f.starred}).from(f).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(f).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let i=this.openHandle(true);try{let a=n?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,n)):drizzleOrm.eq(f.id,e);return i.db.transaction(c=>{let u=c.select({metadata:f.metadata}).from(f).where(a).get();if(!u)return null;let g=u.metadata?JSON.parse(u.metadata):{},h=g.overdrive??{},m=o?.defaultTurns??h.defaultTurns??3,S=o?.updatedBy??"ui",I=new Date().toISOString(),A,$,B,ie;switch(r){case "enable-count":{let ee=o?.turns??m,Le=o?.consumeCurrent?Math.max(ee-1,0):ee;A=Le>0?"count":"off",$=Le,B=!0,ie="count";break}case "enable-latch":{A="latch",$=0,B=!0,ie="latch";break}case "disable":{A="off",$=0,B=!1;break}default:{let ee=h.state??"off",Le=typeof h.remaining=="number"?h.remaining:0;if(ee==="count"&&Le>0){let O=Le-1;O<=0?(A="off",$=0):(A="count",$=O),B=!0,ie="count";}else ee==="latch"?(A="latch",$=0,B=!0,ie="latch"):(A="off",$=0,B=!1);break}}return g.overdrive={state:A,remaining:$,defaultTurns:m,updatedAt:I,updatedBy:S},c.update(f).set({metadata:JSON.stringify(g),updated_at:I}).where(a).run(),{applied:B,appliedMode:ie,state:A,remaining:$}},{behavior:"immediate"})}catch(a){throw a instanceof p?a:new p("DB_ERROR","Failed to resolve overdrive",a)}finally{i.close();}}};var On="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function na(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let o=e[r];o<248&&(n+=On[o%62]);}for(;n.length<t;)n+=On[crypto.randomBytes(1)[0]%62];return n}function yt(t){return `${t}_${na(8)}`}function go(t,e){let{createHash:n}=dt("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=r[i];let s="";for(let i of o)s+=On[i%62];return `${t}_${s}`}var ra=["urgent","high","medium","low"],oa=["investigating","in-progress","in-review","on-hold","done"],fo="custom:";var sa=new Set(ra),ia=new Set(oa);function bn(t){return typeof t=="string"&&sa.has(t)}function Cn(t){if(typeof t!="string")return false;if(ia.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(fo))return false;let e=t.slice(fo.length);return e.length>=1&&e.length<=20}function ho(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 Nn(t){let e=ho(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return bn(r.priority)&&(o.priority=r.priority),Cn(r.state)&&(o.state=r.state),o}function mo(t,e){let n=ho(t)??{},r={...Nn(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)}var ua="regeneration_replaced";var pa="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var ga="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Pn=class extends p{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=o;}},St=class extends Pn{},Mn=class extends p{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},fa=new Set(lr),ha=new Set(dr),ma=new Set(cr),_a=new Set(ur),ka=50,ko=100,To=280,yo=40,Ta=new Set(pr),Wt=["queued","running"],ya=["success","completed","done","failed","error"];function Ln(t){return Ta.has(t)}function N(t){throw new p("VALIDATION",t)}function ue(t){throw new p("NOT_FOUND",t)}function y(t,e){(typeof t!="string"||t.trim().length===0)&&N(`${e} is required`);}function Et(t={}){let e=t.actor??t,n=e.actorType??"system";return fa.has(n)||N(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&N("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function wa(t){y(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&y(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&N("title must not be empty"),t.title.length>120&&N("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!bn(t.priority)&&N(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Cn(t.state)&&N(`invalid state: ${String(t.state)}`);}function Ea(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&N("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)&&N(`${n} must be a non-negative integer`);let e=t.limit??ka;return (!Number.isInteger(e)||e<1||e>ko)&&N(`limit must be between 1 and ${ko}`),e}function $n(t){typeof t!="string"&&N("text is required");let e=t.trim();return e.length===0&&N("text must not be empty"),e.length>To&&N(`text must be at most ${To} characters`),e}function De(t,e){return y(t??"",e),t}function Hn(t){_a.has(t)||N(`invalid highlight kind: ${String(t)}`);}function Ra(t){ma.has(t)||N(`invalid highlight source: ${String(t)}`);}function Ia(t){y(t.threadId,"threadId"),y(t.workspaceId,"workspaceId");let e=t.source??"manual";Ra(e),Hn(t.kind);let n=$n(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let u=t.taskId??(r&&o&&r===o?r:void 0),g=De(u,"taskId");return (r!==g||o!==g)&&N("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:g,coversToTaskId:g,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=De(r,"coversFromTaskId"),i=De(o,"coversToTaskId"),a=t.sourceTaskId??s,l=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return De(a??void 0,"sourceTaskId"),De(l??void 0,"detectorVersion"),De(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:a,detectorVersion:l,contentFingerprint:c}}function Aa(t,e){(!t||typeof t!="object")&&N(`candidates[${e}] is required`),Hn(t.kind);let n=$n(t.text),r=De(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=De(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=De(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||go("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return y(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function va(t){Array.isArray(t)||N("candidates must be an array"),t.length>yo&&N(`candidates must contain at most ${yo} items`);let e=new Map;for(let[n,r]of t.entries()){let o=Aa(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function vt(t){let e=Nn(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 Sa(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&N("event payload must be a JSON object"),e}catch(e){throw new p("VALIDATION","event payload must be JSON serializable",e)}}function Rt(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 It(t,e){return !!t.select({id:b.id}).from(b).where(drizzleOrm.eq(b.thread_id,e)).limit(1).get()}function Je(t,e){ha.has(e.type)||N(`invalid thread event type: ${String(e.type)}`);let n=yt("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:Sa(e.payload),created_at:e.createdAt}).run();let r=t.select().from(b).where(drizzleOrm.eq(b.id,n)).get();if(!r)throw new p("DB_ERROR","Thread event insert did not return a row");return r}function At(t,e,n,r,o){let s=vt(e);Je(t,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function Vt(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 zt(t,e,n,r,o,s,i){let a=o==="thread.highlight.created"?Vt(e):{before:i?Vt({...e,...i,id:e.id}):void 0,after:Vt(e)};return Je(t,{threadId:e.thread_id,seq:s,type:o,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:a})}function xa(t,e,n,r,o,s){return Je(t,{threadId:e.thread_id,seq:o,type:"thread.highlight.deleted",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:Vt(e),...s??{}}})}var Kt=class extends te{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ee.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs.existsSync(n))throw new p("NOT_FOUND","Database not found");if(e){let o=Ee.dirname(n);fs.existsSync(o)||fs.mkdirSync(o,{recursive:true});}let r=P(n);if(e)try{pe(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=drizzleOrm.eq(f.id,n),s=r===void 0?o:r===null?drizzleOrm.and(o,drizzleOrm.isNull(f.workspace_id)):drizzleOrm.and(o,drizzleOrm.eq(f.workspace_id,r));return e.select().from(f).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(v).where(drizzleOrm.eq(v.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(y(e,"threadId"),!fs.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:f.workspace_id}).from(f).where(drizzleOrm.eq(f.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(y(e,"threadId"),!fs.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?vt(o):null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){wa(e);let n=Et(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||ue(`Thread ${e.threadId} not found`);let a=vt(i),l=e.title!==void 0,c=l&&e.title!==a.title,u=l&&i.title_locked!==1,g=e.priority!==void 0&&e.priority!==a.priority,h=e.state!==void 0&&e.state!==a.state,m=c||g||h;if(!m&&!u)return a;let S=i.metadata;(g||h)&&(S=mo(i.metadata,{priority:e.priority,state:e.state}));let I={};if(m&&(I.metadata=S,I.updated_at=r),c&&(I.title=e.title),l&&(I.title_locked=1),s.update(f).set(I).where(e.workspaceId===void 0?drizzleOrm.eq(f.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(f.id,e.threadId),drizzleOrm.isNull(f.workspace_id)):drizzleOrm.and(drizzleOrm.eq(f.id,e.threadId),drizzleOrm.eq(f.workspace_id,e.workspaceId))).run(),!m){let B={...i,title_locked:1};return vt(B)}let A=Rt(s,i.id)+1;It(s,i.id)||(At(s,i,n,r,A),A+=1),c&&(Je(s,{threadId:i.id,seq:A,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:a.title,after:e.title}}),A+=1),g&&(Je(s,{threadId:i.id,seq:A,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:a.priority,after:e.priority}}),A+=1),h&&Je(s,{threadId:i.id,seq:A,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:a.state,after:e.state}});let $={...i,title:c?e.title:i.title,metadata:S,title_locked:l?1:i.title_locked,updated_at:r};return vt($)},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(y(e,"threadId"),!fs.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(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(y(e,"threadId"),y(n,"workspaceId"),!fs.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:d.id,prompt:d.prompt,result:d.result,status:d.status,startedAt:d.started_at,completedAt:d.completed_at}).from(d).where(drizzleOrm.and(drizzleOrm.eq(d.thread_id,e),drizzleOrm.eq(d.workspace_id,n),drizzleOrm.inArray(d.status,ya),drizzleOrm.or(drizzleOrm.isNull(d.parent_task_id),drizzleOrm.eq(d.parent_task_id,"")),drizzleOrm.sql`${d.result} IS NOT NULL AND length(trim(${d.result})) > 0`)).orderBy(drizzleOrm.asc(d.started_at),drizzleOrm.asc(d.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){y(e.threadId,"threadId"),y(e.workspaceId,"workspaceId"),y(e.requestId,"requestId"),y(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&y(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findThread(o,e.threadId,e.workspaceId);s||ue(`Thread ${e.threadId} not found`);let i=o.select().from(v).where(drizzleOrm.and(drizzleOrm.eq(v.thread_id,s.id),drizzleOrm.eq(v.request_id,e.requestId))).orderBy(drizzleOrm.desc(v.requested_at),drizzleOrm.desc(v.id)).limit(1).get();if(i)return {run:i,created:!1};let a=o.select().from(v).where(drizzleOrm.and(drizzleOrm.eq(v.thread_id,s.id),drizzleOrm.inArray(v.status,Wt))).orderBy(drizzleOrm.asc(v.requested_at),drizzleOrm.asc(v.id)).limit(1).get();if(a)throw new Mn(a);let l=e.runId??yt("thr");o.insert(v).values({id:l,thread_id:s.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let c=o.select().from(v).where(drizzleOrm.eq(v.id,l)).get();if(!c)throw new p("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to create highlight regeneration run",o)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(y(e,"runId"),n!==void 0&&y(n,"workspaceId"),!fs.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(y(e,"threadId"),y(n,"workspaceId"),y(r,"requestId"),!fs.existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(v).where(drizzleOrm.and(drizzleOrm.eq(v.thread_id,e),drizzleOrm.eq(v.request_id,r))).orderBy(drizzleOrm.desc(v.requested_at),drizzleOrm.desc(v.id)).limit(1).get()??null:null}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to read highlight regeneration request",s)}finally{o.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){y(e,"runId"),n!==void 0&&y(n,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findRegenerationRun(s,e,n);if(i||ue(`Highlight regeneration run ${e} not found`),Ln(i.status)||N(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(v).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq(v.id,i.id),drizzleOrm.eq(v.status,"queued"))).run();let a=s.select().from(v).where(drizzleOrm.eq(v.id,i.id)).get();if(!a)throw new p("DB_ERROR","Highlight regeneration run start did not return a row");return a},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){y(e.runId,"runId"),y(e.errorCode,"errorCode"),e.workspaceId!==void 0&&y(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findRegenerationRun(o,e.runId,e.workspaceId);if(s||ue(`Highlight regeneration run ${e.runId} not found`),Ln(s.status)||N(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(v).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq(v.id,s.id),drizzleOrm.inArray(v.status,Wt))).run();let i=o.select().from(v).where(drizzleOrm.eq(v.id,s.id)).get();if(!i)throw new p("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=pa){y(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(v).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray(v.status,Wt)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){y(e.runId,"runId"),y(e.threadId,"threadId"),y(e.workspaceId,"workspaceId"),y(e.detectorVersion,"detectorVersion");let n=va(e.candidates),r=Et(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let a=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!a||a.thread_id!==e.threadId)&&ue(`Highlight regeneration run ${e.runId} not found`),Ln(a.status)||N(`invalid highlight regeneration status: ${a.status}`),a.status==="failed")throw new p("CONFLICT","Highlight regeneration run has already failed");if(a.status==="completed")return {run:a,deletedCount:0,createdCount:0,previousAutoCount:a.previous_auto_count??0,newAutoCount:a.new_auto_count??0};s=!0;let l=this.findThread(i,e.threadId,e.workspaceId);l||ue(`Thread ${e.threadId} not found`),a.detector_version!==e.detectorVersion&&N("detectorVersion does not match the regeneration run");let c=i.select().from(w).where(drizzleOrm.eq(w.thread_id,l.id)).orderBy(drizzleOrm.asc(w.created_at),drizzleOrm.asc(w.id)).all(),u=new Set(n.map(O=>O.contentFingerprint)),g=c.filter(O=>O.source==="auto"&&O.status==="active"&&O.revision===0&&!u.has(O.content_fingerprint??"")),h=c.filter(O=>O.source==="auto"&&O.status==="active").length,m=new Set(c.filter(O=>!g.includes(O)&&O.content_fingerprint).map(O=>O.content_fingerprint)),S=n.filter(O=>!m.has(O.contentFingerprint)),I=new Date().toISOString(),A=Rt(i,l.id)+1;It(i,l.id)||(At(i,l,r,I,A),A+=1);for(let O of g)i.delete(w).where(drizzleOrm.eq(w.id,O.id)).run(),xa(i,O,r,I,A,{runId:e.runId,reason:ua}),A+=1;let $=0,B=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let O of S){let Fn=yt("thl");i.insert(w).values({id:Fn,thread_id:l.id,source:"auto",kind:O.kind,status:"active",text:O.text,covers_from_task_id:O.coversFromTaskId,covers_to_task_id:O.coversToTaskId,revision:0,created_at:I,updated_at:I,agent_id:B,source_task_id:O.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:O.contentFingerprint,dismissed_at:null}).run();let qn=i.select().from(w).where(drizzleOrm.eq(w.id,Fn)).get();if(!qn)throw new p("DB_ERROR","Regenerated highlight insert did not return a row");zt(i,qn,r,I,"thread.highlight.created",A),A+=1,$+=1;}let ee=i.select().from(w).where(drizzleOrm.eq(w.thread_id,l.id)).all().filter(O=>O.source==="auto"&&O.status==="active").length;Je(i,{threadId:l.id,seq:A,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:I,payload:{runId:a.id,detectorVersion:e.detectorVersion,previousAutoCount:h,newAutoCount:ee,deletedCount:g.length,createdCount:$}}),i.update(v).set({status:"completed",started_at:a.started_at??I,completed_at:I,error_code:null,previous_auto_count:h,new_auto_count:ee}).where(drizzleOrm.and(drizzleOrm.eq(v.id,a.id),drizzleOrm.inArray(v.status,Wt))).run();let Le=i.select().from(v).where(drizzleOrm.eq(v.id,a.id)).get();if(!Le)throw new p("DB_ERROR","Highlight regeneration completion did not return a row");return {run:Le,deletedCount:g.length,createdCount:$,previousAutoCount:h,newAutoCount:ee}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:ga});}catch{}throw i instanceof p?i:new p("DB_ERROR","Failed to complete highlight regeneration",i)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;y(o.threadId,"threadId"),y(o.workspaceId,"workspaceId");let s=Ea(o);if(!fs.existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let a=i.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${b.seq}), 0)`}).from(b).where(drizzleOrm.eq(b.thread_id,o.threadId)).get()?.maxSeq??0,l;o.beforeSeq!==void 0?l=i.db.select().from(b).where(drizzleOrm.and(drizzleOrm.eq(b.thread_id,o.threadId),drizzleOrm.lt(b.seq,o.beforeSeq))).orderBy(drizzleOrm.desc(b.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?l=i.db.select().from(b).where(drizzleOrm.and(drizzleOrm.eq(b.thread_id,o.threadId),drizzleOrm.sql`${b.seq} > ${o.afterSeq}`)).orderBy(drizzleOrm.asc(b.seq)).limit(s+1).all():l=i.db.select().from(b).where(drizzleOrm.eq(b.thread_id,o.threadId)).orderBy(drizzleOrm.desc(b.seq)).limit(s+1).all().reverse();let c=l.length>s,u=o.afterSeq!==void 0?l.slice(0,s):c?l.slice(1):l,g=!1,h=u[0];return h&&(g=!!i.db.select({id:b.id}).from(b).where(drizzleOrm.and(drizzleOrm.eq(b.thread_id,o.threadId),drizzleOrm.lt(b.seq,h.seq))).limit(1).get()),{items:u,latestSeq:a,hasMoreOlder:g}}catch(a){throw a instanceof p?a:new p("DB_ERROR","Failed to list thread timeline",a)}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=Ia(e),r=Et(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let a=this.findThread(i,e.threadId,e.workspaceId);if(a||ue(`Thread ${e.threadId} not found`),n.source==="auto"){let h=i.select().from(w).where(drizzleOrm.and(drizzleOrm.eq(w.thread_id,e.threadId),drizzleOrm.eq(w.source_task_id,n.sourceTaskId),drizzleOrm.eq(w.detector_version,n.detectorVersion),drizzleOrm.eq(w.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc(w.created_at),drizzleOrm.asc(w.id)).limit(1).get();if(h)return h}let l=e.id??yt("thl"),c={id:l,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(w).values(c).run();let u=i.select().from(w).where(drizzleOrm.eq(w.id,l)).get();if(!u)throw new p("DB_ERROR","Highlight insert did not return a row");let g=Rt(i,a.id)+1;return It(i,a.id)||(At(i,a,r,o,g),g+=1),zt(i,u,r,o,"thread.highlight.created",g),u},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){y(e.threadId,"threadId"),y(e.workspaceId,"workspaceId"),y(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&N("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&N("highlight update requires at least one field"),e.kind!==void 0&&Hn(e.kind);let n=e.text===void 0?void 0:$n(e.text),r=Et(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let a=this.findThread(i,e.threadId,e.workspaceId);a||ue(`Thread ${e.threadId} not found`);let l=i.select().from(w).where(drizzleOrm.and(drizzleOrm.eq(w.id,e.highlightId),drizzleOrm.eq(w.thread_id,a.id))).limit(1).get();if(l||ue(`Highlight ${e.highlightId} not found`),l.revision!==e.expectedRevision)throw new St(a.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new St(a.id,l.id,e.expectedRevision,l.revision);let c=e.kind??l.kind,u=n??l.text,g=e.coversFromTaskId??l.covers_from_task_id,h=e.coversToTaskId??l.covers_to_task_id;(!u||g.length===0||h.length===0)&&N("highlight projection is incomplete");let m=c!==l.kind||u!==l.text||g!==l.covers_from_task_id||h!==l.covers_to_task_id,S=r.actorType==="user"&&l.source==="auto"&&m?"manual":l.source;if(!(m||S!==l.source))return l;let A=l.revision+1;i.update(w).set({source:S,kind:c,text:u,covers_from_task_id:g,covers_to_task_id:h,revision:A,updated_at:o}).where(drizzleOrm.and(drizzleOrm.eq(w.id,l.id),drizzleOrm.eq(w.revision,l.revision))).run();let $=i.select().from(w).where(drizzleOrm.eq(w.id,l.id)).get();if(!$)throw new p("DB_ERROR","Highlight update did not return a row");let B=Rt(i,a.id)+1;return It(i,a.id)||(At(i,a,r,o,B),B+=1),zt(i,$,r,o,"thread.highlight.updated",B,l),$},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){y(e.threadId,"threadId"),y(e.workspaceId,"workspaceId"),y(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&N("expectedRevision must be a non-negative integer");let n=Et(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||ue(`Thread ${e.threadId} not found`);let a=s.select().from(w).where(drizzleOrm.and(drizzleOrm.eq(w.id,e.highlightId),drizzleOrm.eq(w.thread_id,i.id))).limit(1).get();if(a||ue(`Highlight ${e.highlightId} not found`),a.revision!==e.expectedRevision)throw new St(i.id,a.id,e.expectedRevision,a.revision);if(a.status==="dismissed")return a;let l=a.revision+1;s.update(w).set({status:"dismissed",text:null,revision:l,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(w.id,a.id),drizzleOrm.eq(w.revision,a.revision))).run();let c=s.select().from(w).where(drizzleOrm.eq(w.id,a.id)).get();if(!c)throw new p("DB_ERROR","Highlight dismissal did not return a row");let u=Rt(s,i.id)+1;return It(s,i.id)||(At(s,i,n,r,u),u+=1),zt(s,c,n,r,"thread.highlight.deleted",u,a),c},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(y(e,"threadId"),y(n,"workspaceId"),r.taskId!==void 0&&y(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&y(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&y(r.coversToTaskId,"coversToTaskId"),!fs.existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,n))return null;let i=o.db.select().from(w).where(drizzleOrm.and(drizzleOrm.eq(w.thread_id,e),drizzleOrm.eq(w.status,"active"))).orderBy(drizzleOrm.asc(w.created_at),drizzleOrm.asc(w.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let a=o.db.all(drizzleOrm.sql`
|
|
374
|
+
`),c},{behavior:"immediate"})}}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(f).set({last_message:n,updated_at:s}).where(drizzleOrm.eq(f.id,e)).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};n.title!==void 0&&(o.title=n.title,o.title_locked=1),n.titleLocked!==void 0&&(o.title_locked=n.titleLocked?1:0),r.db.update(f).set(o).where(drizzleOrm.eq(f.id,e)).run();}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let o=n;if(!o||typeof o!="object"||Array.isArray(o))return new rt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new rt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new rt("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let l of [i.priority,i.state])if(l!=null&&(typeof l!="string"||l.length===0))return new rt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let a=this.openHandle(true);try{let l=r?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,r)):drizzleOrm.eq(f.id,e);return a.db.transaction(c=>{let u=c.select({metadata:f.metadata}).from(f).where(l).get();if(!u)return null;let g=yt(u.metadata),h=g.threadTitle,m=h&&typeof h=="object"&&!Array.isArray(h)?{...h}:{};i.priority===null?delete m.priority:i.priority!==void 0&&(m.priority=i.priority),i.state===null?delete m.state:i.state!==void 0&&(m.state=i.state),Object.keys(m).length>0?g.threadTitle=m:delete g.threadTitle;let S=Object.keys(g).length>0?JSON.stringify(g):null,I=new Date().toISOString();c.update(f).set({metadata:S,updated_at:I}).where(l).run();let v=c.select({metadata:f.metadata}).from(f).where(l).get();if(!v)throw new p("DB_ERROR","Thread-title metadata update could not be read back");let $=_a(v.metadata);return {threadId:e,priority:$.priority,state:$.state}},{behavior:"immediate"})}catch(l){throw l instanceof p?l:new p("DB_ERROR","Failed to patch thread-title metadata",l)}finally{a.close();}}togglePin(e,n){let r=this.openHandle(true);try{let o=n?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,n)):drizzleOrm.eq(f.id,e);return r.db.transaction(s=>{let i=s.select({pinned:f.pinned,metadata:f.metadata}).from(f).where(o).get();if(!i)return null;let a=i.pinned?0:1,l=yt(i.metadata);if(a){let c=n?drizzleOrm.and(drizzleOrm.eq(f.pinned,1),drizzleOrm.eq(f.workspace_id,n)):drizzleOrm.eq(f.pinned,1),u=s.select({metadata:f.metadata}).from(f).where(c).all(),g=null;for(let h of u){let m=yt(h.metadata);typeof m.pinOrder=="number"&&(g===null||m.pinOrder<g)&&(g=m.pinOrder);}l.pinOrder=g===null?0:g-1;}else delete l.pinOrder;return s.update(f).set({pinned:a,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(o).run(),{pinned:!!a}},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>{for(let s=0;s<e.length;s++){let i=n?drizzleOrm.and(drizzleOrm.eq(f.id,e[s]),drizzleOrm.eq(f.workspace_id,n)):drizzleOrm.eq(f.id,e[s]),a=o.select({metadata:f.metadata}).from(f).where(i).get();if(!a)continue;let l=yt(a.metadata);l.pinOrder=s+1,o.update(f).set({metadata:JSON.stringify(l)}).where(i).run();}},{behavior:"immediate"});}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,n)):drizzleOrm.eq(f.id,e),s=r.db.select({starred:f.starred}).from(f).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(f).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let i=this.openHandle(true);try{let a=n?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,n)):drizzleOrm.eq(f.id,e);return i.db.transaction(c=>{let u=c.select({metadata:f.metadata}).from(f).where(a).get();if(!u)return null;let g=u.metadata?JSON.parse(u.metadata):{},h=g.overdrive??{},m=o?.defaultTurns??h.defaultTurns??3,S=o?.updatedBy??"ui",I=new Date().toISOString(),v,$,B,ae;switch(r){case "enable-count":{let ee=o?.turns??m,Le=o?.consumeCurrent?Math.max(ee-1,0):ee;v=Le>0?"count":"off",$=Le,B=!0,ae="count";break}case "enable-latch":{v="latch",$=0,B=!0,ae="latch";break}case "disable":{v="off",$=0,B=!1;break}default:{let ee=h.state??"off",Le=typeof h.remaining=="number"?h.remaining:0;if(ee==="count"&&Le>0){let O=Le-1;O<=0?(v="off",$=0):(v="count",$=O),B=!0,ae="count";}else ee==="latch"?(v="latch",$=0,B=!0,ae="latch"):(v="off",$=0,B=!1);break}}return g.overdrive={state:v,remaining:$,defaultTurns:m,updatedAt:I,updatedBy:S},c.update(f).set({metadata:JSON.stringify(g),updated_at:I}).where(a).run(),{applied:B,appliedMode:ae,state:v,remaining:$}},{behavior:"immediate"})}catch(a){throw a instanceof p?a:new p("DB_ERROR","Failed to resolve overdrive",a)}finally{i.close();}}};var bn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ka(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let o=e[r];o<248&&(n+=bn[o%62]);}for(;n.length<t;)n+=bn[crypto.randomBytes(1)[0]%62];return n}function wt(t){return `${t}_${ka(8)}`}function yo(t,e){let{createHash:n}=lt("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=r[i];let s="";for(let i of o)s+=bn[i%62];return `${t}_${s}`}var Ta=["urgent","high","medium","low"],ya=["investigating","in-progress","in-review","on-hold","done"],wo="custom:";var wa=new Set(Ta),Ea=new Set(ya);function Nn(t){return typeof t=="string"&&wa.has(t)}function Dn(t){if(typeof t!="string")return false;if(Ea.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(wo))return false;let e=t.slice(wo.length);return e.length>=1&&e.length<=20}function Eo(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 Pn(t){let e=Eo(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return Nn(r.priority)&&(o.priority=r.priority),Dn(r.state)&&(o.state=r.state),o}function Ro(t,e){let n=Eo(t)??{},r={...Pn(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)}var Sa="regeneration_replaced";var xa="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Oa="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",$n=class extends p{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=o;}},xt=class extends $n{},Hn=class extends p{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},Ca=new Set(ur),ba=new Set(cr),Na=new Set(pr),Da=new Set(gr),Pa=50,vo=100,Ao=280,So=40,La=new Set(fr),Vt=["queued","running"],Ma=["success","completed","done","failed","error"];function Mn(t){return La.has(t)}function N(t){throw new p("VALIDATION",t)}function pe(t){throw new p("NOT_FOUND",t)}function y(t,e){(typeof t!="string"||t.trim().length===0)&&N(`${e} is required`);}function Rt(t={}){let e=t.actor??t,n=e.actorType??"system";return Ca.has(n)||N(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&N("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function $a(t){y(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&y(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&N("title must not be empty"),t.title.length>120&&N("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!Nn(t.priority)&&N(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Dn(t.state)&&N(`invalid state: ${String(t.state)}`);}function Ha(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&N("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)&&N(`${n} must be a non-negative integer`);let e=t.limit??Pa;return (!Number.isInteger(e)||e<1||e>vo)&&N(`limit must be between 1 and ${vo}`),e}function Un(t){typeof t!="string"&&N("text is required");let e=t.trim();return e.length===0&&N("text must not be empty"),e.length>Ao&&N(`text must be at most ${Ao} characters`),e}function Pe(t,e){return y(t??"",e),t}function Fn(t){Da.has(t)||N(`invalid highlight kind: ${String(t)}`);}function Ua(t){Na.has(t)||N(`invalid highlight source: ${String(t)}`);}function Fa(t){y(t.threadId,"threadId"),y(t.workspaceId,"workspaceId");let e=t.source??"manual";Ua(e),Fn(t.kind);let n=Un(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let u=t.taskId??(r&&o&&r===o?r:void 0),g=Pe(u,"taskId");return (r!==g||o!==g)&&N("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:g,coversToTaskId:g,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=Pe(r,"coversFromTaskId"),i=Pe(o,"coversToTaskId"),a=t.sourceTaskId??s,l=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return Pe(a??void 0,"sourceTaskId"),Pe(l??void 0,"detectorVersion"),Pe(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:a,detectorVersion:l,contentFingerprint:c}}function qa(t,e){(!t||typeof t!="object")&&N(`candidates[${e}] is required`),Fn(t.kind);let n=Un(t.text),r=Pe(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Pe(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Pe(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||yo("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return y(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function Ba(t){Array.isArray(t)||N("candidates must be an array"),t.length>So&&N(`candidates must contain at most ${So} items`);let e=new Map;for(let[n,r]of t.entries()){let o=qa(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function St(t){let e=Pn(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 ja(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&N("event payload must be a JSON object"),e}catch(e){throw new p("VALIDATION","event payload must be JSON serializable",e)}}function It(t,e){return t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${C.seq}), 0)`}).from(C).where(drizzleOrm.eq(C.thread_id,e)).get()?.maxSeq??0}function vt(t,e){return !!t.select({id:C.id}).from(C).where(drizzleOrm.eq(C.thread_id,e)).limit(1).get()}function Ye(t,e){ba.has(e.type)||N(`invalid thread event type: ${String(e.type)}`);let n=wt("the");t.insert(C).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:ja(e.payload),created_at:e.createdAt}).run();let r=t.select().from(C).where(drizzleOrm.eq(C.id,n)).get();if(!r)throw new p("DB_ERROR","Thread event insert did not return a row");return r}function At(t,e,n,r,o){let s=St(e);Ye(t,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function Kt(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 Jt(t,e,n,r,o,s,i){let a=o==="thread.highlight.created"?Kt(e):{before:i?Kt({...e,...i,id:e.id}):void 0,after:Kt(e)};return Ye(t,{threadId:e.thread_id,seq:s,type:o,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:a})}function Ga(t,e,n,r,o,s){return Ye(t,{threadId:e.thread_id,seq:o,type:"thread.highlight.deleted",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:Kt(e),...s??{}}})}var Yt=class extends te{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs.existsSync(n))throw new p("NOT_FOUND","Database not found");if(e){let o=Re.dirname(n);fs.existsSync(o)||fs.mkdirSync(o,{recursive:true});}let r=L(n);if(e)try{ge(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=drizzleOrm.eq(f.id,n),s=r===void 0?o:r===null?drizzleOrm.and(o,drizzleOrm.isNull(f.workspace_id)):drizzleOrm.and(o,drizzleOrm.eq(f.workspace_id,r));return e.select().from(f).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(A).where(drizzleOrm.eq(A.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(y(e,"threadId"),!fs.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:f.workspace_id}).from(f).where(drizzleOrm.eq(f.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(y(e,"threadId"),!fs.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?St(o):null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){$a(e);let n=Rt(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||pe(`Thread ${e.threadId} not found`);let a=St(i),l=e.title!==void 0,c=l&&e.title!==a.title,u=l&&i.title_locked!==1,g=e.priority!==void 0&&e.priority!==a.priority,h=e.state!==void 0&&e.state!==a.state,m=c||g||h;if(!m&&!u)return a;let S=i.metadata;(g||h)&&(S=Ro(i.metadata,{priority:e.priority,state:e.state}));let I={};if(m&&(I.metadata=S,I.updated_at=r),c&&(I.title=e.title),l&&(I.title_locked=1),s.update(f).set(I).where(e.workspaceId===void 0?drizzleOrm.eq(f.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(f.id,e.threadId),drizzleOrm.isNull(f.workspace_id)):drizzleOrm.and(drizzleOrm.eq(f.id,e.threadId),drizzleOrm.eq(f.workspace_id,e.workspaceId))).run(),!m){let B={...i,title_locked:1};return St(B)}let v=It(s,i.id)+1;vt(s,i.id)||(At(s,i,n,r,v),v+=1),c&&(Ye(s,{threadId:i.id,seq:v,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:a.title,after:e.title}}),v+=1),g&&(Ye(s,{threadId:i.id,seq:v,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:a.priority,after:e.priority}}),v+=1),h&&Ye(s,{threadId:i.id,seq:v,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:a.state,after:e.state}});let $={...i,title:c?e.title:i.title,metadata:S,title_locked:l?1:i.title_locked,updated_at:r};return St($)},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(y(e,"threadId"),!fs.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(${C.seq}), 0)`}).from(C).where(drizzleOrm.eq(C.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(y(e,"threadId"),y(n,"workspaceId"),!fs.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:d.id,prompt:d.prompt,result:d.result,status:d.status,startedAt:d.started_at,completedAt:d.completed_at}).from(d).where(drizzleOrm.and(drizzleOrm.eq(d.thread_id,e),drizzleOrm.eq(d.workspace_id,n),drizzleOrm.inArray(d.status,Ma),drizzleOrm.or(drizzleOrm.isNull(d.parent_task_id),drizzleOrm.eq(d.parent_task_id,"")),drizzleOrm.sql`${d.result} IS NOT NULL AND length(trim(${d.result})) > 0`)).orderBy(drizzleOrm.asc(d.started_at),drizzleOrm.asc(d.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){y(e.threadId,"threadId"),y(e.workspaceId,"workspaceId"),y(e.requestId,"requestId"),y(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&y(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findThread(o,e.threadId,e.workspaceId);s||pe(`Thread ${e.threadId} not found`);let i=o.select().from(A).where(drizzleOrm.and(drizzleOrm.eq(A.thread_id,s.id),drizzleOrm.eq(A.request_id,e.requestId))).orderBy(drizzleOrm.desc(A.requested_at),drizzleOrm.desc(A.id)).limit(1).get();if(i)return {run:i,created:!1};let a=o.select().from(A).where(drizzleOrm.and(drizzleOrm.eq(A.thread_id,s.id),drizzleOrm.inArray(A.status,Vt))).orderBy(drizzleOrm.asc(A.requested_at),drizzleOrm.asc(A.id)).limit(1).get();if(a)throw new Hn(a);let l=e.runId??wt("thr");o.insert(A).values({id:l,thread_id:s.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let c=o.select().from(A).where(drizzleOrm.eq(A.id,l)).get();if(!c)throw new p("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to create highlight regeneration run",o)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(y(e,"runId"),n!==void 0&&y(n,"workspaceId"),!fs.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(y(e,"threadId"),y(n,"workspaceId"),y(r,"requestId"),!fs.existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(A).where(drizzleOrm.and(drizzleOrm.eq(A.thread_id,e),drizzleOrm.eq(A.request_id,r))).orderBy(drizzleOrm.desc(A.requested_at),drizzleOrm.desc(A.id)).limit(1).get()??null:null}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to read highlight regeneration request",s)}finally{o.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){y(e,"runId"),n!==void 0&&y(n,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findRegenerationRun(s,e,n);if(i||pe(`Highlight regeneration run ${e} not found`),Mn(i.status)||N(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(A).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq(A.id,i.id),drizzleOrm.eq(A.status,"queued"))).run();let a=s.select().from(A).where(drizzleOrm.eq(A.id,i.id)).get();if(!a)throw new p("DB_ERROR","Highlight regeneration run start did not return a row");return a},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){y(e.runId,"runId"),y(e.errorCode,"errorCode"),e.workspaceId!==void 0&&y(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findRegenerationRun(o,e.runId,e.workspaceId);if(s||pe(`Highlight regeneration run ${e.runId} not found`),Mn(s.status)||N(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(A).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq(A.id,s.id),drizzleOrm.inArray(A.status,Vt))).run();let i=o.select().from(A).where(drizzleOrm.eq(A.id,s.id)).get();if(!i)throw new p("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=xa){y(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(A).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray(A.status,Vt)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){y(e.runId,"runId"),y(e.threadId,"threadId"),y(e.workspaceId,"workspaceId"),y(e.detectorVersion,"detectorVersion");let n=Ba(e.candidates),r=Rt(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let a=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!a||a.thread_id!==e.threadId)&&pe(`Highlight regeneration run ${e.runId} not found`),Mn(a.status)||N(`invalid highlight regeneration status: ${a.status}`),a.status==="failed")throw new p("CONFLICT","Highlight regeneration run has already failed");if(a.status==="completed")return {run:a,deletedCount:0,createdCount:0,previousAutoCount:a.previous_auto_count??0,newAutoCount:a.new_auto_count??0};s=!0;let l=this.findThread(i,e.threadId,e.workspaceId);l||pe(`Thread ${e.threadId} not found`),a.detector_version!==e.detectorVersion&&N("detectorVersion does not match the regeneration run");let c=i.select().from(w).where(drizzleOrm.eq(w.thread_id,l.id)).orderBy(drizzleOrm.asc(w.created_at),drizzleOrm.asc(w.id)).all(),u=new Set(n.map(O=>O.contentFingerprint)),g=c.filter(O=>O.source==="auto"&&O.status==="active"&&O.revision===0&&!u.has(O.content_fingerprint??"")),h=c.filter(O=>O.source==="auto"&&O.status==="active").length,m=new Set(c.filter(O=>!g.includes(O)&&O.content_fingerprint).map(O=>O.content_fingerprint)),S=n.filter(O=>!m.has(O.contentFingerprint)),I=new Date().toISOString(),v=It(i,l.id)+1;vt(i,l.id)||(At(i,l,r,I,v),v+=1);for(let O of g)i.delete(w).where(drizzleOrm.eq(w.id,O.id)).run(),Ga(i,O,r,I,v,{runId:e.runId,reason:Sa}),v+=1;let $=0,B=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let O of S){let Bn=wt("thl");i.insert(w).values({id:Bn,thread_id:l.id,source:"auto",kind:O.kind,status:"active",text:O.text,covers_from_task_id:O.coversFromTaskId,covers_to_task_id:O.coversToTaskId,revision:0,created_at:I,updated_at:I,agent_id:B,source_task_id:O.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:O.contentFingerprint,dismissed_at:null}).run();let jn=i.select().from(w).where(drizzleOrm.eq(w.id,Bn)).get();if(!jn)throw new p("DB_ERROR","Regenerated highlight insert did not return a row");Jt(i,jn,r,I,"thread.highlight.created",v),v+=1,$+=1;}let ee=i.select().from(w).where(drizzleOrm.eq(w.thread_id,l.id)).all().filter(O=>O.source==="auto"&&O.status==="active").length;Ye(i,{threadId:l.id,seq:v,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:I,payload:{runId:a.id,detectorVersion:e.detectorVersion,previousAutoCount:h,newAutoCount:ee,deletedCount:g.length,createdCount:$}}),i.update(A).set({status:"completed",started_at:a.started_at??I,completed_at:I,error_code:null,previous_auto_count:h,new_auto_count:ee}).where(drizzleOrm.and(drizzleOrm.eq(A.id,a.id),drizzleOrm.inArray(A.status,Vt))).run();let Le=i.select().from(A).where(drizzleOrm.eq(A.id,a.id)).get();if(!Le)throw new p("DB_ERROR","Highlight regeneration completion did not return a row");return {run:Le,deletedCount:g.length,createdCount:$,previousAutoCount:h,newAutoCount:ee}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Oa});}catch{}throw i instanceof p?i:new p("DB_ERROR","Failed to complete highlight regeneration",i)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;y(o.threadId,"threadId"),y(o.workspaceId,"workspaceId");let s=Ha(o);if(!fs.existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let a=i.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${C.seq}), 0)`}).from(C).where(drizzleOrm.eq(C.thread_id,o.threadId)).get()?.maxSeq??0,l;o.beforeSeq!==void 0?l=i.db.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.thread_id,o.threadId),drizzleOrm.lt(C.seq,o.beforeSeq))).orderBy(drizzleOrm.desc(C.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?l=i.db.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.thread_id,o.threadId),drizzleOrm.sql`${C.seq} > ${o.afterSeq}`)).orderBy(drizzleOrm.asc(C.seq)).limit(s+1).all():l=i.db.select().from(C).where(drizzleOrm.eq(C.thread_id,o.threadId)).orderBy(drizzleOrm.desc(C.seq)).limit(s+1).all().reverse();let c=l.length>s,u=o.afterSeq!==void 0?l.slice(0,s):c?l.slice(1):l,g=!1,h=u[0];return h&&(g=!!i.db.select({id:C.id}).from(C).where(drizzleOrm.and(drizzleOrm.eq(C.thread_id,o.threadId),drizzleOrm.lt(C.seq,h.seq))).limit(1).get()),{items:u,latestSeq:a,hasMoreOlder:g}}catch(a){throw a instanceof p?a:new p("DB_ERROR","Failed to list thread timeline",a)}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=Fa(e),r=Rt(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let a=this.findThread(i,e.threadId,e.workspaceId);if(a||pe(`Thread ${e.threadId} not found`),n.source==="auto"){let h=i.select().from(w).where(drizzleOrm.and(drizzleOrm.eq(w.thread_id,e.threadId),drizzleOrm.eq(w.source_task_id,n.sourceTaskId),drizzleOrm.eq(w.detector_version,n.detectorVersion),drizzleOrm.eq(w.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc(w.created_at),drizzleOrm.asc(w.id)).limit(1).get();if(h)return h}let l=e.id??wt("thl"),c={id:l,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(w).values(c).run();let u=i.select().from(w).where(drizzleOrm.eq(w.id,l)).get();if(!u)throw new p("DB_ERROR","Highlight insert did not return a row");let g=It(i,a.id)+1;return vt(i,a.id)||(At(i,a,r,o,g),g+=1),Jt(i,u,r,o,"thread.highlight.created",g),u},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){y(e.threadId,"threadId"),y(e.workspaceId,"workspaceId"),y(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&N("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&N("highlight update requires at least one field"),e.kind!==void 0&&Fn(e.kind);let n=e.text===void 0?void 0:Un(e.text),r=Rt(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let a=this.findThread(i,e.threadId,e.workspaceId);a||pe(`Thread ${e.threadId} not found`);let l=i.select().from(w).where(drizzleOrm.and(drizzleOrm.eq(w.id,e.highlightId),drizzleOrm.eq(w.thread_id,a.id))).limit(1).get();if(l||pe(`Highlight ${e.highlightId} not found`),l.revision!==e.expectedRevision)throw new xt(a.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new xt(a.id,l.id,e.expectedRevision,l.revision);let c=e.kind??l.kind,u=n??l.text,g=e.coversFromTaskId??l.covers_from_task_id,h=e.coversToTaskId??l.covers_to_task_id;(!u||g.length===0||h.length===0)&&N("highlight projection is incomplete");let m=c!==l.kind||u!==l.text||g!==l.covers_from_task_id||h!==l.covers_to_task_id,S=r.actorType==="user"&&l.source==="auto"&&m?"manual":l.source;if(!(m||S!==l.source))return l;let v=l.revision+1;i.update(w).set({source:S,kind:c,text:u,covers_from_task_id:g,covers_to_task_id:h,revision:v,updated_at:o}).where(drizzleOrm.and(drizzleOrm.eq(w.id,l.id),drizzleOrm.eq(w.revision,l.revision))).run();let $=i.select().from(w).where(drizzleOrm.eq(w.id,l.id)).get();if(!$)throw new p("DB_ERROR","Highlight update did not return a row");let B=It(i,a.id)+1;return vt(i,a.id)||(At(i,a,r,o,B),B+=1),Jt(i,$,r,o,"thread.highlight.updated",B,l),$},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){y(e.threadId,"threadId"),y(e.workspaceId,"workspaceId"),y(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&N("expectedRevision must be a non-negative integer");let n=Rt(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||pe(`Thread ${e.threadId} not found`);let a=s.select().from(w).where(drizzleOrm.and(drizzleOrm.eq(w.id,e.highlightId),drizzleOrm.eq(w.thread_id,i.id))).limit(1).get();if(a||pe(`Highlight ${e.highlightId} not found`),a.revision!==e.expectedRevision)throw new xt(i.id,a.id,e.expectedRevision,a.revision);if(a.status==="dismissed")return a;let l=a.revision+1;s.update(w).set({status:"dismissed",text:null,revision:l,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(w.id,a.id),drizzleOrm.eq(w.revision,a.revision))).run();let c=s.select().from(w).where(drizzleOrm.eq(w.id,a.id)).get();if(!c)throw new p("DB_ERROR","Highlight dismissal did not return a row");let u=It(s,i.id)+1;return vt(s,i.id)||(At(s,i,n,r,u),u+=1),Jt(s,c,n,r,"thread.highlight.deleted",u,a),c},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(y(e,"threadId"),y(n,"workspaceId"),r.taskId!==void 0&&y(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&y(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&y(r.coversToTaskId,"coversToTaskId"),!fs.existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,n))return null;let i=o.db.select().from(w).where(drizzleOrm.and(drizzleOrm.eq(w.thread_id,e),drizzleOrm.eq(w.status,"active"))).orderBy(drizzleOrm.asc(w.created_at),drizzleOrm.asc(w.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let a=o.db.all(drizzleOrm.sql`
|
|
374
375
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
375
376
|
ORDER BY started_at ASC, id ASC
|
|
376
|
-
`),l=new Map(a.map((h,m)=>[h.id,m])),c=r.taskId===void 0?void 0:l.get(r.taskId),u=r.coversFromTaskId===void 0?void 0:l.get(r.coversFromTaskId),g=r.coversToTaskId===void 0?void 0:l.get(r.coversToTaskId);return i.filter(h=>{let m=l.get(h.covers_from_task_id),S=l.get(h.covers_to_task_id);if(m===void 0||S===void 0)return !1;let I=Math.min(m,S),
|
|
377
|
+
`),l=new Map(a.map((h,m)=>[h.id,m])),c=r.taskId===void 0?void 0:l.get(r.taskId),u=r.coversFromTaskId===void 0?void 0:l.get(r.coversFromTaskId),g=r.coversToTaskId===void 0?void 0:l.get(r.coversToTaskId);return i.filter(h=>{let m=l.get(h.covers_from_task_id),S=l.get(h.covers_to_task_id);if(m===void 0||S===void 0)return !1;let I=Math.min(m,S),v=Math.max(m,S);return !(c!==void 0&&(c<I||c>v)||u!==void 0&&v<u||g!==void 0&&I>g)})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};var U=class extends p{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Oo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Za(){let t=crypto.randomBytes(16),e="";for(let n of t)e+=Oo[n%Oo.length];return e.slice(0,12)}function Co(){return `c_${Za()}`}function ed(t){return typeof t=="string"&&un.includes(t)}function td(t){return typeof t=="string"&&pn.includes(t)}function at(t){if(!ed(t))throw new U("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function bo(t){if(!td(t))throw new U("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function No(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new U("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function dt(t){if(typeof t!="string"||t.trim().length===0)throw new U("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Xt(t){if(typeof t!="string"||t.trim().length===0)throw new U("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function Ge(t,e){return drizzleOrm.and(drizzleOrm.eq(_.code_group,t),drizzleOrm.or(drizzleOrm.isNull(_.workspace_id),drizzleOrm.eq(_.workspace_id,e)))}var Qt=class extends te{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs.existsSync(n))throw new p("NOT_FOUND","Database not found");e&&fs.mkdirSync(Re.dirname(n),{recursive:true});let r=L(n);if(e)try{ge(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(at(e),dt(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(_).where(drizzleOrm.and(Ge(e,n),drizzleOrm.eq(_.is_archived,0))).orderBy(drizzleOrm.asc(_.sort_order),drizzleOrm.asc(_.code)).all()}catch(o){throw new p("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(at(e),dt(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(_).where(Ge(e,n)).orderBy(drizzleOrm.asc(_.sort_order),drizzleOrm.asc(_.code)).all()}catch(o){throw new p("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(at(n),dt(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)Xt(o);if(new Set(e.codes).size!==e.codes.length)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(_).where(Ge(n,e.workspaceId)).all(),i=s.filter(m=>m.is_archived===0),a=new Set(s.map(m=>m.code)),l=new Set(i.map(m=>m.code)),c=e.codes.find(m=>!a.has(m));if(c)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${c}`);if(e.codes.length!==i.length||e.codes.some(m=>!l.has(m)))throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let u=new Map(i.map(m=>[m.code,m])),g=e.codes.map(m=>{let S=u.get(m);if(!S)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${m}`);return S}),h;for(let[m,S]of g.entries())S.sort_order!==m&&(h??=new Date().toISOString(),o.update(_).set({sort_order:m,updated_at:h}).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,n),drizzleOrm.eq(_.code,S.code))).run());return o.select().from(_).where(Ge(n,e.workspaceId)).orderBy(drizzleOrm.asc(_.sort_order),drizzleOrm.asc(_.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(at(e),Xt(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).limit(1).get()??null}catch(o){throw new p("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){dt(e.workspaceId);let n=No(e.name);bo(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:_.code}).from(_).where(drizzleOrm.and(Ge("THREAD_STATE",e.workspaceId),drizzleOrm.eq(_.is_archived,0),drizzleOrm.eq(_.code_name,n))).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=o.select({maxSortOrder:drizzleOrm.sql`max(${_.sort_order})`}).from(_).where(Ge("THREAD_STATE",e.workspaceId)).get(),a=new Date().toISOString(),l=Co();for(;o.select({code:_.code}).from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,"THREAD_STATE"),drizzleOrm.eq(_.code,l))).limit(1).get();)l=Co();o.insert(_).values({code_group:"THREAD_STATE",code:l,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:a,updated_at:a}).run();let c=o.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,"THREAD_STATE"),drizzleOrm.eq(_.code,l))).limit(1).get();if(!c)throw new p("DB_ERROR","Created common code could not be read back");return c},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(at(e.group),Xt(e.code),dt(e.workspaceId),e.name===void 0&&e.color===void 0)throw new U("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:No(e.name);e.color!==void 0&&bo(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e.group),drizzleOrm.eq(_.code,e.code))).limit(1).get();if(!s)throw new U("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(s,e.workspaceId),n===null&&s.is_builtin!==1)throw new U("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let l=drizzleOrm.and(Ge(e.group,e.workspaceId),drizzleOrm.eq(_.is_archived,0));if(o.select({code:_.code}).from(_).where(drizzleOrm.and(l,drizzleOrm.eq(_.code_name,n),drizzleOrm.sql`${_.code} <> ${e.code}`)).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`)}let i={updated_at:new Date().toISOString()};e.name!==void 0&&(i.code_name=n??null),e.color!==void 0&&(i.color=e.color),o.update(_).set(i).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e.group),drizzleOrm.eq(_.code,e.code))).run();let a=o.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e.group),drizzleOrm.eq(_.code,e.code))).limit(1).get();if(!a)throw new p("DB_ERROR","Updated common code could not be read back");return a},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(at(e),Xt(n),dt(r),typeof o!="boolean")throw new U("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let a=i.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).limit(1).get();if(!a)throw new U("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(a.is_builtin===1)throw new U("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(a,r),!o&&a.code_name!==null&&i.select({code:_.code}).from(_).where(drizzleOrm.and(Ge(e,r),drizzleOrm.eq(_.is_archived,0),drizzleOrm.eq(_.code_name,a.code_name),drizzleOrm.ne(_.code,n))).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${a.code_name}`);i.update(_).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).run();let l=i.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).limit(1).get();if(!l)throw new p("DB_ERROR","Archived common code could not be read back");return l},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to archive common code",i)}finally{s.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new U("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function od(t){return t.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
377
378
|
`).filter(o=>!(o.startsWith("Loaded ")&&o.includes("layouts from")||o.includes("[dotenv@")||o.includes("[Nest]")&&o.includes("DEBUG")||o.startsWith("Registered custom layout:")||o.startsWith("Updated custom layout:"))).join(`
|
|
378
|
-
`).trim()}function
|
|
379
|
-
`):
|
|
380
|
-
`)[0].slice(0,200)),n.push({id:`${r.id}-assistant`,text:
|
|
379
|
+
`).trim()}function sd(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 id(t,e,n){if(!t||e==="failed"&&Wt(t,n))return "";let r=t;try{let o=JSON.parse(r);Array.isArray(o)?r=o.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
|
|
380
|
+
`):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=od(r);}return r}var Zt=class{dbPath;constructor(e){this.dbPath=e??Re.join(Fo.homedir(),".crewx","crewx.db");}getThreadRepo(){return new zt({dbPath:this.dbPath})}getThreadHistoryRepo(){return new Yt({dbPath:this.dbPath})}updateThread(e,n){this.getThreadRepo().updateThread(e,{title:n.title});}async ensureThread(e,n,r){let o=this.getThreadRepo(),s=o.findThreadById(e);if(s){if(s.platform!==n)throw new Error(`Thread '${e}' already exists with platform '${s.platform}' \u2014 cannot change to '${n}' (platform is immutable)`);return {created:false}}return o.ensureThread(e,n,r),{created:true}}async fetchHistory(e,n){let r=n?.limit??100,o=this.getThreadRepo(),s=o.findThreadById(e),i=o.findTopLevelTasks(e,void 0,r),a=new Set(["queued","cancelled"]);i=i.filter(g=>(!g.status||!a.has(g.status))&&(!n?.currentTraceId||g.trace_id!==n.currentTraceId));let l=s?.platform??"cli",c=this.rowsToMessages(i),u=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,s?.workspace_id??null);return {threadId:e,platform:l,messages:c,...u?{highlights:u}:{},metadata:{title:s?.title??void 0,firstMessage:s?.first_message??void 0,lastMessage:s?.last_message??void 0,messageCount:s?.message_count??0,updatedAt:s?.updated_at?new Date(s.updated_at).getTime():void 0}}}async fetchThreadState(e){try{let n=this.getThreadHistoryRepo().getSnapshot(e);if(!n)return;let r=new Qt({dbPath:this.dbPath}),o=(s,i)=>{try{return r.resolve(s,i)?.code_name||i}catch{return i}};return {...n.title?{title:n.title}:{},...n.priority?{priority:{code:n.priority,name:o("THREAD_PRIORITY",n.priority)}}:{},...n.state?{state:{code:n.state,name:o("THREAD_STATE",n.state)}}:{}}}catch{return}}async fetchHighlights(e){let n=this.getThreadRepo().findThreadById(e);return this.readActiveHighlights(e,n?.workspace_id??null)}async saveUserMessage(e,n,r,o){let{firstMessage:s}=this.getThreadRepo().saveUserMessage(e,n);return {id:e,firstMessage:s}}async saveAssistantMessage(e,n,r,o){return this.getThreadRepo().saveAssistantMessage(e,n),{id:e}}close(){}normalizeStatus(e){if(e&&!["success","completed","done"].includes(e)){if(["failed","error"].includes(e))return "failed";if(e==="running")return "running"}}readActiveHighlights(e,n){if(!n)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,n)??[]).filter(o=>typeof o.text=="string"&&o.text.length>0).map(o=>({id:o.id,text:o.text,kind:o.kind,source:o.source,coversFromTaskId:o.covers_from_task_id,coversToTaskId:o.covers_to_task_id,createdAt:o.created_at}))}catch{return}}rowsToMessages(e){let n=[];for(let r of e){r.prompt&&n.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let o=this.normalizeStatus(r.status),s=sd(r.metadata),i=id(r.result,o??r.status??null,s);if(i||o==="running"||o==="failed"){let a={agent_id:r.agent_id,task_id:r.id};o&&(a.status=o),o==="failed"&&r.error&&(a.reason=r.error.split(`
|
|
381
|
+
`)[0].slice(0,200)),n.push({id:`${r.id}-assistant`,text:i,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:a});}}return n}};var qn=class extends Me{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new Zt(e?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(e,n,r,o){}async afterAssistantMessage(e,n,r){}attach(e){this.unsubStart=e.on("task:start",async n=>{if(!n.threadId)return;let r=n.platform??"cli";try{let o=await this._provider.ensureThread(n.threadId,r,n.workspaceId),s=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,s.id,o.created||s.firstMessage,n);}catch{}}),this.unsubEnd=e.on("task:end",async n=>{if(!n.result)return;let r=n.metadata?.threadId;if(!r)return;let o=n.agentRef?.replace(/^@/,"")??"";try{let{id:s}=await this._provider.saveAssistantMessage(r,n.result,o);await this.afterAssistantMessage(r,s,n);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};exports.ConversationPlugin=qn;exports.FileLoggerPlugin=tn;exports.SqliteTracingPlugin=Cn;
|