@crewx/sdk 0.9.0-rc.61 → 0.9.0-rc.63
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 +92 -92
- package/dist/esm/plugins/index.js +37 -37
- package/dist/esm/repository/index.js +85 -85
- package/dist/events/types.d.ts +1 -0
- package/dist/index.browser.js +2 -2
- package/dist/index.js +93 -93
- package/dist/migrations/0015_panoramic_gorilla_man.sql +71 -0
- package/dist/migrations/meta/0015_snapshot.json +2315 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/dist/plugins/index.js +34 -34
- package/dist/repository/index.d.ts +2 -0
- package/dist/repository/index.js +85 -85
- package/dist/repository/project.repository.d.ts +88 -0
- package/dist/repository/task.repository.d.ts +2 -0
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/projects.d.ts +610 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/utils/id.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as mt from'path';import mt__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import Xe,{existsSync,mkdirSync,readFileSync}from'fs';import On from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,asc,gt,lt,or,notLike,like,inArray,gte,lte}from'drizzle-orm';import {randomUUID,createHash,randomBytes}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,primaryKey,check,getTableConfig}from'drizzle-orm/sqlite-core';var Gt=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var vn=()=>fileURLToPath(import.meta.url),An=()=>mt__default.dirname(vn()),y=An();var D=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(On.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function w(i){let t=Gt("better-sqlite3"),{drizzle:e}=Gt("drizzle-orm/better-sqlite3"),n=new t(i);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),n.exec("PRAGMA analysis_limit = 400"),n.exec("PRAGMA optimize"),{db:e(n),runRaw:(r,o=[])=>n.prepare(r).run(...o),close:()=>n.close()}}var De=new Set,Cn={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"};function oe(i,t){return (i.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function jn(i,t){if(t>0||!oe(i,"tasks"))return;let e=i.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,o]of Object.entries(Cn))n.has(r)||i.run(`ALTER TABLE tasks ADD COLUMN ${r} ${o}`);}var $n={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"}};function Ln(i,t,e){if(!oe(i,"__drizzle_migrations")||!oe(i,"tasks"))return;let n=i.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(a=>a.hash)),o=JSON.parse(readFileSync(mt__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of o.entries){let c=$n[a.tag];if(!c)continue;let u=mt__default.join(t,`${a.tag}.sql`);if(!existsSync(u))continue;let l=readFileSync(u,"utf-8"),p=createHash("sha256").update(l).digest("hex");if(r.has(p))continue;let h=i.all("PRAGMA table_info(tasks)"),f=new Set(h.map(m=>m.name));for(let[m,q]of Object.entries(c))f.has(m)||(i.run(`ALTER TABLE tasks ADD COLUMN ${m} ${q}`),f.add(m));}}function Bn(i,t,e){let n=i.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(a=>a.hash)),o=JSON.parse(readFileSync(mt__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of o.entries){let c=mt__default.join(t,`${a.tag}.sql`);if(!existsSync(c))continue;let u=readFileSync(c,"utf-8"),l=createHash("sha256").update(u).digest("hex");if(r.has(l))continue;let p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,h=[],f;for(;(f=p.exec(u))!==null;)h.push({table:f[1],column:f[2]});if(h.length===0||!u.split(/-->\s*statement-breakpoint/).map(z=>z.trim()).filter(Boolean).every(z=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(z)))continue;h.every(({table:z,column:G})=>i.all(`PRAGMA table_info("${z}")`).some(it=>it.name===G))&&i.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${a.when})`);}}function Ot(i){let{migrate:t}=Gt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Gt("drizzle-orm"),n=[mt__default.join(y,"../migrations"),mt__default.join(y,"migrations"),mt__default.join(y,"../../../../drizzle/migrations"),mt__default.join(process.cwd(),"drizzle/migrations")],r=n.find(l=>existsSync(mt__default.join(l,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
|
|
2
2
|
${n.join(`
|
|
3
|
-
`)}`);let s=i.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;s?.cnt&&(a=i.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),_n(i,a),s?.cnt&&(hn(i,r,e),fn(i,r,e)),t(i,{migrationsFolder:r});let u=(i.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(u>0){let l=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${u} migration${u>1?"s":""} applied).`);}}function O(i,t){_e.has(t)||(Rt(i),_e.add(t));}var h=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},i=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(i.agent_id),idx_tasks_status:index("idx_tasks_status").on(i.status),idx_tasks_started_at:index("idx_tasks_started_at").on(i.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(i.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(i.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(i.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(i.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(i.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(i.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(i.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(i.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(i.workspace_id,i.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>h.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},i=>({idx_threads_updated_at:index("idx_threads_updated_at").on(i.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(i.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(i.workspace_id,i.updated_at),idx_threads_title:index("idx_threads_title").on(i.title)}));var ct=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>ct.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},i=>({idx_spans_task_id:index("idx_spans_task_id").on(i.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(i.parent_span_id)}));var rt=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},i=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(i.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(i.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(i.timestamp)}));var J=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},i=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(i.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(i.thread_id,i.seq),uniq_thread_boxes_thread_seq:unique().on(i.thread_id,i.seq)}));var Et=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},i=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(i.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(i.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(i.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(i.partition_key)}));var P=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},i=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(i.provider,i.account_ref,i.limit_window,i.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(i.limit_window,i.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(i.provider,i.limit_window,i.bucket_start)}));var q=sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},i=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(i.workspace_id,i.month)}));var k=sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},i=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(i.workspace_id,sql`${i.created_at} DESC`)})),C=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},i=>({pk:primaryKey({columns:[i.notification_id,i.user_id]})}));var S=sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},i=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(i.workspace_id,i.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(i.workspace_id,i.created_at)}));sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},i=>({idCheck:check("ui_instances_id_ck",sql`length(${i.id}) BETWEEN 5 AND 128 AND ${i.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${i.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${i.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${i.definition_hash}) = 64 AND ${i.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${i.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${i.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${i.domain_ref_json}) AND json_type(${i.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${i.state_json}) AND json_type(${i.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${i.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${i.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${i.granted_capabilities_json}) AND json_type(${i.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${i.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${i.updated_at} >= ${i.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(i.workspace_id,i.thread_id)}));sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},i=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${i.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${i.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${i.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${i.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${i.actor_json}) AND json_type(${i.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${i.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${i.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${i.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${i.after_revision} IS NULL OR ${i.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${i.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${i.outcome} IS NULL OR ${i.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${i.input_json}) AND json_type(${i.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${i.result_json} IS NULL OR (json_valid(${i.result_json}) AND json_type(${i.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${i.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${i.settled_at} IS NULL OR ${i.settled_at} >= ${i.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
3
|
+
`)}`);let o=i.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;o?.cnt&&(a=i.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),jn(i,a),o?.cnt&&(Bn(i,r,e),Ln(i,r,e)),t(i,{migrationsFolder:r});let u=(i.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(u>0){let l=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${u} migration${u>1?"s":""} applied).`);}}function I(i,t){De.has(t)||(Ot(i),De.add(t));}var g=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var s=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},i=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(i.agent_id),idx_tasks_status:index("idx_tasks_status").on(i.status),idx_tasks_started_at:index("idx_tasks_started_at").on(i.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(i.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(i.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(i.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(i.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(i.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(i.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(i.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(i.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(i.workspace_id,i.started_at)}));var _=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>g.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},i=>({idx_threads_updated_at:index("idx_threads_updated_at").on(i.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(i.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(i.workspace_id,i.updated_at),idx_threads_title:index("idx_threads_title").on(i.title)}));var kt=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>kt.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},i=>({idx_spans_task_id:index("idx_spans_task_id").on(i.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(i.parent_span_id)}));var ut=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},i=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(i.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(i.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(i.timestamp)}));var et=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},i=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(i.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(i.thread_id,i.seq),uniq_thread_boxes_thread_seq:unique().on(i.thread_id,i.seq)}));var Ct=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},i=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(i.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(i.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(i.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(i.partition_key)}));var U=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},i=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(i.provider,i.account_ref,i.limit_window,i.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(i.limit_window,i.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(i.provider,i.limit_window,i.bucket_start)}));var J=sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},i=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(i.workspace_id,i.month)}));var E=sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},i=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(i.workspace_id,sql`${i.created_at} DESC`)})),j=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},i=>({pk:primaryKey({columns:[i.notification_id,i.user_id]})}));var S=sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},i=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(i.workspace_id,i.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(i.workspace_id,i.created_at)}));sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},i=>({idCheck:check("ui_instances_id_ck",sql`length(${i.id}) BETWEEN 5 AND 128 AND ${i.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${i.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${i.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${i.definition_hash}) = 64 AND ${i.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${i.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${i.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${i.domain_ref_json}) AND json_type(${i.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${i.state_json}) AND json_type(${i.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${i.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${i.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${i.granted_capabilities_json}) AND json_type(${i.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${i.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${i.updated_at} >= ${i.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(i.workspace_id,i.thread_id)}));sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},i=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${i.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${i.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${i.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${i.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${i.actor_json}) AND json_type(${i.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${i.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${i.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${i.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${i.after_revision} IS NULL OR ${i.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${i.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${i.outcome} IS NULL OR ${i.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${i.input_json}) AND json_type(${i.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${i.result_json} IS NULL OR (json_valid(${i.result_json}) AND json_type(${i.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${i.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${i.settled_at} IS NULL OR ${i.settled_at} >= ${i.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
4
4
|
(${i.status} = 'requested' AND ${i.after_revision} IS NULL AND ${i.outcome} IS NULL AND ${i.settled_at} IS NULL)
|
|
5
5
|
OR
|
|
6
6
|
(${i.status} = 'settled' AND ${i.after_revision} IS NOT NULL AND ${i.outcome} IS NOT NULL AND ${i.settled_at} IS NOT NULL)
|
|
7
|
-
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(i.instance_id,i.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(i.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(i.requested_at)}));function
|
|
7
|
+
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(i.instance_id,i.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(i.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(i.requested_at)}));var x=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},i=>({idCheck:check("projects_id_ck",sql`${i.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${i.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${i.stages_json}) AND json_type(${i.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${i.stage_index} >= 1`)})),X=sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>x.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},i=>({idCheck:check("project_criteria_id_ck",sql`${i.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${i.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${i.evidence_json}) AND json_type(${i.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(i.project_id,i.position)})),ct=sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>x.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},i=>({idCheck:check("project_events_id_ck",sql`${i.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${i.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${i.payload_json}) AND json_type(${i.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(i.project_id,i.seq)}));function ce(i){let t=mt.resolve(i);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Ue(i){let t=ce(i);return createHash("sha256").update(t).digest("hex")}function te(i){return i.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var pe=class extends D{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{Ot(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=te(basename(n)),a=`${te(basename(dirname(n)))}-${r}`,c=[r,a];try{let u=l=>t.select({id:g.id}).from(g).where(and(eq(g.slug,l),ne(g.id,e))).limit(1).all().length>0;for(let l of c)if(!u(l))return l;for(let l=2;l<1e3;l+=1){let p=`${a}-${l}`;if(!u(p))return p}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:g.id,slug:g.slug}).from(g).all(),n=0;for(let r of e)if(r.slug.includes("/")){let o=te(r.slug.replace(/\//g,"-"));t.db.update(g).set({slug:o,updated_at:new Date().toISOString()}).where(eq(g.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:o,workspacePath:a}=e,c=new Date().toISOString();t.insert(g).values({id:n,slug:r,name:o,workspace_path:a,is_active:1,created_at:c,updated_at:c}).onConflictDoNothing().run(),t.update(g).set({workspace_path:a,updated_at:c}).where(and(eq(g.id,n),isNull(g.workspace_path))).run();}registerWorkspace(t){let e=ce(t),n=this.openHandle(true);try{let r=Ue(e),o=basename(e),a=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:a,name:o,workspacePath:e}),{id:r,slug:a}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(g.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(g).where(n).get();return {rows:e.db.select().from(g).where(n).orderBy(desc(g.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(g).where(eq(g.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
|
|
8
8
|
(SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
|
|
9
9
|
FROM threads t
|
|
10
10
|
WHERE t.workspace_id = ${t}
|
|
11
11
|
ORDER BY t.updated_at DESC
|
|
12
|
-
LIMIT ${e.limit} OFFSET ${e.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(eq(h.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?and(eq(h.slug,t),ne$1(h.id,e)):eq(h.slug,t);return !!n.db.select({id:h.id}).from(h).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let a=new Date().toISOString();s.db.insert(h).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:a,updated_at:a}).run();let c=s.db.select().from(h).where(eq(h.id,t)).limit(1).get();if(!c)throw new d("DB_ERROR","Insert did not return a row");return c}catch(a){throw a instanceof d?a:new d("DB_ERROR","Failed to insert workspace",a)}finally{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(h).where(eq(h.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(and(eq(h.is_active,1),isNotNull(h.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(h.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(h).where(eq(h.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var De=[h,o,p,ct,rt,J,Et];function Vn(){return at__default.join(ln.homedir(),".crewx","crewx.db")}function Qn(i){if(!Te.existsSync(i))return null;let t=Math.floor(Date.now()/1e3),e=`${i}.bak-${t}`;return Te.copyFileSync(i,e),e}function Ae(i){let t=i.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Zn(i){return i==null||typeof i=="object"&&"queryChunks"in i?null:typeof i=="number"?String(i):typeof i=="boolean"?i?"1":"0":typeof i=="string"?`'${i.replace(/'/g,"''")}'`:String(i)}function tr(i){let t=i.getSQLType(),e=`"${i.name}" ${t}`,n=Zn(i.default);return n!==null&&(e+=` DEFAULT ${n}`),i.notNull&&(e+=" NOT NULL"),e}function er(i,t){let e=t?.dbPath??Vn(),n=t?.force??false,r=t?.dryRun??false,s=r?null:Qn(e);if(n&&!r)try{i.run("DELETE FROM __drizzle_migrations");}catch{}let a=Ae(i);if(!r)try{Rt(i);}catch(f){let m=f instanceof Error?`${f.message} ${f.cause?.message??""}`:"";if(!n||!m.includes("duplicate column"))throw f}let c,u;r?(c=De.map(m=>getTableConfig(m).name).filter(m=>!a.has(m)),u=a):(u=Ae(i),c=[...u].filter(f=>!a.has(f)));let l=[],_=[];for(let f of De){let m=getTableConfig(f),E=m.name;if(!u.has(E))continue;let B=i.all(`PRAGMA table_info("${E}")`),M=new Set(B.map(A=>A.name)),z=new Set(m.columns.map(A=>A.name));for(let A of m.columns)if(!M.has(A.name)){if(!r){let Z=tr(A);i.run(`ALTER TABLE "${E}" ADD COLUMN ${Z}`);}l.push({table:E,column:A.name});}for(let A of B)z.has(A.name)||_.push(`${E}.${A.name} exists in DB but not in schema (untouched)`);}return {created:c,altered:l,warnings:_,backupPath:s}}function Oe(i){let t=i.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}var pt="2026-05-09",cr="0.8.9-rc.13",ft=10,ht=parseInt(cr.split("rc.")[1]);function ve(){let i=sql`
|
|
12
|
+
LIMIT ${e.limit} OFFSET ${e.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(g).where(eq(g.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?and(eq(g.slug,t),ne(g.id,e)):eq(g.slug,t);return !!n.db.select({id:g.id}).from(g).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let o=this.openHandle(true);try{let a=new Date().toISOString();o.db.insert(g).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:a,updated_at:a}).run();let c=o.db.select().from(g).where(eq(g.id,t)).limit(1).get();if(!c)throw new d("DB_ERROR","Insert did not return a row");return c}catch(a){throw a instanceof d?a:new d("DB_ERROR","Failed to insert workspace",a)}finally{o.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let o=r.db.select().from(g).where(eq(g.id,t)).limit(1).get();if(!o)throw new d("NOT_FOUND",`Workspace ${t} not found`);return o}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update workspace",o)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:g.id,workspace_path:g.workspace_path}).from(g).where(and(eq(g.is_active,1),isNotNull(g.workspace_path))).all(),n=0;for(let r of e){let o=r.workspace_path;existsSync(join(o,"crewx.yaml"))||existsSync(join(o,"crewx.yml"))||(t.db.update(g).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(g.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(g).where(eq(g.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Fe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function wr(i){let t=randomBytes(i*2),e="";for(let n=0;n<t.length&&e.length<i;n++){let r=t[n];r<248&&(e+=Fe[r%62]);}for(;e.length<i;)e+=Fe[randomBytes(1)[0]%62];return e}function bt(i){return `${i}_${wr(8)}`}var xr=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),Tr=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),Dr=new Set(["pending","verifying","passed","failed"]),Nr=new Set(["user","project_manager","system"]),vr=new Set(["task","wi","url"]),Ar=/^\d{4}-\d{2}-\d{2}$/;function O(i){throw new d("VALIDATION",i)}function nt(i){throw new d("NOT_FOUND",i)}function L(i,t){(typeof i!="string"||i.trim().length===0)&&O(`${t} is required`);}function Ir(i){if(i==null)return;Ar.test(i)||O("dueDate must use YYYY-MM-DD");let t=new Date(`${i}T00:00:00.000Z`);(Number.isNaN(t.getTime())||t.toISOString().slice(0,10)!==i)&&O("dueDate must be a valid calendar date");}function Pr(i){(!Array.isArray(i)||i.length===0)&&O("stages must contain at least one stage");let t=new Set;for(let e of i)L(e.key,"stage.key"),L(e.label,"stage.label"),t.has(e.key)&&O(`duplicate stage key: ${e.key}`),t.add(e.key);}function Or(i){Array.isArray(i)||O("criteria must be an array");for(let t of i)L(t,"criterion.statement");}function jt(i={}){let t=i.actorType??"system";Nr.has(t)||O(`invalid actorType: ${String(t)}`);let e=i.actorId??null;return (t==="user"||t==="project_manager")&&(!e||e.trim().length===0)&&O(`actorId is required for ${t}`),{actorType:t,actorId:e}}function Ve(i,t){let e=i??{};if((e===null||typeof e!="object"||Array.isArray(e))&&O("event payload must be a JSON object"),t==="accepted")for(let n of ["remainingRisks","nextPlan","lessons","evidenceRefs"])(!Object.prototype.hasOwnProperty.call(e,n)||e[n]===void 0)&&O(`accepted payload requires ${n}`);try{return JSON.stringify(e)}catch(n){throw new d("VALIDATION","event payload must be JSON serializable",n)}}function Cr(i){return Array.isArray(i)||O("evidence must be an array"),i.map(t=>((!t||typeof t!="object")&&O("evidence item must be an object"),vr.has(t.kind)||O(`invalid evidence kind: ${String(t.kind)}`),L(t.ref,"evidence.ref"),t.label!==void 0&&typeof t.label!="string"&&O("evidence.label must be a string"),t.label===void 0?{kind:t.kind,ref:t.ref}:{kind:t.kind,ref:t.ref,label:t.label}))}function Je(i){try{let t=JSON.parse(i);if(!Array.isArray(t))throw new Error("not an array");return t}catch(t){throw new d("DB_ERROR","Project stages JSON is invalid",t)}}function Ye(i){return L(i.projectId,"projectId"),L(i.title,"title"),xr.has(i.type)||O(`invalid project event type: ${String(i.type)}`),{...jt(i),payloadJson:Ve(i.payload,i.type)}}function It(i,t,e){let n=Ye(t);i.select({id:x.id}).from(x).where(eq(x.id,t.projectId)).get()||nt(`Project ${t.projectId} not found`);let o=i.select({maxSeq:sql`COALESCE(MAX(${ct.seq}), 0)`}).from(ct).where(eq(ct.project_id,t.projectId)).get()?.maxSeq??0,a=bt("pje");i.insert(ct).values({id:a,project_id:t.projectId,seq:o+1,actor_type:n.actorType,actor_id:n.actorId,type:t.type,title:t.title,summary:t.summary??null,payload_json:n.payloadJson,created_at:e}).run();let c=i.select().from(ct).where(eq(ct.id,a)).get();if(!c)throw new d("DB_ERROR","Event insert did not return a row");return c}var _e=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(!t&&!existsSync(e))throw new d("NOT_FOUND","Database not found");if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}let n=w(e);if(t)try{I(n.db,e);}catch(r){throw n.close(),r}return n}getDetailFromHandle(t,e){let n=t.db.select().from(x).where(eq(x.id,e)).get();if(!n)return;let r=t.db.select().from(X).where(eq(X.project_id,e)).orderBy(asc(X.position)).all();return {...n,stages:Je(n.stages_json),criteria:r}}getDetailOrThrow(t){let e=this.getProject(t);return e||nt(`Project ${t} not found`),e}createProject(t){L(t.workspaceId,"workspaceId"),L(t.name,"name"),L(t.outcome,"outcome"),Ir(t.dueDate),Pr(t.stages),Or(t.criteria);let e=bt("prj"),n=new Date().toISOString(),r=this.openHandle(true);try{r.db.transaction(o=>{o.insert(x).values({id:e,workspace_id:t.workspaceId,name:t.name,outcome:t.outcome,due_date:t.dueDate??null,scene:"planning",stages_json:JSON.stringify(t.stages),stage_index:1,created_at:n,updated_at:n,accepted_at:null,archived_at:null}).run(),t.criteria.forEach((a,c)=>{o.insert(X).values({id:bt("pjc"),project_id:e,position:c+1,statement:a,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:n,updated_at:n}).run();}),It(o,{projectId:e,actorType:"system",type:"created",title:"Project created",payload:{}},n);});}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to create project",o)}finally{r.close();}return this.getDetailOrThrow(e)}getProject(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return this.getDetailFromHandle(e,t)}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to get project",n)}finally{e.close();}}listProjectsByWorkspace(t,e={}){if(L(t,"workspaceId"),!this.dbExists())return [];let n=this.openHandle(false);try{let r=e.includeArchived?eq(x.workspace_id,t):and(eq(x.workspace_id,t),isNull(x.archived_at));return n.db.select({id:x.id}).from(x).where(r).orderBy(desc(x.updated_at),desc(x.created_at)).all().map(a=>this.getDetailFromHandle(n,a.id)).filter(a=>a!==void 0)}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to list projects",r)}finally{n.close();}}archiveProject(t){L(t,"projectId");let e=this.openHandle(true);try{e.db.update(x).set({archived_at:new Date().toISOString()}).where(eq(x.id,t)).run().changes===0&&nt(`Project ${t} not found`);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to archive project",n)}finally{e.close();}return this.getDetailOrThrow(t)}setScene(t,e,n={}){L(t,"projectId"),Tr.has(e)||O(`invalid project scene: ${String(e)}`);let r=jt(n),o=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let u=c.select().from(x).where(eq(x.id,t)).get();u||nt(`Project ${t} not found`),c.update(x).set({scene:e,updated_at:o}).where(eq(x.id,t)).run(),It(c,{projectId:t,...r,type:"scene_changed",title:"Project scene changed",payload:{before:u.scene,after:e}},o);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to set project scene",c)}finally{a.close();}return this.getDetailOrThrow(t)}setStageIndex(t,e,n={}){L(t,"projectId"),Number.isInteger(e)||O("stage index must be an integer");let r=jt(n),o=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let u=c.select().from(x).where(eq(x.id,t)).get();u||nt(`Project ${t} not found`);let l=Je(u.stages_json);(e<1||e>l.length)&&O("stage index is outside the project stages"),c.update(x).set({stage_index:e,updated_at:o}).where(eq(x.id,t)).run(),It(c,{projectId:t,...r,type:"stage_advanced",title:"Project stage advanced",payload:{before:u.stage_index,after:e}},o);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to set project stage",c)}finally{a.close();}return this.getDetailOrThrow(t)}setCriterionVerify(t,e,n,r={}){let o=typeof t=="string"?{projectId:typeof n=="string"?t:void 0,criterionId:typeof n=="string"?e:t,verifyStatus:typeof n=="string"?n:e,...typeof n=="string"?r:n}:t,a=o.verifyStatus??o.status;(!a||!Dr.has(a))&&O(`invalid criterion status: ${String(a)}`),L(o.criterionId,"criterionId");let c=jt(o),u=new Date().toISOString(),l=this.openHandle(true),p;try{l.db.transaction(f=>{let m=f.select().from(X).where(eq(X.id,o.criterionId)).get();m||nt(`Criterion ${o.criterionId} not found`),p=m.project_id,o.projectId&&o.projectId!==m.project_id&&nt(`Criterion ${o.criterionId} not found in project ${o.projectId}`),f.update(X).set({verify_status:a,verified_at:a==="passed"?u:null,updated_at:u}).where(eq(X.id,o.criterionId)).run(),It(f,{projectId:m.project_id,...c,type:"criterion_verified",title:"Criterion verification updated",payload:{criterionId:o.criterionId,status:a}},u);});}catch(f){throw f instanceof d?f:new d("DB_ERROR","Failed to set criterion verification",f)}finally{l.close();}let h=p?this.getProject(p)?.criteria.find(f=>f.id===o.criterionId):void 0;return h||nt(`Criterion ${o.criterionId} not found`),h}setCriterionEvidence(t,e,n,r={}){let o=typeof t=="string"?{projectId:Array.isArray(n)?t:void 0,criterionId:Array.isArray(n)?e:t,evidence:Array.isArray(n)?n:e,...Array.isArray(n)?r:n}:t;L(o.criterionId,"criterionId");let a=Cr(o.evidence),c=jt(o),u=new Date().toISOString(),l=this.openHandle(true),p;try{l.db.transaction(f=>{let m=f.select().from(X).where(eq(X.id,o.criterionId)).get();m||nt(`Criterion ${o.criterionId} not found`),p=m.project_id,o.projectId&&o.projectId!==m.project_id&&nt(`Criterion ${o.criterionId} not found in project ${o.projectId}`),f.update(X).set({evidence_json:JSON.stringify(a),updated_at:u}).where(eq(X.id,o.criterionId)).run(),It(f,{projectId:m.project_id,...c,type:"criterion_verified",title:"Criterion evidence updated",payload:{criterionId:o.criterionId,evidence:a}},u);});}catch(f){throw f instanceof d?f:new d("DB_ERROR","Failed to set criterion evidence",f)}finally{l.close();}let h=p?this.getProject(p)?.criteria.find(f=>f.id===o.criterionId):void 0;return h||nt(`Criterion ${o.criterionId} not found`),h}appendEvent(t,e){let n=typeof t=="string"?{...e,projectId:t}:t;Ye(n);let r=new Date().toISOString(),o=this.openHandle(true),a;try{o.db.transaction(c=>{a=It(c,n,r);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to append project event",c)}finally{o.close();}if(!a)throw new d("DB_ERROR","Event append did not return a row");return a}listEvents(t,e={}){if(L(t,"projectId"),e.afterSeq!==void 0&&(!Number.isInteger(e.afterSeq)||e.afterSeq<0)&&O("afterSeq must be a non-negative integer"),e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1)&&O("limit must be a positive integer"),!this.dbExists())return [];let n=this.openHandle(false);try{let r=[eq(ct.project_id,t)];e.afterSeq!==void 0&&r.push(gt(ct.seq,e.afterSeq));let o=n.db.select().from(ct).where(and(...r)).orderBy(asc(ct.seq));return e.limit!==void 0&&(o=o.limit(e.limit)),o.all()}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to list project events",r)}finally{n.close();}}acceptProject(t,e){L(t,"projectId");let n=jt(e),r={remainingRisks:e.remainingRisks,nextPlan:e.nextPlan,lessons:e.lessons,evidenceRefs:e.evidenceRefs};Ve(r,"accepted");let o=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{c.select({id:x.id}).from(x).where(eq(x.id,t)).get()||nt(`Project ${t} not found`),c.update(x).set({scene:"accepted",accepted_at:o,updated_at:o}).where(eq(x.id,t)).run(),It(c,{projectId:t,...n,type:"accepted",title:"Project accepted",payload:r},o);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to accept project",c)}finally{a.close();}return this.getDetailOrThrow(t)}};var Ze=[g,s,_,kt,ut,et,Ct];function Lr(){return mt__default.join(On.homedir(),".crewx","crewx.db")}function Br(i){if(!Xe.existsSync(i))return null;let t=Math.floor(Date.now()/1e3),e=`${i}.bak-${t}`;return Xe.copyFileSync(i,e),e}function tn(i){let t=i.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Ur(i){return i==null||typeof i=="object"&&"queryChunks"in i?null:typeof i=="number"?String(i):typeof i=="boolean"?i?"1":"0":typeof i=="string"?`'${i.replace(/'/g,"''")}'`:String(i)}function Hr(i){let t=i.getSQLType(),e=`"${i.name}" ${t}`,n=Ur(i.default);return n!==null&&(e+=` DEFAULT ${n}`),i.notNull&&(e+=" NOT NULL"),e}function Mr(i,t){let e=t?.dbPath??Lr(),n=t?.force??false,r=t?.dryRun??false,o=r?null:Br(e);if(n&&!r)try{i.run("DELETE FROM __drizzle_migrations");}catch{}let a=tn(i);if(!r)try{Ot(i);}catch(h){let f=h instanceof Error?`${h.message} ${h.cause?.message??""}`:"";if(!n||!f.includes("duplicate column"))throw h}let c,u;r?(c=Ze.map(f=>getTableConfig(f).name).filter(f=>!a.has(f)),u=a):(u=tn(i),c=[...u].filter(h=>!a.has(h)));let l=[],p=[];for(let h of Ze){let f=getTableConfig(h),m=f.name;if(!u.has(m))continue;let q=i.all(`PRAGMA table_info("${m}")`),z=new Set(q.map(P=>P.name)),G=new Set(f.columns.map(P=>P.name));for(let P of f.columns)if(!z.has(P.name)){if(!r){let it=Hr(P);i.run(`ALTER TABLE "${m}" ADD COLUMN ${it}`);}l.push({table:m,column:P.name});}for(let P of q)G.has(P.name)||p.push(`${m}.${P.name} exists in DB but not in schema (untouched)`);}return {created:c,altered:l,warnings:p,backupPath:o}}function en(i){let t=i.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}var xt="2026-05-09",Vr="0.8.9-rc.13",Tt=10,Dt=parseInt(Vr.split("rc.")[1]);function nn(){let i=sql`
|
|
13
13
|
CASE
|
|
14
|
-
WHEN ${
|
|
15
|
-
WHEN ${
|
|
16
|
-
WHEN ${
|
|
17
|
-
WHEN ${
|
|
18
|
-
WHEN ${
|
|
19
|
-
WHEN ${
|
|
20
|
-
WHEN ${
|
|
14
|
+
WHEN ${s.model} LIKE 'claude-%' OR ${s.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
15
|
+
WHEN ${s.model} LIKE 'gpt-%' OR ${s.model} LIKE 'codex-%' THEN 'codex'
|
|
16
|
+
WHEN ${s.model} LIKE 'gemini-%' THEN 'gemini'
|
|
17
|
+
WHEN ${s.model} LIKE 'grok-%' THEN 'grok'
|
|
18
|
+
WHEN ${s.model} LIKE 'zai-%' OR ${s.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
19
|
+
WHEN ${s.model} LIKE 'minimax/%' THEN 'minimax'
|
|
20
|
+
WHEN ${s.model} LIKE 'qwen%' THEN 'qwen'
|
|
21
21
|
ELSE 'unknown'
|
|
22
22
|
END
|
|
23
|
-
`,t=sql`json_extract(${
|
|
23
|
+
`,t=sql`json_extract(${s.metadata}, '$.provider')`,e=sql`trim(${t})`,n=sql`substr(${e}, 1, instr(${e}, '/') - 1)`,r=sql`
|
|
24
24
|
CASE
|
|
25
25
|
WHEN instr(${e}, '/') > 0
|
|
26
26
|
AND ${n} IN ('cli', 'acp', 'api', 'plugin', 'remote')
|
|
@@ -29,19 +29,19 @@ ${n.join(`
|
|
|
29
29
|
END
|
|
30
30
|
`;return sql`
|
|
31
31
|
CASE
|
|
32
|
-
WHEN ${
|
|
33
|
-
WHEN json_valid(${
|
|
34
|
-
WHEN json_type(${
|
|
35
|
-
WHEN json_type(${
|
|
36
|
-
WHEN json_type(${
|
|
32
|
+
WHEN ${s.metadata} IS NULL THEN ${i}
|
|
33
|
+
WHEN json_valid(${s.metadata}) = 0 THEN 'unknown'
|
|
34
|
+
WHEN json_type(${s.metadata}, '$') IS NOT 'object' THEN 'unknown'
|
|
35
|
+
WHEN json_type(${s.metadata}, '$.provider') IS NULL THEN ${i}
|
|
36
|
+
WHEN json_type(${s.metadata}, '$.provider') IS NOT 'text' THEN 'unknown'
|
|
37
37
|
WHEN ${e} = '' THEN 'unknown'
|
|
38
38
|
WHEN trim(${r}) = '' THEN 'unknown'
|
|
39
39
|
ELSE ${r}
|
|
40
40
|
END
|
|
41
|
-
`}var
|
|
41
|
+
`}var Yr=new Set(["workflow","mcp"]),rn=600*1e3,he=class extends D{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{I(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(s).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,project_id:t.projectId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:s.id,set:{pid:sql`COALESCE(excluded.pid, ${s.pid})`},setWhere:eq(s.status,"running")}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}listTasksByProjectId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(s).where(eq(s.project_id,t)).orderBy(desc(s.started_at)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to list tasks by project",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
42
42
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
43
43
|
model=COALESCE(?, model)
|
|
44
|
-
WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let
|
|
44
|
+
WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let o=r.select({logs:s.logs}).from(s).where(eq(s.id,t)).limit(1).get(),a=o?.logs?JSON.parse(o.logs):[];a.push(e),r.update(s).set({logs:JSON.stringify(a)}).where(eq(s.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).where(eq(s.status,"running")).orderBy(desc(s.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).orderBy(desc(s.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(s).where(eq(s.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:s.id,status:s.status,pid:s.pid}).from(s).where(eq(s.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(s).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(s.id,t),eq(s.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:s.id,pid:s.pid,platform:s.platform,run_epoch:s.run_epoch}).from(s).where(eq(s.status,"running")).all(),n=Date.now(),r=new Set,o=0;for(let a of e){if(a.pid){let l=!1;try{process.kill(a.pid,0),l=!0;}catch{}l||(t.db.update(s).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(s.id,a.id),eq(s.status,"running"))).run(),o++);continue}if(Yr.has(a.platform??"cli"))continue;let c=`${a.id}:${a.run_epoch??0}`;r.add(c);let u=this.pidNullObservedSince.get(c);if(u===void 0){this.pidNullObservedSince.set(c,n);continue}n-u>=rn&&(t.db.update(s).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(s.id,a.id),eq(s.status,"running"))).run(),o++,this.pidNullObservedSince.delete(c));}for(let a of Array.from(this.pidNullObservedSince.keys()))r.has(a)||this.pidNullObservedSince.delete(a);return o}finally{t.close();}}reapRunningWorkflowTasks(t=rn){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let n=new Date(Date.now()-t).toISOString();return e.db.update(s).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(s.status,"running"),eq(s.platform,"workflow"),isNull(s.pid),lt(s.started_at,n),or(isNull(s.metadata),and(notLike(s.metadata,'%"kind":"workflow_card"%'),notLike(s.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{e.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=w(r);try{let a=e?eq(s.workspace_id,e):void 0,c=a?and(eq(s.id,t),a):eq(s.id,t),u=o.db.select().from(s).where(c).limit(1).get()??void 0;if(!u){let l=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),p=a?and(l,a):l;u=o.db.select().from(s).where(p).orderBy(desc(s.started_at)).limit(1).get()??void 0;}if(u)return u}catch(a){throw new d("DB_ERROR","Failed to find task status",a)}finally{o.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let a of n){if(!existsSync(a))continue;let c=w(a);try{let u=e?and(eq(s.parent_task_id,t),eq(s.workspace_id,e)):eq(s.parent_task_id,t),l=c.db.select().from(s).where(u).orderBy(asc(s.started_at)).all();for(let p of l)r.has(p.id)||(r.add(p.id),o.push(p));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{c.close();}}return o}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
|
|
45
45
|
SELECT
|
|
46
46
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
47
47
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -62,7 +62,7 @@ ${n.join(`
|
|
|
62
62
|
FROM tasks
|
|
63
63
|
GROUP BY workspace_id
|
|
64
64
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
65
|
-
`)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,
|
|
65
|
+
`)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,o=0,a=0,c=0;for(let u of n){if(!existsSync(u))continue;let l=w(u);try{let p=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),h=e?and(p,eq(s.workspace_id,e)):p,f=l.db.select({id:s.id,input_tokens:s.input_tokens,output_tokens:s.output_tokens,cost_usd:s.cost_usd}).from(s).where(h).all();for(let m of f)r.has(m.id)||(r.add(m.id),o+=m.input_tokens??0,a+=m.output_tokens??0,c+=m.cost_usd??0);}catch(p){throw new d("DB_ERROR","Failed to get thread token usage",p)}finally{l.close();}}return {inputTokens:o,outputTokens:a,costUsd:c}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let a of n){if(!existsSync(a))continue;let c=w(a);try{let u=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),l=e?and(u,eq(s.workspace_id,e)):u,p=c.db.select().from(s).where(l).orderBy(asc(s.started_at)).all();for(let h of p)r.has(h.id)||(r.add(h.id),o.push(h));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{c.close();}}return o}parseWorkflowCardMetadata(t){if(!t)return {};try{let e=JSON.parse(t);return {kind:typeof e.kind=="string"?e.kind:void 0,workflowRunId:typeof e.workflowRunId=="string"?e.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let t=[];for(let e of this.resolveDbPaths()){if(!existsSync(e))continue;let n=w(e);try{t.push(...n.db.select({id:s.id,agent_id:s.agent_id,thread_id:s.thread_id,workspace_id:s.workspace_id,platform:s.platform,status:s.status,error:s.error,completed_at:s.completed_at,duration_ms:s.duration_ms,started_at:s.started_at,metadata:s.metadata}).from(s).where(and(eq(s.platform,"workflow"),or(like(s.metadata,'%"kind":"workflow_card"%'),like(s.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(s.started_at)).all());}catch(r){throw new d("DB_ERROR","Failed to find workflow parent tasks",r)}finally{n.close();}}return t}batchFetchWorkflowCards(t,e){let n=new Map;if(t.length===0)return n;let r=new Set(t),o=new Map,a=e?eq(s.workspace_id,e):void 0,c=(u,l)=>{if(!u)return;let p=o.get(u);if(p&&l.started_at<=p)return;let h=this.parseWorkflowCardMetadata(l.metadata);h.kind!=="workflow_card"&&h.kind!=="workflow_ui_instance"||(o.set(u,l.started_at),n.set(u,{taskId:l.id,workflowRunId:h.workflowRunId,raw:l.result??void 0}));};for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let l=w(u);try{let p=and(inArray(s.thread_id,t),or(like(s.metadata,'%"kind":"workflow_card"%'),like(s.metadata,'%"kind":"workflow_ui_instance"%'))),h=l.db.select({id:s.id,thread_id:s.thread_id,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(a?and(p,a):p).all();for(let q of h)c(q.thread_id,q);let f=and(isNull(s.thread_id),or(like(s.metadata,'%"kind":"workflow_card"%'),like(s.metadata,'%"kind":"workflow_ui_instance"%'))),m=l.db.select({id:s.id,command:s.command,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(a?and(f,a):f).all();for(let q of m){let z=this.extractThreadIdFromCommand(q.command);!z||!r.has(z)||c(z,q);}}catch(p){throw new d("DB_ERROR","Failed to batch fetch workflow cards",p)}finally{l.close();}}return n}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(s.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(s.agent_id,r));let o=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;o&&n.push(inArray(s.status,o));let a=t.q??t.search;a&&n.push(like(s.prompt,`%${a}%`)),t.from&&n.push(gte(s.started_at,t.from)),t.to&&n.push(lt(s.started_at,t.to));let c=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(s).where(c).get(),l=(t.sortDir??"DESC")==="ASC"?asc(s.started_at):desc(s.started_at);return {rows:e.db.select().from(s).where(c).orderBy(l).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
|
|
66
66
|
SELECT
|
|
67
67
|
t.agent_id,
|
|
68
68
|
t.workspace_id,
|
|
@@ -70,11 +70,11 @@ ${n.join(`
|
|
|
70
70
|
COALESCE(SUM(
|
|
71
71
|
COALESCE(t.input_tokens, 0)
|
|
72
72
|
+ CASE
|
|
73
|
-
WHEN t.started_at >= ${
|
|
73
|
+
WHEN t.started_at >= ${xt}
|
|
74
74
|
AND (
|
|
75
75
|
t.crewx_version IS NULL
|
|
76
76
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
77
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
77
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Tt}) AS INTEGER) < ${Dt})
|
|
78
78
|
)
|
|
79
79
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
80
80
|
ELSE 0
|
|
@@ -93,11 +93,11 @@ ${n.join(`
|
|
|
93
93
|
COALESCE(SUM(
|
|
94
94
|
COALESCE(t.input_tokens, 0)
|
|
95
95
|
+ CASE
|
|
96
|
-
WHEN t.started_at >= ${
|
|
96
|
+
WHEN t.started_at >= ${xt}
|
|
97
97
|
AND (
|
|
98
98
|
t.crewx_version IS NULL
|
|
99
99
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
100
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
100
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Tt}) AS INTEGER) < ${Dt})
|
|
101
101
|
)
|
|
102
102
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
103
103
|
ELSE 0
|
|
@@ -113,11 +113,11 @@ ${n.join(`
|
|
|
113
113
|
COALESCE(SUM(
|
|
114
114
|
COALESCE(t.input_tokens, 0)
|
|
115
115
|
+ CASE
|
|
116
|
-
WHEN t.started_at >= ${
|
|
116
|
+
WHEN t.started_at >= ${xt}
|
|
117
117
|
AND (
|
|
118
118
|
t.crewx_version IS NULL
|
|
119
119
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
120
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
120
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Tt}) AS INTEGER) < ${Dt})
|
|
121
121
|
)
|
|
122
122
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
123
123
|
ELSE 0
|
|
@@ -135,11 +135,11 @@ ${n.join(`
|
|
|
135
135
|
COALESCE(SUM(
|
|
136
136
|
COALESCE(t.input_tokens, 0)
|
|
137
137
|
+ CASE
|
|
138
|
-
WHEN t.started_at >= ${
|
|
138
|
+
WHEN t.started_at >= ${xt}
|
|
139
139
|
AND (
|
|
140
140
|
t.crewx_version IS NULL
|
|
141
141
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
142
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
142
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Tt}) AS INTEGER) < ${Dt})
|
|
143
143
|
)
|
|
144
144
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
145
145
|
ELSE 0
|
|
@@ -147,18 +147,18 @@ ${n.join(`
|
|
|
147
147
|
), 0)
|
|
148
148
|
+ COALESCE(SUM(t.output_tokens), 0)
|
|
149
149
|
) DESC
|
|
150
|
-
`).map(a=>({agentId:a.agent_id,workspaceId:a.workspace_id??null,totalTasks:a.total_tasks,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(
|
|
150
|
+
`).map(a=>({agentId:a.agent_id,workspaceId:a.workspace_id??null,totalTasks:a.total_tasks,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(o){throw new d("DB_ERROR","Failed to get agent usage",o)}finally{r.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
|
|
151
151
|
SELECT
|
|
152
152
|
date(t.started_at) AS date,
|
|
153
153
|
t.agent_id,
|
|
154
154
|
COALESCE(SUM(
|
|
155
155
|
COALESCE(t.input_tokens, 0)
|
|
156
156
|
+ CASE
|
|
157
|
-
WHEN t.started_at >= ${
|
|
157
|
+
WHEN t.started_at >= ${xt}
|
|
158
158
|
AND (
|
|
159
159
|
t.crewx_version IS NULL
|
|
160
160
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
161
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
161
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Tt}) AS INTEGER) < ${Dt})
|
|
162
162
|
)
|
|
163
163
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
164
164
|
ELSE 0
|
|
@@ -181,11 +181,11 @@ ${n.join(`
|
|
|
181
181
|
COALESCE(SUM(
|
|
182
182
|
COALESCE(t.input_tokens, 0)
|
|
183
183
|
+ CASE
|
|
184
|
-
WHEN t.started_at >= ${
|
|
184
|
+
WHEN t.started_at >= ${xt}
|
|
185
185
|
AND (
|
|
186
186
|
t.crewx_version IS NULL
|
|
187
187
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
188
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
188
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Tt}) AS INTEGER) < ${Dt})
|
|
189
189
|
)
|
|
190
190
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
191
191
|
ELSE 0
|
|
@@ -200,74 +200,74 @@ ${n.join(`
|
|
|
200
200
|
AND t.started_at < ${e}
|
|
201
201
|
GROUP BY date(t.started_at), t.agent_id
|
|
202
202
|
ORDER BY date(t.started_at) ASC
|
|
203
|
-
`).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(
|
|
204
|
-
COALESCE(${
|
|
203
|
+
`).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(o){throw new d("DB_ERROR","Failed to get agent usage trend",o)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(s).where(and(eq(s.id,t),eq(s.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let e=this.openHandle(false);try{return e.db.select({id:s.id,thread_id:s.thread_id,status:s.status,result:s.result,error:s.error,started_at:s.started_at,completed_at:s.completed_at,metadata:s.metadata}).from(s).where(and(eq(s.agent_id,t.agentId),eq(s.workspace_id,t.workspaceId),sql`${s.metadata} IS NOT NULL AND json_valid(${s.metadata}) AND json_extract(${s.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(desc(s.started_at)).limit(1).get()??null}catch(n){throw new d("DB_ERROR","Failed to find latest task by metadata",n)}finally{e.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString(),a=n?and(eq(s.id,t),eq(s.status,"running"),eq(s.workspace_id,n)):and(eq(s.id,t),eq(s.status,"running"));r.db.update(s).set({status:"failed",error:e,completed_at:o}).where(a).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to mark task failed",o)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let a of n){if(!existsSync(a))continue;let c=w(a);try{let u=e?and(like(s.prompt,`%${t}%`),eq(s.workspace_id,e)):like(s.prompt,`%${t}%`),l=c.db.select().from(s).where(u).orderBy(asc(s.started_at)).all();for(let p of l)r.has(p.id)||(r.add(p.id),o.push(p));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{c.close();}}return o}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=nn(),a=sql`
|
|
204
|
+
COALESCE(${s.input_tokens}, 0)
|
|
205
205
|
+ CASE
|
|
206
|
-
WHEN ${
|
|
206
|
+
WHEN ${s.started_at} >= ${xt}
|
|
207
207
|
AND (
|
|
208
|
-
${
|
|
209
|
-
OR (${
|
|
210
|
-
OR (${
|
|
208
|
+
${s.crewx_version} IS NULL
|
|
209
|
+
OR (${s.crewx_version} LIKE '0.8.%' AND ${s.crewx_version} NOT LIKE '0.8.9%')
|
|
210
|
+
OR (${s.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${s.crewx_version}, ${Tt}) AS INTEGER) < ${Dt})
|
|
211
211
|
)
|
|
212
|
-
THEN COALESCE(${
|
|
212
|
+
THEN COALESCE(${s.cached_input_tokens}, 0)
|
|
213
213
|
ELSE 0
|
|
214
214
|
END
|
|
215
|
-
`,c=n?sql`WHERE ${
|
|
215
|
+
`,c=n?sql`WHERE ${s.status} IN ('completed', 'success') AND ${s.started_at} >= ${t} AND ${s.started_at} < ${e} AND ${s.workspace_id} = ${n}`:sql`WHERE ${s.status} IN ('completed', 'success') AND ${s.started_at} >= ${t} AND ${s.started_at} < ${e}`;return r.db.all(sql`
|
|
216
216
|
SELECT
|
|
217
|
-
${
|
|
217
|
+
${o} AS provider,
|
|
218
218
|
COUNT(*) AS total_tasks,
|
|
219
219
|
COALESCE(SUM(${a}), 0) AS input_tokens,
|
|
220
|
-
COALESCE(SUM(${
|
|
221
|
-
COALESCE(SUM(${
|
|
222
|
-
COALESCE(SUM(${
|
|
223
|
-
COALESCE(SUM(${
|
|
224
|
-
MAX(${
|
|
225
|
-
FROM ${
|
|
220
|
+
COALESCE(SUM(${s.output_tokens}), 0) AS output_tokens,
|
|
221
|
+
COALESCE(SUM(${s.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
222
|
+
COALESCE(SUM(${s.cost_usd}), 0) AS cost_usd,
|
|
223
|
+
COALESCE(SUM(${s.duration_ms}), 0) AS active_duration_ms,
|
|
224
|
+
MAX(${s.completed_at}) AS last_active_at
|
|
225
|
+
FROM ${s}
|
|
226
226
|
${c}
|
|
227
|
-
GROUP BY ${
|
|
228
|
-
ORDER BY (COALESCE(SUM(${a}), 0) + COALESCE(SUM(${
|
|
229
|
-
`).map(l=>({provider:l.provider,totalTasks:l.total_tasks,inputTokens:l.input_tokens,outputTokens:l.output_tokens,cachedInputTokens:l.cached_input_tokens,costUsd:l.cost_usd,totalTokens:l.input_tokens+l.output_tokens,activeDurationMs:l.active_duration_ms??0,lastActiveAt:l.last_active_at??null}))}catch(
|
|
230
|
-
COALESCE(${
|
|
227
|
+
GROUP BY ${o}
|
|
228
|
+
ORDER BY (COALESCE(SUM(${a}), 0) + COALESCE(SUM(${s.output_tokens}), 0)) DESC
|
|
229
|
+
`).map(l=>({provider:l.provider,totalTasks:l.total_tasks,inputTokens:l.input_tokens,outputTokens:l.output_tokens,cachedInputTokens:l.cached_input_tokens,costUsd:l.cost_usd,totalTokens:l.input_tokens+l.output_tokens,activeDurationMs:l.active_duration_ms??0,lastActiveAt:l.last_active_at??null}))}catch(o){throw new d("DB_ERROR","Failed to get provider usage",o)}finally{r.close();}}getModelUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=nn(),a=sql`
|
|
230
|
+
COALESCE(${s.input_tokens}, 0)
|
|
231
231
|
+ CASE
|
|
232
|
-
WHEN ${
|
|
232
|
+
WHEN ${s.started_at} >= ${xt}
|
|
233
233
|
AND (
|
|
234
|
-
${
|
|
235
|
-
OR (${
|
|
236
|
-
OR (${
|
|
234
|
+
${s.crewx_version} IS NULL
|
|
235
|
+
OR (${s.crewx_version} LIKE '0.8.%' AND ${s.crewx_version} NOT LIKE '0.8.9%')
|
|
236
|
+
OR (${s.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${s.crewx_version}, ${Tt}) AS INTEGER) < ${Dt})
|
|
237
237
|
)
|
|
238
|
-
THEN COALESCE(${
|
|
238
|
+
THEN COALESCE(${s.cached_input_tokens}, 0)
|
|
239
239
|
ELSE 0
|
|
240
240
|
END
|
|
241
|
-
`,c=n?sql`WHERE ${
|
|
241
|
+
`,c=n?sql`WHERE ${s.status} IN ('completed', 'success') AND ${s.started_at} >= ${t} AND ${s.started_at} < ${e} AND ${s.workspace_id} = ${n}`:sql`WHERE ${s.status} IN ('completed', 'success') AND ${s.started_at} >= ${t} AND ${s.started_at} < ${e}`,u=r.db.all(sql`
|
|
242
242
|
SELECT
|
|
243
|
-
${
|
|
244
|
-
${
|
|
243
|
+
${s.model} AS model,
|
|
244
|
+
${o} AS provider,
|
|
245
245
|
COUNT(*) AS total_tasks,
|
|
246
246
|
COALESCE(SUM(${a}), 0) AS input_tokens,
|
|
247
|
-
COALESCE(SUM(${
|
|
248
|
-
COALESCE(SUM(${
|
|
249
|
-
COALESCE(SUM(${
|
|
250
|
-
COALESCE(SUM(${
|
|
251
|
-
MAX(${
|
|
252
|
-
FROM ${
|
|
247
|
+
COALESCE(SUM(${s.output_tokens}), 0) AS output_tokens,
|
|
248
|
+
COALESCE(SUM(${s.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
249
|
+
COALESCE(SUM(${s.cost_usd}), 0) AS cost_usd,
|
|
250
|
+
COALESCE(SUM(${s.duration_ms}), 0) AS active_duration_ms,
|
|
251
|
+
MAX(${s.completed_at}) AS last_active_at
|
|
252
|
+
FROM ${s}
|
|
253
253
|
${c}
|
|
254
|
-
GROUP BY ${
|
|
255
|
-
`),l=new Map;for(let
|
|
254
|
+
GROUP BY ${s.model}, ${o}
|
|
255
|
+
`),l=new Map;for(let p of u){let h=en(p.model??""),f=JSON.stringify([p.provider,h]),m=l.get(f);m?(m.totalTasks+=p.total_tasks,m.inputTokens+=p.input_tokens,m.outputTokens+=p.output_tokens,m.cachedInputTokens+=p.cached_input_tokens,m.costUsd+=p.cost_usd,m.totalTokens+=p.input_tokens+p.output_tokens,m.activeDurationMs+=p.active_duration_ms??0,p.last_active_at&&(!m.lastActiveAt||p.last_active_at>m.lastActiveAt)&&(m.lastActiveAt=p.last_active_at)):l.set(f,{model:h,provider:p.provider,totalTasks:p.total_tasks,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null});}return Array.from(l.values()).sort((p,h)=>h.costUsd-p.costUsd)}catch(o){throw new d("DB_ERROR","Failed to get model usage",o)}finally{r.close();}}getTasksForReport(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=n?sql`WHERE ${s.started_at} >= ${t} AND ${s.started_at} < ${e} AND ${s.workspace_id} = ${n}`:sql`WHERE ${s.started_at} >= ${t} AND ${s.started_at} < ${e}`;return r.db.all(sql`
|
|
256
256
|
SELECT
|
|
257
|
-
${
|
|
258
|
-
${
|
|
259
|
-
${
|
|
260
|
-
${
|
|
261
|
-
${
|
|
262
|
-
${
|
|
263
|
-
FROM ${
|
|
264
|
-
${
|
|
265
|
-
ORDER BY ${
|
|
266
|
-
`).map(c=>({threadId:c.thread_id,agentId:c.agent_id,startedAt:c.started_at,status:c.status,error:c.error,exitCode:c.exit_code}))}catch(
|
|
257
|
+
${s.thread_id} AS thread_id,
|
|
258
|
+
${s.agent_id} AS agent_id,
|
|
259
|
+
${s.started_at} AS started_at,
|
|
260
|
+
${s.status} AS status,
|
|
261
|
+
${s.error} AS error,
|
|
262
|
+
${s.exit_code} AS exit_code
|
|
263
|
+
FROM ${s}
|
|
264
|
+
${o}
|
|
265
|
+
ORDER BY ${s.started_at} ASC
|
|
266
|
+
`).map(c=>({threadId:c.thread_id,agentId:c.agent_id,startedAt:c.started_at,status:c.status,error:c.error,exitCode:c.exit_code}))}catch(o){throw new d("DB_ERROR","Failed to get tasks for report",o)}finally{r.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(s.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&n.push(inArray(s.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&n.push(inArray(s.status,t.statuses)),t.from&&n.push(gte(s.started_at,t.from)),t.to&&n.push(lt(s.started_at,t.to));let r=n.length>0?and(...n):void 0,o=(t.order??"DESC")==="ASC"?asc(s.started_at):desc(s.started_at),a={id:s.id,agent_id:s.agent_id,status:s.status,prompt:s.prompt,started_at:s.started_at,completed_at:s.completed_at,thread_id:s.thread_id};return t.limit?e.db.select(a).from(s).where(r).orderBy(o).limit(t.limit).all():e.db.select(a).from(s).where(r).orderBy(o).all()}catch(n){throw new d("DB_ERROR","Failed to find task evidence",n)}finally{e.close();}}findThreadChains(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=t.maxThreads??8,r=t.maxTurnsPerThread??4,o=[isNotNull(s.thread_id),isNull(s.parent_task_id),isNull(s.caller_agent_id),or(isNull(s.platform),ne(s.platform,"workflow")),or(isNull(s.metadata),and(notLike(s.metadata,'%"kind":"workflow_card"%'),notLike(s.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(s.metadata),notLike(s.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&o.push(eq(s.workspace_id,t.workspaceId)),t.from&&o.push(gte(s.started_at,t.from)),t.to&&o.push(lt(s.started_at,t.to));let a=e.db.select({id:s.id,agent_id:s.agent_id,status:s.status,prompt:s.prompt,started_at:s.started_at,completed_at:s.completed_at,thread_id:s.thread_id}).from(s).where(and(...o)).orderBy(asc(s.started_at),asc(s.id)).all(),c=new Map;for(let l of a){if(!l.thread_id)continue;let p={id:l.id,agentId:l.agent_id,status:l.status,prompt:l.prompt,startedAt:l.started_at,completedAt:l.completed_at},h=c.get(l.thread_id);h?h.push(p):c.set(l.thread_id,[p]);}let u=[];for(let[l,p]of c){let h=p.filter(f=>f.agentId===t.targetAgentId).length;h<2||u.push({threadId:l,targetAgentTurnCount:h,turns:p});}return u.sort((l,p)=>{let h=l.turns[l.turns.length-1].startedAt,f=p.turns[p.turns.length-1].startedAt;return h<f?1:h>f?-1:0}),u.slice(0,n).map(l=>({threadId:l.threadId,targetAgentTurnCount:l.targetAgentTurnCount,turns:l.turns.slice(-r)}))}catch(n){throw new d("DB_ERROR","Failed to find thread chains",n)}finally{e.close();}}};var ge=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{I(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:g.id}).from(g).where(eq(g.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
|
|
267
267
|
SELECT 1 FROM tasks parent
|
|
268
268
|
WHERE parent.id = ${t}.parent_task_id
|
|
269
269
|
AND parent.thread_id = ${t}.thread_id
|
|
270
|
-
)`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let
|
|
270
|
+
)`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let o of e){if(!existsSync(o))continue;let a=w(o);try{let c=t?eq(_.workspace_id,t):void 0,u=a.db.select().from(_).where(c).orderBy(desc(_.updated_at)).all();for(let l of u)n.has(l.id)||(n.add(l.id),r.push(l));}catch(c){throw new d("DB_ERROR","Failed to find all threads",c)}finally{a.close();}}return r}findThreadsByIdsOrTitles(t,e){if(t.length===0)return [];let n=this.resolveDbPaths(),r=new Set,o=[];for(let a of n){if(!existsSync(a))continue;let c=w(a);try{let u=or(inArray(_.id,t),inArray(_.title,t)),l=e?and(u,eq(_.workspace_id,e)):u,p=c.db.select().from(_).where(l).orderBy(desc(_.updated_at)).all();for(let h of p)r.has(h.id)||(r.add(h.id),o.push(h));}catch(u){throw new d("DB_ERROR","Failed to find threads by ids or titles",u)}finally{c.close();}}return o}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=w(r);try{let a=eq(_.id,t),c=e?and(a,eq(_.workspace_id,e)):a,u=o.db.select().from(_).where(c).limit(1).get()??void 0;if(u)return u}catch(a){throw new d("DB_ERROR","Failed to find thread by id",a)}finally{o.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=w(r);try{let a=eq(_.id,t),c=e?and(a,eq(_.workspace_id,e)):a;if(o.db.select({id:_.id}).from(_).where(c).limit(1).get())return !0}catch(a){throw new d("DB_ERROR","Failed to check thread existence",a)}finally{o.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,o=0,a=0,c=0,u=0,l=new Set;for(let p of n){if(!existsSync(p))continue;let h=w(p);try{let f=h.db.get(sql`
|
|
271
271
|
SELECT
|
|
272
272
|
count(*) AS cnt,
|
|
273
273
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -278,13 +278,13 @@ ${n.join(`
|
|
|
278
278
|
WHERE child.thread_id = ${t}
|
|
279
279
|
AND ${this.topLevelTaskPredicateSql()}
|
|
280
280
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
281
|
-
`);
|
|
281
|
+
`);f&&(r+=f.cnt,o+=f.total_input,a+=f.total_output,c+=f.total_cached,u+=f.total_cost);let m=h.db.all(sql`
|
|
282
282
|
SELECT DISTINCT child.agent_id FROM tasks child
|
|
283
283
|
WHERE child.thread_id = ${t}
|
|
284
284
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
285
285
|
AND ${this.topLevelTaskPredicateSql()}
|
|
286
286
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
287
|
-
`);for(let
|
|
287
|
+
`);for(let q of m)l.add(q.agent_id);}catch(f){throw new d("DB_ERROR","Failed to aggregate task stats",f)}finally{h.close();}}return {taskCount:r,inputTokens:o,outputTokens:a,cachedInputTokens:c,costUsd:u,agentIds:Array.from(l)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),o=new Set,a=[];for(let c of r){if(!existsSync(c))continue;let u=w(c);try{let l;n!==void 0?l=u.db.all(sql`
|
|
288
288
|
SELECT * FROM (
|
|
289
289
|
SELECT child.*,
|
|
290
290
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -301,7 +301,7 @@ ${n.join(`
|
|
|
301
301
|
AND ${this.topLevelTaskPredicateSql()}
|
|
302
302
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
303
303
|
ORDER BY child.started_at ASC
|
|
304
|
-
`);for(let
|
|
304
|
+
`);for(let p of l)o.has(p.id)||(o.add(p.id),a.push(p));}catch(l){throw new d("DB_ERROR","Failed to find top-level tasks",l)}finally{u.close();}}if(n!==void 0&&r.length>1){let c=new Map;for(let u of a){let l=u.agent_id??"";c.has(l)||c.set(l,[]),c.get(l).push(u);}a=[];for(let u of c.values())u.sort((l,p)=>(p.started_at??"").localeCompare(l.started_at??"")),a.push(...u.slice(0,n));a.sort((u,l)=>(u.started_at??"").localeCompare(l.started_at??""));}return a}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let a of n){if(!existsSync(a))continue;let c=w(a);try{let u=eq(s.thread_id,t),l=e?and(u,eq(s.workspace_id,e)):u,p=c.db.select().from(s).where(l).orderBy(asc(s.started_at)).all();for(let h of p)r.has(h.id)||(r.add(h.id),o.push(h));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{c.close();}}return o}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let a=w(o);try{let c=and(eq(s.id,e),eq(s.thread_id,t)),u=n?and(c,eq(s.workspace_id,n)):c,l=a.db.select().from(s).where(u).limit(1).get();if(!l)continue;let p=a.db.select().from(s).where(eq(s.parent_task_id,l.id)).orderBy(asc(s.started_at)).all();return {task:l,children:p}}catch(c){throw new d("DB_ERROR","Failed to find task by id",c)}finally{a.close();}}}batchFetchTasksQuery(t,e){return sql`
|
|
305
305
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
306
306
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
307
307
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -311,12 +311,12 @@ ${n.join(`
|
|
|
311
311
|
AND ${this.topLevelTaskPredicateSql()}
|
|
312
312
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
313
313
|
ORDER BY child.started_at ASC
|
|
314
|
-
`}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let
|
|
314
|
+
`}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let a=w(o);try{let c=a.db.all(this.batchFetchTasksQuery(t,e));for(let u of c){let l=u.thread_id;n.has(l)||n.set(l,[]),n.get(l).push(u);}}catch(c){throw new d("DB_ERROR","Failed to batch fetch tasks",c)}finally{a.close();}}return n}explainBatchFetchTasksPlan(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=w(r);try{return o.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,e)}`).map(c=>c.detail)}finally{o.close();}}return []}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=eq(_.id,t),a=n?and(o,eq(_.workspace_id,n)):o;if(!r.db.select({id:_.id}).from(_).where(a).limit(1).get())return;r.db.update(_).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(_.id,t)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update thread title",o)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,o=new Date().toISOString();if(n.db.select({id:_.id,message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()){let c={updated_at:o};e.title!==void 0&&(c.title=e.title),e.titleLocked!==void 0&&(c.title_locked=e.titleLocked?1:0),n.db.update(_).set(c).where(eq(_.id,t)).run();}else n.db.insert(_).values({id:t,platform:e.platform,workspace_id:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:o,updated_at:o}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let o=n?this.validateWorkspaceId(r,n):null,a=r.db.select({id:_.id,platform:_.platform,workspace_id:_.workspace_id}).from(_).where(eq(_.id,t)).limit(1).get();if(a){o&&!a.workspace_id&&r.db.update(_).set({workspace_id:o}).where(eq(_.id,t)).run();return}let c=new Date().toISOString();r.db.insert(_).values({id:t,platform:e,workspace_id:o,message_count:0,created_at:c,updated_at:c}).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to ensure thread",o)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let o=new Date().toISOString();return {firstMessage:r.db.transaction(c=>{let l=c.select({message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()?.message_count===0;return c.run(sql`
|
|
315
315
|
UPDATE threads
|
|
316
316
|
SET first_message = COALESCE(first_message, ${e}),
|
|
317
317
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
|
|
318
318
|
last_message = ${e},
|
|
319
319
|
message_count = message_count + 1,
|
|
320
|
-
updated_at = ${
|
|
320
|
+
updated_at = ${o}
|
|
321
321
|
WHERE id = ${t}
|
|
322
|
-
`),l},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:s}).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!s)return null;let a=s.pinned?0:1,c=s.metadata?JSON.parse(s.metadata):{};if(a){let u=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),l=n.db.select({metadata:p.metadata}).from(p).where(u).all(),_=null;for(let f of l){let m=f.metadata?JSON.parse(f.metadata):{};typeof m.pinOrder=="number"&&(_===null||m.pinOrder<_)&&(_=m.pinOrder);}c.pinOrder=_===null?0:_-1;}else delete c.pinOrder;return n.db.update(p).set({pinned:a,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(r).run(),{pinned:!!a}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),a=n.db.select({metadata:p.metadata}).from(p).where(s).get();if(!a)continue;let c=a.metadata?JSON.parse(a.metadata):{};c.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(c)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({starred:p.starred}).from(p).where(r).get();if(!s)return null;let a=s.starred?0:1;return n.db.update(p).set({starred:a}).where(r).run(),{starred:!!a}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let a=this.openHandle(true);try{let c=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return a.db.transaction(l=>{let _=l.select({metadata:p.metadata}).from(p).where(c).get();if(!_)return null;let f=_.metadata?JSON.parse(_.metadata):{},m=f.overdrive??{},E=r?.defaultTurns??m.defaultTurns??3,B=r?.updatedBy??"ui",M=new Date().toISOString(),z,A,Z,xt;switch(n){case "enable-count":{let Tt=r?.turns??E,Nt=r?.consumeCurrent?Math.max(Tt-1,0):Tt;z=Nt>0?"count":"off",A=Nt,Z=!0,xt="count";break}case "enable-latch":{z="latch",A=0,Z=!0,xt="latch";break}case "disable":{z="off",A=0,Z=!1;break}default:{let Tt=m.state??"off",Nt=typeof m.remaining=="number"?m.remaining:0;if(Tt==="count"&&Nt>0){let ue=Nt-1;ue<=0?(z="off",A=0):(z="count",A=ue),Z=!0,xt="count";}else Tt==="latch"?(z="latch",A=0,Z=!0,xt="latch"):(z="off",A=0,Z=!1);break}}return f.overdrive={state:z,remaining:A,defaultTurns:E,updatedAt:M,updatedBy:B},l.update(p).set({metadata:JSON.stringify(f),updated_at:M}).where(c).run(),{applied:Z,appliedMode:xt,state:z,remaining:A}},{behavior:"immediate"})}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to resolve overdrive",c)}finally{a.close();}}};var ne=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(ct).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(ct).where(eq(ct.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(ct).where(eq(ct.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var re=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(rt).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(rt).where(eq(rt.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:rt.tool_name,count:sql`count(*)`}).from(rt).where(eq(rt.task_id,t)).groupBy(rt.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var oe=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(J).where(eq(J.thread_id,t)).orderBy(asc(J.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(J).where(and(eq(J.id,e),eq(J.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(J).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(J).where(eq(J.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var se=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(Et).values({id:randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(Et).orderBy(desc(Et.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function qe(i){return new Date(Math.floor(i/3e5)*3e5).toISOString()}var ie=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=qe(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(P).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[P.provider,P.account_ref,P.limit_window,P.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider:P.provider,bucket_start:P.bucket_start,used_percent:P.used_percent,remaining_percent:P.remaining_percent,resets_at:P.resets_at}).from(P).where(and(eq(P.limit_window,t.window),gte(P.bucket_start,t.fromIso),lte(P.bucket_start,t.toIso))).orderBy(asc(P.bucket_start)).all(),r=new Map;for(let s of n)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,a])=>({provider:s,points:a}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};var ae=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert(q).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[q.workspace_id,q.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let n=e.db.select().from(q).where(and(eq(q.workspace_id,t.workspaceId),eq(q.month,t.month))).limit(1).get();if(!n)throw new d("DB_ERROR","Failed to read back published usage report");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to publish usage report",n)}finally{e.close();}}findByMonth(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(q).where(and(eq(q.workspace_id,t),eq(q.month,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{n.close();}}listByWorkspace(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(q).where(eq(q.workspace_id,t)).orderBy(desc(q.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};var Ge="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function jr(i){let t=randomBytes(i*2),e="";for(let n=0;n<t.length&&e.length<i;n++){let r=t[n];r<248&&(e+=Ge[r%62]);}for(;e.length<i;)e+=Ge[randomBytes(1)[0]%62];return e}function Wt(i){return `${i}_${jr(8)}`}var Qe=500,Ze=50,de=class extends D{dbPath;cap;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db")),this.cap=t.cap??Qe;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}create(t){let e=this.openHandle(true);try{let n=Wt("ntf"),r=new Date().toISOString();return e.db.insert(k).values({id:n,workspace_id:t.workspaceId,agent_id:t.agentId??null,task_id:t.taskId??null,thread_id:t.threadId??null,source:t.source??"agent",level:t.level??"info",title:t.title,body:t.body??null,target_user_id:t.targetUserId??null,created_at:r,metadata:t.metadata??null}).run(),this.enforceCap(e,t.workspaceId),{id:n}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create notification",n)}finally{e.close();}}enforceCap(t,e){let s=(t.db.select({count:sql`count(*)`}).from(k).where(eq(k.workspace_id,e)).get()?.count??0)-this.cap;if(s<=0)return;let c=t.db.select({id:k.id}).from(k).innerJoin(C,eq(C.notification_id,k.id)).where(eq(k.workspace_id,e)).groupBy(k.id).orderBy(asc(k.created_at)).limit(s).all().map(u=>u.id);c.length!==0&&(t.db.delete(C).where(inArray(C.notification_id,c)).run(),t.db.delete(k).where(inArray(k.id,c)).run());}list(t){if(!this.dbExists())return [];let e=t.limit??Ze,n=this.openHandle(false);try{return n.db.select({id:k.id,workspace_id:k.workspace_id,agent_id:k.agent_id,task_id:k.task_id,thread_id:k.thread_id,source:k.source,level:k.level,title:k.title,body:k.body,target_user_id:k.target_user_id,created_at:k.created_at,metadata:k.metadata,read_at:C.read_at}).from(k).leftJoin(C,and(eq(C.notification_id,k.id),eq(C.user_id,t.userId))).where(eq(k.workspace_id,t.workspaceId)).orderBy(desc(k.created_at)).limit(e).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(r){throw new d("DB_ERROR","Failed to list notifications",r)}finally{n.close();}}unreadCount(t){if(!this.dbExists())return 0;let e=this.openHandle(false);try{return e.db.select({count:sql`count(*)`}).from(k).leftJoin(C,and(eq(C.notification_id,k.id),eq(C.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(C.notification_id))).get()?.count??0}catch(n){throw new d("DB_ERROR","Failed to count unread notifications",n)}finally{e.close();}}markRead(t){let e=this.openHandle(true);try{if(!e.db.select({id:k.id}).from(k).where(and(eq(k.id,t.notificationId),eq(k.workspace_id,t.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return e.db.insert(C).values({notification_id:t.notificationId,user_id:t.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark notification read",n)}finally{e.close();}}markAllRead(t){let e=this.openHandle(true);try{let n=e.db.select({id:k.id}).from(k).leftJoin(C,and(eq(C.notification_id,k.id),eq(C.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(C.notification_id))).all();if(n.length===0)return 0;let r=new Date().toISOString();return e.db.transaction(s=>{for(let a of n)s.insert(C).values({notification_id:a.id,user_id:t.userId,read_at:r}).onConflictDoNothing().run();}),n.length}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark all notifications read",n)}finally{e.close();}}};var nn=50,le=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}create(t){let e=this.openHandle(true);try{let n=new Date().toISOString(),r=[],s=t.map(a=>{let c=Wt("sug");return r.push(c),{id:c,workspace_id:a.workspaceId,agent_id:a.agentId,task_id:a.taskId??null,type:a.type,status:a.status??"pending",payload:a.payload,applied_commit_sha:a.appliedCommitSha??null,created_at:n,updated_at:n}});return s.length>0&&e.db.insert(S).values(s).run(),{ids:r}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create agent suggestions",n)}finally{e.close();}}findLatestSet(t,e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=n.db.select({task_id:S.task_id}).from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e))).orderBy(desc(S.created_at)).limit(1).get();if(!r)return [];let s=r.task_id===null?isNull(S.task_id):eq(S.task_id,r.task_id);return n.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),s)).orderBy(asc(S.created_at)).all()}catch(r){throw new d("DB_ERROR","Failed to find latest agent suggestion set",r)}finally{n.close();}}findSetByTaskId(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),eq(S.task_id,n))).orderBy(asc(S.created_at)).all()}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{r.close();}}findById(t,e,n){if(!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),eq(S.id,n))).get()??null}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion by id",s)}finally{r.close();}}updateStatus(t,e,n){let r=this.openHandle(true);try{let s={status:e,updated_at:new Date().toISOString()};return n!==void 0&&(s.applied_commit_sha=n),r.db.update(S).set(s).where(eq(S.id,t)).run().changes>0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update agent suggestion status",s)}finally{r.close();}}listByAgent(t,e,n=nn){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e))).orderBy(desc(S.created_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to list agent suggestions",s)}finally{r.close();}}findDismissed(t,e,n=20){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),eq(S.status,"dismissed"))).orderBy(desc(S.updated_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{r.close();}}};export{le as AgentSuggestionRepository,D as BaseSqliteRepository,nn as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,Qe as DEFAULT_NOTIFICATION_CAP,Ze as DEFAULT_NOTIFICATION_LIST_LIMIT,de as NotificationRepository,d as RepositoryError,se as RequestLogRepository,ne as SpanRepository,te as TaskRepository,oe as ThreadBoxRepository,ee as ThreadRepository,re as ToolCallRepository,ie as UsageLimitSnapshotRepository,ae as UsageReportRepository,Qt as WorkspaceRepository,qe as calcBucketStart,w as openDrizzleDb,er as pushSchema,Rt as runMigrations,O as runMigrationsOnce,o as tasks};
|
|
322
|
+
`),l},{behavior:"immediate"})}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save user message",o)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.update(_).set({last_message:e,updated_at:o}).where(eq(_.id,t)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save assistant message",o)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(_).set(r).where(eq(_.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(_.id,t),eq(_.workspace_id,e)):eq(_.id,t),o=n.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!o)return null;let a=o.pinned?0:1,c=o.metadata?JSON.parse(o.metadata):{};if(a){let u=e?and(eq(_.pinned,1),eq(_.workspace_id,e)):eq(_.pinned,1),l=n.db.select({metadata:_.metadata}).from(_).where(u).all(),p=null;for(let h of l){let f=h.metadata?JSON.parse(h.metadata):{};typeof f.pinOrder=="number"&&(p===null||f.pinOrder<p)&&(p=f.pinOrder);}c.pinOrder=p===null?0:p-1;}else delete c.pinOrder;return n.db.update(_).set({pinned:a,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(r).run(),{pinned:!!a}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let o=e?and(eq(_.id,t[r]),eq(_.workspace_id,e)):eq(_.id,t[r]),a=n.db.select({metadata:_.metadata}).from(_).where(o).get();if(!a)continue;let c=a.metadata?JSON.parse(a.metadata):{};c.pinOrder=r+1,n.db.update(_).set({metadata:JSON.stringify(c)}).where(o).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(_.id,t),eq(_.workspace_id,e)):eq(_.id,t),o=n.db.select({starred:_.starred}).from(_).where(r).get();if(!o)return null;let a=o.starred?0:1;return n.db.update(_).set({starred:a}).where(r).run(),{starred:!!a}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let a=this.openHandle(true);try{let c=e?and(eq(_.id,t),eq(_.workspace_id,e)):eq(_.id,t);return a.db.transaction(l=>{let p=l.select({metadata:_.metadata}).from(_).where(c).get();if(!p)return null;let h=p.metadata?JSON.parse(p.metadata):{},f=h.overdrive??{},m=r?.defaultTurns??f.defaultTurns??3,q=r?.updatedBy??"ui",z=new Date().toISOString(),G,P,it,Bt;switch(n){case "enable-count":{let Ut=r?.turns??m,Ht=r?.consumeCurrent?Math.max(Ut-1,0):Ut;G=Ht>0?"count":"off",P=Ht,it=!0,Bt="count";break}case "enable-latch":{G="latch",P=0,it=!0,Bt="latch";break}case "disable":{G="off",P=0,it=!1;break}default:{let Ut=f.state??"off",Ht=typeof f.remaining=="number"?f.remaining:0;if(Ut==="count"&&Ht>0){let Te=Ht-1;Te<=0?(G="off",P=0):(G="count",P=Te),it=!0,Bt="count";}else Ut==="latch"?(G="latch",P=0,it=!0,Bt="latch"):(G="off",P=0,it=!1);break}}return h.overdrive={state:G,remaining:P,defaultTurns:m,updatedAt:z,updatedBy:q},l.update(_).set({metadata:JSON.stringify(h),updated_at:z}).where(c).run(),{applied:it,appliedMode:Bt,state:G,remaining:P}},{behavior:"immediate"})}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to resolve overdrive",c)}finally{a.close();}}};var me=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{I(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(kt).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(kt).where(eq(kt.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(kt).where(eq(kt.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var we=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{I(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(ut).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(ut).where(eq(ut.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:ut.tool_name,count:sql`count(*)`}).from(ut).where(eq(ut.task_id,t)).groupBy(ut.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var ke=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{I(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:_.id}).from(_).where(eq(_.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(et).where(eq(et.thread_id,t)).orderBy(asc(et.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(et).where(and(eq(et.id,e),eq(et.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(et).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(et).where(eq(et.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var ye=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{I(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let o of t)r.insert(Ct).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:n,metadata:o.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(Ct).orderBy(desc(Ct.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function hn(i){return new Date(Math.floor(i/3e5)*3e5).toISOString()}var Ee=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{I(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=hn(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(U).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[U.provider,U.account_ref,U.limit_window,U.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider:U.provider,bucket_start:U.bucket_start,used_percent:U.used_percent,remaining_percent:U.remaining_percent,resets_at:U.resets_at}).from(U).where(and(eq(U.limit_window,t.window),gte(U.bucket_start,t.fromIso),lte(U.bucket_start,t.toIso))).orderBy(asc(U.bucket_start)).all(),r=new Map;for(let o of n)r.has(o.provider)||r.set(o.provider,[]),r.get(o.provider).push({bucketStart:o.bucket_start,usedPercent:o.used_percent,remainingPercent:o.remaining_percent,resetsAt:o.resets_at??null});return Array.from(r.entries()).map(([o,a])=>({provider:o,points:a}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};var Re=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{I(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert(J).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[J.workspace_id,J.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let n=e.db.select().from(J).where(and(eq(J.workspace_id,t.workspaceId),eq(J.month,t.month))).limit(1).get();if(!n)throw new d("DB_ERROR","Failed to read back published usage report");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to publish usage report",n)}finally{e.close();}}findByMonth(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(J).where(and(eq(J.workspace_id,t),eq(J.month,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{n.close();}}listByWorkspace(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(J).where(eq(J.workspace_id,t)).orderBy(desc(J.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};var Rn=500,bn=50,be=class extends D{dbPath;cap;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db")),this.cap=t.cap??Rn;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{I(n.db,e);}catch(r){throw n.close(),r}return n}create(t){let e=this.openHandle(true);try{let n=bt("ntf"),r=new Date().toISOString();return e.db.insert(E).values({id:n,workspace_id:t.workspaceId,agent_id:t.agentId??null,task_id:t.taskId??null,thread_id:t.threadId??null,source:t.source??"agent",level:t.level??"info",title:t.title,body:t.body??null,target_user_id:t.targetUserId??null,created_at:r,metadata:t.metadata??null}).run(),this.enforceCap(e,t.workspaceId),{id:n}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create notification",n)}finally{e.close();}}enforceCap(t,e){let o=(t.db.select({count:sql`count(*)`}).from(E).where(eq(E.workspace_id,e)).get()?.count??0)-this.cap;if(o<=0)return;let c=t.db.select({id:E.id}).from(E).innerJoin(j,eq(j.notification_id,E.id)).where(eq(E.workspace_id,e)).groupBy(E.id).orderBy(asc(E.created_at)).limit(o).all().map(u=>u.id);c.length!==0&&(t.db.delete(j).where(inArray(j.notification_id,c)).run(),t.db.delete(E).where(inArray(E.id,c)).run());}list(t){if(!this.dbExists())return [];let e=t.limit??bn,n=this.openHandle(false);try{return n.db.select({id:E.id,workspace_id:E.workspace_id,agent_id:E.agent_id,task_id:E.task_id,thread_id:E.thread_id,source:E.source,level:E.level,title:E.title,body:E.body,target_user_id:E.target_user_id,created_at:E.created_at,metadata:E.metadata,read_at:j.read_at}).from(E).leftJoin(j,and(eq(j.notification_id,E.id),eq(j.user_id,t.userId))).where(eq(E.workspace_id,t.workspaceId)).orderBy(desc(E.created_at)).limit(e).all().map(o=>({...o,read_at:o.read_at??null,read:o.read_at!=null}))}catch(r){throw new d("DB_ERROR","Failed to list notifications",r)}finally{n.close();}}unreadCount(t){if(!this.dbExists())return 0;let e=this.openHandle(false);try{return e.db.select({count:sql`count(*)`}).from(E).leftJoin(j,and(eq(j.notification_id,E.id),eq(j.user_id,t.userId))).where(and(eq(E.workspace_id,t.workspaceId),isNull(j.notification_id))).get()?.count??0}catch(n){throw new d("DB_ERROR","Failed to count unread notifications",n)}finally{e.close();}}markRead(t){let e=this.openHandle(true);try{if(!e.db.select({id:E.id}).from(E).where(and(eq(E.id,t.notificationId),eq(E.workspace_id,t.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return e.db.insert(j).values({notification_id:t.notificationId,user_id:t.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark notification read",n)}finally{e.close();}}markAllRead(t){let e=this.openHandle(true);try{let n=e.db.select({id:E.id}).from(E).leftJoin(j,and(eq(j.notification_id,E.id),eq(j.user_id,t.userId))).where(and(eq(E.workspace_id,t.workspaceId),isNull(j.notification_id))).all();if(n.length===0)return 0;let r=new Date().toISOString();return e.db.transaction(o=>{for(let a of n)o.insert(j).values({notification_id:a.id,user_id:t.userId,read_at:r}).onConflictDoNothing().run();}),n.length}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark all notifications read",n)}finally{e.close();}}};var Tn=50,xe=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{I(n.db,e);}catch(r){throw n.close(),r}return n}create(t){let e=this.openHandle(true);try{let n=new Date().toISOString(),r=[],o=t.map(a=>{let c=bt("sug");return r.push(c),{id:c,workspace_id:a.workspaceId,agent_id:a.agentId,task_id:a.taskId??null,type:a.type,status:a.status??"pending",payload:a.payload,applied_commit_sha:a.appliedCommitSha??null,created_at:n,updated_at:n}});return o.length>0&&e.db.insert(S).values(o).run(),{ids:r}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create agent suggestions",n)}finally{e.close();}}findLatestSet(t,e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=n.db.select({task_id:S.task_id}).from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e))).orderBy(desc(S.created_at)).limit(1).get();if(!r)return [];let o=r.task_id===null?isNull(S.task_id):eq(S.task_id,r.task_id);return n.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),o)).orderBy(asc(S.created_at)).all()}catch(r){throw new d("DB_ERROR","Failed to find latest agent suggestion set",r)}finally{n.close();}}findSetByTaskId(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),eq(S.task_id,n))).orderBy(asc(S.created_at)).all()}catch(o){throw new d("DB_ERROR","Failed to find agent suggestion set by task id",o)}finally{r.close();}}findById(t,e,n){if(!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),eq(S.id,n))).get()??null}catch(o){throw new d("DB_ERROR","Failed to find agent suggestion by id",o)}finally{r.close();}}updateStatus(t,e,n){let r=this.openHandle(true);try{let o={status:e,updated_at:new Date().toISOString()};return n!==void 0&&(o.applied_commit_sha=n),r.db.update(S).set(o).where(eq(S.id,t)).run().changes>0}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update agent suggestion status",o)}finally{r.close();}}listByAgent(t,e,n=Tn){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e))).orderBy(desc(S.created_at)).limit(n).all()}catch(o){throw new d("DB_ERROR","Failed to list agent suggestions",o)}finally{r.close();}}findDismissed(t,e,n=20){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),eq(S.status,"dismissed"))).orderBy(desc(S.updated_at)).limit(n).all()}catch(o){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",o)}finally{r.close();}}};export{xe as AgentSuggestionRepository,D as BaseSqliteRepository,Tn as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,Rn as DEFAULT_NOTIFICATION_CAP,bn as DEFAULT_NOTIFICATION_LIST_LIMIT,be as NotificationRepository,_e as ProjectRepository,d as RepositoryError,ye as RequestLogRepository,me as SpanRepository,he as TaskRepository,ke as ThreadBoxRepository,ge as ThreadRepository,we as ToolCallRepository,Ee as UsageLimitSnapshotRepository,Re as UsageReportRepository,pe as WorkspaceRepository,hn as calcBucketStart,w as openDrizzleDb,Mr as pushSchema,Ot as runMigrations,I as runMigrationsOnce,s as tasks};
|