@crewx/sdk 0.9.0-rc.65 → 0.9.0-rc.67
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/config/global-settings.d.ts +14 -0
- package/dist/esm/index.js +99 -92
- package/dist/esm/plugins/index.js +118 -111
- package/dist/esm/repository/index.js +141 -119
- package/dist/facade/Crewx.d.ts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +100 -93
- package/dist/local-server/base-url.d.ts +18 -0
- package/dist/local-server/index.d.ts +8 -0
- package/dist/local-server/opencode.d.ts +8 -0
- package/dist/local-server/probe.d.ts +3 -0
- package/dist/local-server/runtime.d.ts +26 -0
- package/dist/local-server/types.d.ts +43 -0
- package/dist/migrations/0016_fuzzy_hemingway.sql +14 -0
- package/dist/migrations/meta/0016_snapshot.json +2419 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/dist/plugins/index.js +118 -111
- package/dist/repository/db.d.ts +8 -0
- package/dist/repository/index.d.ts +7 -2
- package/dist/repository/index.js +141 -119
- package/dist/repository/task-log-migration.d.ts +74 -0
- package/dist/repository/task-log.repository.d.ts +44 -0
- package/dist/repository/task.repository.d.ts +6 -0
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/task-log-events.d.ts +119 -0
- package/dist/schema/tasks.d.ts +53 -0
- package/dist/types/index.d.ts +1 -0
- package/package.json +1 -1
|
@@ -1,47 +1,54 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as be from'path';import be__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as hn from'fs';import hn__default,{existsSync,mkdirSync,readFileSync,statfsSync,statSync}from'fs';import wr,{homedir}from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,asc,gt as gt$1,lt,or,notLike,like,inArray,gte,lte}from'drizzle-orm';import {randomUUID,createHash,randomBytes}from'crypto';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var qe=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var gr=()=>fileURLToPath(import.meta.url),fr=()=>be__default.dirname(gr()),y=fr();var N=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(wr.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(e,t,n){super(t),this.name="RepositoryError",this.code=e,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};var Ft=r=>{try{return hn.statSync(`${r}-wal`).size}catch{return 0}},zt=32*1024*1024;function k(r){let e=qe("better-sqlite3"),{drizzle:t}=qe("drizzle-orm/better-sqlite3"),n=new e(r);return n.exec("PRAGMA journal_mode = WAL"),n.exec(`PRAGMA journal_size_limit = ${zt}`),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),n.exec("PRAGMA analysis_limit = 400"),n.exec("PRAGMA optimize"),{db:t(n),runRaw:(o,s=[])=>n.prepare(o).run(...s),close:()=>n.close()}}function kr(r,e="TRUNCATE"){if(e!=="PASSIVE"&&e!=="TRUNCATE")throw new Error(`Unsupported journal reclaim mode: ${e}`);let t=qe("better-sqlite3"),n=Ft(r),o;try{o=new t(r),o.pragma("busy_timeout = 1000");let s=o.pragma(`wal_checkpoint(${e})`),a=Ft(r);return {busy:s[0]?.busy===1,walBytesBefore:n,walBytesAfter:a}}finally{o?.close();}}var Wt=new Set,yr={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 ft(r,e){return (r.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function br(r,e){if(e>0||!ft(r,"tasks"))return;let t=r.all("PRAGMA table_info(tasks)"),n=new Set(t.map(o=>o.name));for(let[o,s]of Object.entries(yr))n.has(o)||r.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var Rr={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"}};function Er(r,e,t){if(!ft(r,"__drizzle_migrations")||!ft(r,"tasks"))return;let n=r.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(n.map(a=>a.hash)),s=JSON.parse(readFileSync(be__default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=Rr[a.tag];if(!c)continue;let u=be__default.join(e,`${a.tag}.sql`);if(!existsSync(u))continue;let l=readFileSync(u,"utf-8"),p=createHash("sha256").update(l).digest("hex");if(o.has(p))continue;let _=r.all("PRAGMA table_info(tasks)"),g=new Set(_.map(m=>m.name));for(let[m,j]of Object.entries(c))g.has(m)||(r.run(`ALTER TABLE tasks ADD COLUMN ${m} ${j}`),g.add(m));}}function Sr(r,e,t){let n=r.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(n.map(a=>a.hash)),s=JSON.parse(readFileSync(be__default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=be__default.join(e,`${a.tag}.sql`);if(!existsSync(c))continue;let u=readFileSync(c,"utf-8"),l=createHash("sha256").update(u).digest("hex");if(o.has(l))continue;let p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,_=[],g;for(;(g=p.exec(u))!==null;)_.push({table:g[1],column:g[2]});if(_.length===0||!u.split(/-->\s*statement-breakpoint/).map(w=>w.trim()).filter(Boolean).every(w=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(w)))continue;_.every(({table:w,column:$})=>r.all(`PRAGMA table_info("${w}")`).some(K=>K.name===$))&&r.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${a.when})`);}}function Me(r){let{migrate:e}=qe("drizzle-orm/better-sqlite3/migrator"),{sql:t}=qe("drizzle-orm"),n=[be__default.join(y,"../migrations"),be__default.join(y,"migrations"),be__default.join(y,"../../../../drizzle/migrations"),be__default.join(process.cwd(),"drizzle/migrations")],o=n.find(l=>existsSync(be__default.join(l,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
2
2
|
${n.join(`
|
|
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
|
-
(${
|
|
3
|
+
`)}`);let s=r.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;s?.cnt&&(a=r.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),br(r,a),s?.cnt&&(Sr(r,o,t),Er(r,o,t)),e(r,{migrationsFolder:o});let u=(r.get(t`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 L(r,e){Wt.has(e)||(Me(r),Wt.add(e));}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 i=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"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),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)},r=>({log_storage_check:check("tasks_log_storage_ck",sql`${r.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(r.agent_id),idx_tasks_status:index("idx_tasks_status").on(r.status),idx_tasks_started_at:index("idx_tasks_started_at").on(r.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(r.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(r.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(r.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(r.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(r.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(r.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(r.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(r.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(r.workspace_id,r.started_at)}));var pe=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>i.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},r=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(r.task_id,r.seq)}));var f=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)},r=>({idx_threads_updated_at:index("idx_threads_updated_at").on(r.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(r.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(r.workspace_id,r.updated_at),idx_threads_title:index("idx_threads_title").on(r.title)}));var Se=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Se.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")},r=>({idx_spans_task_id:index("idx_spans_task_id").on(r.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(r.parent_span_id)}));var _e=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.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()},r=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(r.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(r.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(r.timestamp)}));var re=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>f.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()},r=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(r.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(r.thread_id,r.seq),uniq_thread_boxes_thread_seq:unique().on(r.thread_id,r.seq)}));var Ue=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")},r=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(r.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(r.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(r.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(r.partition_key)}));var F=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")},r=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(r.provider,r.account_ref,r.limit_window,r.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(r.limit_window,r.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(r.provider,r.limit_window,r.bucket_start)}));var Y=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")},r=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(r.workspace_id,r.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")},r=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(r.workspace_id,sql`${r.created_at} DESC`)})),B=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},r=>({pk:primaryKey({columns:[r.notification_id,r.user_id]})}));var v=sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},r=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(r.workspace_id,r.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(r.workspace_id,r.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()},r=>({idCheck:check("ui_instances_id_ck",sql`length(${r.id}) BETWEEN 5 AND 128 AND ${r.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${r.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${r.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${r.definition_hash}) = 64 AND ${r.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${r.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${r.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${r.domain_ref_json}) AND json_type(${r.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${r.state_json}) AND json_type(${r.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${r.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${r.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${r.granted_capabilities_json}) AND json_type(${r.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${r.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${r.updated_at} >= ${r.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(r.workspace_id,r.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")},r=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${r.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${r.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${r.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${r.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${r.actor_json}) AND json_type(${r.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${r.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${r.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${r.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${r.after_revision} IS NULL OR ${r.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${r.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${r.outcome} IS NULL OR ${r.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${r.input_json}) AND json_type(${r.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${r.result_json} IS NULL OR (json_valid(${r.result_json}) AND json_type(${r.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${r.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${r.settled_at} IS NULL OR ${r.settled_at} >= ${r.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
4
|
+
(${r.status} = 'requested' AND ${r.after_revision} IS NULL AND ${r.outcome} IS NULL AND ${r.settled_at} IS NULL)
|
|
5
5
|
OR
|
|
6
|
-
(${
|
|
7
|
-
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(
|
|
6
|
+
(${r.status} = 'settled' AND ${r.after_revision} IS NOT NULL AND ${r.outcome} IS NOT NULL AND ${r.settled_at} IS NOT NULL)
|
|
7
|
+
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(r.instance_id,r.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(r.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(r.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")},r=>({idCheck:check("projects_id_ck",sql`${r.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${r.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(${r.stages_json}) AND json_type(${r.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${r.stage_index} >= 1`)})),Z=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()},r=>({idCheck:check("project_criteria_id_ck",sql`${r.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${r.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${r.evidence_json}) AND json_type(${r.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(r.project_id,r.position)})),le=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()},r=>({idCheck:check("project_events_id_ck",sql`${r.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${r.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${r.payload_json}) AND json_type(${r.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(r.project_id,r.seq)}));function yt(r){let e=be.resolve(r);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(t,n)=>`${n.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function on(r){let e=yt(r);return createHash("sha256").update(e).digest("hex")}function dt(r){return r.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Et=class extends N{dbRoot;constructor(e={}){super(),this.dbRoot=e.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{Me(n.db);}catch(o){throw n.close(),o}return n}resolveSlug(e,t,n){let o=dt(basename(n)),a=`${dt(basename(dirname(n)))}-${o}`,c=[o,a];try{let u=l=>e.select({id:h.id}).from(h).where(and(eq(h.slug,l),ne(h.id,t))).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 o}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let e=this.openHandle(true);try{let t=e.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let o of t)if(o.slug.includes("/")){let s=dt(o.slug.replace(/\//g,"-"));e.db.update(h).set({slug:s,updated_at:new Date().toISOString()}).where(eq(h.id,o.id)).run(),n+=1;}return {updated:n,checked:t.length}}catch(t){throw new d("DB_ERROR","Failed to normalize legacy slugs",t)}finally{e.close();}}ensureRow(e,t){let{id:n,slug:o,name:s,workspacePath:a}=t,c=new Date().toISOString();e.insert(h).values({id:n,slug:o,name:s,workspace_path:a,is_active:1,created_at:c,updated_at:c}).onConflictDoNothing().run(),e.update(h).set({workspace_path:a,updated_at:c}).where(and(eq(h.id,n),isNull(h.workspace_path))).run();}registerWorkspace(e){let t=yt(e),n=this.openHandle(true);try{let o=on(t),s=basename(t),a=this.resolveSlug(n.db,o,t);return this.ensureRow(n.db,{id:o,slug:a,name:s,workspacePath:t}),{id:o,slug:a}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to register workspace",o)}finally{n.close();}}listProjects(e){if(!this.dbExists())return {rows:[],total:0};let t=this.openHandle(false);try{let n=e.isActive!==void 0?eq(h.is_active,e.isActive?1:0):void 0,o=t.db.select({count:sql`count(*)`}).from(h).where(n).get();return {rows:t.db.select().from(h).where(n).orderBy(desc(h.updated_at)).limit(e.limit).offset(e.offset).all(),total:o?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(h).where(eq(h.id,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{t.close();}}findAgentsByProject(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${e} AND agent_id IS NOT NULL ORDER BY agent_id`).map(o=>o.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{t.close();}}findThreadsByProject(e,t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let o=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${e}`);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
|
-
WHERE t.workspace_id = ${
|
|
10
|
+
WHERE t.workspace_id = ${e}
|
|
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(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`
|
|
12
|
+
LIMIT ${t.limit} OFFSET ${t.offset}`),total:o?.count??0}}catch(o){throw new d("DB_ERROR","Failed to find threads by project",o)}finally{n.close();}}findBySlug(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(h).where(eq(h.slug,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{t.close();}}slugExists(e,t){if(!this.dbExists())return false;let n=this.openHandle(false);try{let o=t?and(eq(h.slug,e),ne(h.id,t)):eq(h.slug,e);return !!n.db.select({id:h.id}).from(h).where(o).limit(1).get()}catch(o){throw new d("DB_ERROR","Failed to check slug",o)}finally{n.close();}}insert(e,t,n,o){let s=this.openHandle(true);try{let a=new Date().toISOString();s.db.insert(h).values({id:e,slug:t,name:n,workspace_path:o,is_active:1,created_at:a,updated_at:a}).run();let c=s.db.select().from(h).where(eq(h.id,e)).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(e,t,n){let o=this.openHandle(true);try{o.runRaw(`UPDATE workspaces SET ${t.join(", ")} WHERE id = ?`,n);let s=o.db.select().from(h).where(eq(h.id,e)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${e} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{o.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let e=this.openHandle(true);try{let t=e.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 o of t){let s=o.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(e.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(h.id,o.id)).run(),n+=1);}return {softDeleted:n,checked:t.length}}catch(t){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",t)}finally{e.close();}}delete(e){let t=this.openHandle(true);try{t.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${e}`),t.db.delete(h).where(eq(h.id,e)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{t.close();}}};var cn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function co(r){let e=randomBytes(r*2),t="";for(let n=0;n<e.length&&t.length<r;n++){let o=e[n];o<248&&(t+=cn[o%62]);}for(;t.length<r;)t+=cn[randomBytes(1)[0]%62];return t}function Ie(r){return `${r}_${co(8)}`}var mo=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),ho=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),wo=new Set(["pending","verifying","passed","failed"]),ko=new Set(["user","project_manager","system"]),yo=new Set(["task","wi","url"]),bo=/^\d{4}-\d{2}-\d{2}$/;function P(r){throw new d("VALIDATION",r)}function oe(r){throw new d("NOT_FOUND",r)}function M(r,e){(typeof r!="string"||r.trim().length===0)&&P(`${e} is required`);}function Ro(r){if(r==null)return;bo.test(r)||P("dueDate must use YYYY-MM-DD");let e=new Date(`${r}T00:00:00.000Z`);(Number.isNaN(e.getTime())||e.toISOString().slice(0,10)!==r)&&P("dueDate must be a valid calendar date");}function Eo(r){(!Array.isArray(r)||r.length===0)&&P("stages must contain at least one stage");let e=new Set;for(let t of r)M(t.key,"stage.key"),M(t.label,"stage.label"),e.has(t.key)&&P(`duplicate stage key: ${t.key}`),e.add(t.key);}function So(r){Array.isArray(r)||P("criteria must be an array");for(let e of r)M(e,"criterion.statement");}function Fe(r={}){let e=r.actorType??"system";ko.has(e)||P(`invalid actorType: ${String(e)}`);let t=r.actorId??null;return (e==="user"||e==="project_manager")&&(!t||t.trim().length===0)&&P(`actorId is required for ${e}`),{actorType:e,actorId:t}}function fn(r,e){let t=r??{};if((t===null||typeof t!="object"||Array.isArray(t))&&P("event payload must be a JSON object"),e==="accepted")for(let n of ["remainingRisks","nextPlan","lessons","evidenceRefs"])(!Object.prototype.hasOwnProperty.call(t,n)||t[n]===void 0)&&P(`accepted payload requires ${n}`);try{return JSON.stringify(t)}catch(n){throw new d("VALIDATION","event payload must be JSON serializable",n)}}function To(r){return Array.isArray(r)||P("evidence must be an array"),r.map(e=>((!e||typeof e!="object")&&P("evidence item must be an object"),yo.has(e.kind)||P(`invalid evidence kind: ${String(e.kind)}`),M(e.ref,"evidence.ref"),e.label!==void 0&&typeof e.label!="string"&&P("evidence.label must be a string"),e.label===void 0?{kind:e.kind,ref:e.ref}:{kind:e.kind,ref:e.ref,label:e.label}))}function gn(r){try{let e=JSON.parse(r);if(!Array.isArray(e))throw new Error("not an array");return e}catch(e){throw new d("DB_ERROR","Project stages JSON is invalid",e)}}function mn(r){return M(r.projectId,"projectId"),M(r.title,"title"),mo.has(r.type)||P(`invalid project event type: ${String(r.type)}`),{...Fe(r),payloadJson:fn(r.payload,r.type)}}function $e(r,e,t){let n=mn(e);r.select({id:x.id}).from(x).where(eq(x.id,e.projectId)).get()||oe(`Project ${e.projectId} not found`);let s=r.select({maxSeq:sql`COALESCE(MAX(${le.seq}), 0)`}).from(le).where(eq(le.project_id,e.projectId)).get()?.maxSeq??0,a=Ie("pje");r.insert(le).values({id:a,project_id:e.projectId,seq:s+1,actor_type:n.actorType,actor_id:n.actorId,type:e.type,title:e.title,summary:e.summary??null,payload_json:n.payloadJson,created_at:t}).run();let c=r.select().from(le).where(eq(le.id,a)).get();if(!c)throw new d("DB_ERROR","Event insert did not return a row");return c}var St=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new d("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}getDetailFromHandle(e,t){let n=e.db.select().from(x).where(eq(x.id,t)).get();if(!n)return;let o=e.db.select().from(Z).where(eq(Z.project_id,t)).orderBy(asc(Z.position)).all();return {...n,stages:gn(n.stages_json),criteria:o}}getDetailOrThrow(e){let t=this.getProject(e);return t||oe(`Project ${e} not found`),t}createProject(e){M(e.workspaceId,"workspaceId"),M(e.name,"name"),M(e.outcome,"outcome"),Ro(e.dueDate),Eo(e.stages),So(e.criteria);let t=Ie("prj"),n=new Date().toISOString(),o=this.openHandle(true);try{o.db.transaction(s=>{s.insert(x).values({id:t,workspace_id:e.workspaceId,name:e.name,outcome:e.outcome,due_date:e.dueDate??null,scene:"planning",stages_json:JSON.stringify(e.stages),stage_index:1,created_at:n,updated_at:n,accepted_at:null,archived_at:null}).run(),e.criteria.forEach((a,c)=>{s.insert(Z).values({id:Ie("pjc"),project_id:t,position:c+1,statement:a,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:n,updated_at:n}).run();}),$e(s,{projectId:t,actorType:"system",type:"created",title:"Project created",payload:{}},n);});}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to create project",s)}finally{o.close();}return this.getDetailOrThrow(t)}getProject(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return this.getDetailFromHandle(t,e)}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to get project",n)}finally{t.close();}}listProjectsByWorkspace(e,t={}){if(M(e,"workspaceId"),!this.dbExists())return [];let n=this.openHandle(false);try{let o=t.includeArchived?eq(x.workspace_id,e):and(eq(x.workspace_id,e),isNull(x.archived_at));return n.db.select({id:x.id}).from(x).where(o).orderBy(desc(x.updated_at),desc(x.created_at)).all().map(a=>this.getDetailFromHandle(n,a.id)).filter(a=>a!==void 0)}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to list projects",o)}finally{n.close();}}archiveProject(e){M(e,"projectId");let t=this.openHandle(true);try{t.db.update(x).set({archived_at:new Date().toISOString()}).where(eq(x.id,e)).run().changes===0&&oe(`Project ${e} not found`);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to archive project",n)}finally{t.close();}return this.getDetailOrThrow(e)}setScene(e,t,n={}){M(e,"projectId"),ho.has(t)||P(`invalid project scene: ${String(t)}`);let o=Fe(n),s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let u=c.select().from(x).where(eq(x.id,e)).get();u||oe(`Project ${e} not found`),c.update(x).set({scene:t,updated_at:s}).where(eq(x.id,e)).run(),$e(c,{projectId:e,...o,type:"scene_changed",title:"Project scene changed",payload:{before:u.scene,after:t}},s);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to set project scene",c)}finally{a.close();}return this.getDetailOrThrow(e)}setStageIndex(e,t,n={}){M(e,"projectId"),Number.isInteger(t)||P("stage index must be an integer");let o=Fe(n),s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let u=c.select().from(x).where(eq(x.id,e)).get();u||oe(`Project ${e} not found`);let l=gn(u.stages_json);(t<1||t>l.length)&&P("stage index is outside the project stages"),c.update(x).set({stage_index:t,updated_at:s}).where(eq(x.id,e)).run(),$e(c,{projectId:e,...o,type:"stage_advanced",title:"Project stage advanced",payload:{before:u.stage_index,after:t}},s);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to set project stage",c)}finally{a.close();}return this.getDetailOrThrow(e)}setCriterionVerify(e,t,n,o={}){let s=typeof e=="string"?{projectId:typeof n=="string"?e:void 0,criterionId:typeof n=="string"?t:e,verifyStatus:typeof n=="string"?n:t,...typeof n=="string"?o:n}:e,a=s.verifyStatus??s.status;(!a||!wo.has(a))&&P(`invalid criterion status: ${String(a)}`),M(s.criterionId,"criterionId");let c=Fe(s),u=new Date().toISOString(),l=this.openHandle(true),p;try{l.db.transaction(g=>{let m=g.select().from(Z).where(eq(Z.id,s.criterionId)).get();m||oe(`Criterion ${s.criterionId} not found`),p=m.project_id,s.projectId&&s.projectId!==m.project_id&&oe(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(Z).set({verify_status:a,verified_at:a==="passed"?u:null,updated_at:u}).where(eq(Z.id,s.criterionId)).run(),$e(g,{projectId:m.project_id,...c,type:"criterion_verified",title:"Criterion verification updated",payload:{criterionId:s.criterionId,status:a}},u);});}catch(g){throw g instanceof d?g:new d("DB_ERROR","Failed to set criterion verification",g)}finally{l.close();}let _=p?this.getProject(p)?.criteria.find(g=>g.id===s.criterionId):void 0;return _||oe(`Criterion ${s.criterionId} not found`),_}setCriterionEvidence(e,t,n,o={}){let s=typeof e=="string"?{projectId:Array.isArray(n)?e:void 0,criterionId:Array.isArray(n)?t:e,evidence:Array.isArray(n)?n:t,...Array.isArray(n)?o:n}:e;M(s.criterionId,"criterionId");let a=To(s.evidence),c=Fe(s),u=new Date().toISOString(),l=this.openHandle(true),p;try{l.db.transaction(g=>{let m=g.select().from(Z).where(eq(Z.id,s.criterionId)).get();m||oe(`Criterion ${s.criterionId} not found`),p=m.project_id,s.projectId&&s.projectId!==m.project_id&&oe(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(Z).set({evidence_json:JSON.stringify(a),updated_at:u}).where(eq(Z.id,s.criterionId)).run(),$e(g,{projectId:m.project_id,...c,type:"criterion_verified",title:"Criterion evidence updated",payload:{criterionId:s.criterionId,evidence:a}},u);});}catch(g){throw g instanceof d?g:new d("DB_ERROR","Failed to set criterion evidence",g)}finally{l.close();}let _=p?this.getProject(p)?.criteria.find(g=>g.id===s.criterionId):void 0;return _||oe(`Criterion ${s.criterionId} not found`),_}appendEvent(e,t){let n=typeof e=="string"?{...t,projectId:e}:e;mn(n);let o=new Date().toISOString(),s=this.openHandle(true),a;try{s.db.transaction(c=>{a=$e(c,n,o);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to append project event",c)}finally{s.close();}if(!a)throw new d("DB_ERROR","Event append did not return a row");return a}listEvents(e,t={}){if(M(e,"projectId"),t.afterSeq!==void 0&&(!Number.isInteger(t.afterSeq)||t.afterSeq<0)&&P("afterSeq must be a non-negative integer"),t.limit!==void 0&&(!Number.isInteger(t.limit)||t.limit<1)&&P("limit must be a positive integer"),!this.dbExists())return [];let n=this.openHandle(false);try{let o=[eq(le.project_id,e)];t.afterSeq!==void 0&&o.push(gt$1(le.seq,t.afterSeq));let s=n.db.select().from(le).where(and(...o)).orderBy(asc(le.seq));return t.limit!==void 0&&(s=s.limit(t.limit)),s.all()}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to list project events",o)}finally{n.close();}}acceptProject(e,t){M(e,"projectId");let n=Fe(t),o={remainingRisks:t.remainingRisks,nextPlan:t.nextPlan,lessons:t.lessons,evidenceRefs:t.evidenceRefs};fn(o,"accepted");let s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{c.select({id:x.id}).from(x).where(eq(x.id,e)).get()||oe(`Project ${e} not found`),c.update(x).set({scene:"accepted",accepted_at:s,updated_at:s}).where(eq(x.id,e)).run(),$e(c,{projectId:e,...n,type:"accepted",title:"Project accepted",payload:o},s);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to accept project",c)}finally{a.close();}return this.getDetailOrThrow(e)}};var kn=[h,i,f,Se,_e,re,Ue];function No(){return be__default.join(wr.homedir(),".crewx","crewx.db")}function Do(r){if(!hn__default.existsSync(r))return null;let e=Math.floor(Date.now()/1e3),t=`${r}.bak-${e}`;return hn__default.copyFileSync(r,t),t}function yn(r){let e=r.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(e.map(t=>t.name))}function Io(r){return r==null||typeof r=="object"&&"queryChunks"in r?null:typeof r=="number"?String(r):typeof r=="boolean"?r?"1":"0":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:String(r)}function Ao(r){let e=r.getSQLType(),t=`"${r.name}" ${e}`,n=Io(r.default);return n!==null&&(t+=` DEFAULT ${n}`),r.notNull&&(t+=" NOT NULL"),t}function Co(r,e){let t=e?.dbPath??No(),n=e?.force??false,o=e?.dryRun??false,s=o?null:Do(t);if(n&&!o)try{r.run("DELETE FROM __drizzle_migrations");}catch{}let a=yn(r);if(!o)try{Me(r);}catch(_){let g=_ instanceof Error?`${_.message} ${_.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw _}let c,u;o?(c=kn.map(g=>getTableConfig(g).name).filter(g=>!a.has(g)),u=a):(u=yn(r),c=[...u].filter(_=>!a.has(_)));let l=[],p=[];for(let _ of kn){let g=getTableConfig(_),m=g.name;if(!u.has(m))continue;let j=r.all(`PRAGMA table_info("${m}")`),w=new Set(j.map(T=>T.name)),$=new Set(g.columns.map(T=>T.name));for(let T of g.columns)if(!w.has(T.name)){if(!o){let K=Ao(T);r.run(`ALTER TABLE "${m}" ADD COLUMN ${K}`);}l.push({table:m,column:T.name});}for(let T of j)$.has(T.name)||p.push(`${m}.${T.name} exists in DB but not in schema (untouched)`);}return {created:c,altered:l,warnings:p,backupPath:s}}function bn(r){let e=r.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let t=e.lastIndexOf("/");return t>=0&&(e=e.slice(t+1)),e=e.replace(/-\d{8}$/,""),e}function vn(r,e){let t=e===void 0?"":` at index ${e}`;if(!r||typeof r!="object")throw new d("VALIDATION",`Task log entry${t} must be an object`);if(typeof r.timestamp!="string"||typeof r.level!="string"||typeof r.message!="string")throw new d("VALIDATION",`Task log entry${t} must contain string timestamp, level, and message fields`);return {timestamp:r.timestamp,level:r.level,message:r.message}}function Sn(r,e){if(e===null||e.trim()==="")return [];let t;try{t=JSON.parse(e);}catch(n){throw new d("DB_ERROR",`Malformed legacy task logs: ${r}`,n)}if(!Array.isArray(t))throw new d("DB_ERROR",`Malformed legacy task logs: ${r} (expected an array)`);try{return t.map((n,o)=>vn(n,o))}catch(n){throw n instanceof d?new d("DB_ERROR",`Malformed legacy task logs: ${r}`,n):n}}function xn(r){if(r.log_storage!=="blob"&&r.log_storage!=="events")throw new d("DB_ERROR",`Invalid task log storage for task: ${r.id}`);if(!Number.isInteger(r.last_log_seq)||r.last_log_seq<0)throw new d("DB_ERROR",`Invalid task log sequence for task: ${r.id}`);if(!Number.isInteger(r.log_revision)||r.log_revision<0)throw new d("DB_ERROR",`Invalid task log revision for task: ${r.id}`);return r.log_storage}function Tn(r){return {taskId:r.id,source:xn(r),revision:r.log_revision,lastSeq:r.last_log_seq}}function Mo(r){if(!Number.isInteger(r)||r<0)throw new d("VALIDATION","Task log tail limit must be a non-negative integer")}var Ye=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}findStateRow(e,t){return e.db.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get()}findStateRowInTransaction(e,t){return e.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get()}requireStateRowInTransaction(e,t){let n=this.findStateRowInTransaction(e,t);if(!n)throw new d("NOT_FOUND",`Task not found: ${t}`);return n}appendLog(e,t){return this.appendLogs(e,[t])}appendLogs(e,t){let n=t.map((s,a)=>vn(s,a));if(n.length===0){let s=this.getLogState(e);if(!s)throw new d("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(a=>{let c=this.requireStateRowInTransaction(a,e),u=xn(c);if(u==="blob"){let g=Sn(e,c.logs);if(a.update(i).set({logs:JSON.stringify([...g,...n]),log_revision:sql`${i.log_revision} + 1`}).where(eq(i.id,e)).run().changes!==1)throw new d("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:u,revision:c.log_revision+1,lastSeq:c.last_log_seq}}let l=c.last_log_seq+1,p=c.last_log_seq+n.length;if(a.insert(pe).values(n.map((g,m)=>({task_id:e,seq:l+m,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),a.update(i).set({last_log_seq:p,log_revision:sql`${i.log_revision} + 1`}).where(eq(i.id,e)).run().changes!==1)throw new d("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:u,revision:c.log_revision+1,lastSeq:p}},{behavior:"immediate"})}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let t=this.openHandle(false);try{let n=this.findStateRow(t,e);return n?Tn(n):void 0}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to read task log state",n)}finally{t.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,t){return Mo(t),this.readLogsInternal(e,t)}readTail(e,t){return this.readLogsTail(e,t)}readLogsInternal(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let a=Tn(s);if(a.source==="blob"){let p=Sn(e,s.logs);return {...a,entries:t===void 0?p:p.slice(Math.max(0,p.length-t))}}let c=o.select({seq:pe.seq,timestamp:pe.timestamp,level:pe.level,message:pe.message}).from(pe).where(eq(pe.task_id,e)).orderBy(t===void 0?asc(pe.seq):desc(pe.seq)),l=(t===void 0?c.all():c.limit(t).all()).map(({timestamp:p,level:_,message:g})=>({timestamp:p,level:_,message:g}));return t!==void 0&&l.reverse(),{...a,entries:l}},{behavior:"deferred"})}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to read task logs",o)}finally{n.close();}}};var Ce="2026-05-09",Ko="0.8.9-rc.13",Le=10,Pe=parseInt(Ko.split("rc.")[1]);function Nn(){let r=sql`
|
|
13
13
|
CASE
|
|
14
|
-
WHEN ${
|
|
15
|
-
WHEN ${
|
|
16
|
-
WHEN ${
|
|
17
|
-
WHEN ${
|
|
18
|
-
WHEN ${
|
|
19
|
-
WHEN ${
|
|
20
|
-
WHEN ${
|
|
14
|
+
WHEN ${i.model} LIKE 'claude-%' OR ${i.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
15
|
+
WHEN ${i.model} LIKE 'gpt-%' OR ${i.model} LIKE 'codex-%' THEN 'codex'
|
|
16
|
+
WHEN ${i.model} LIKE 'gemini-%' THEN 'gemini'
|
|
17
|
+
WHEN ${i.model} LIKE 'grok-%' THEN 'grok'
|
|
18
|
+
WHEN ${i.model} LIKE 'zai-%' OR ${i.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
19
|
+
WHEN ${i.model} LIKE 'minimax/%' THEN 'minimax'
|
|
20
|
+
WHEN ${i.model} LIKE 'qwen%' THEN 'qwen'
|
|
21
21
|
ELSE 'unknown'
|
|
22
22
|
END
|
|
23
|
-
`,
|
|
23
|
+
`,e=sql`json_extract(${i.metadata}, '$.provider')`,t=sql`trim(${e})`,n=sql`substr(${t}, 1, instr(${t}, '/') - 1)`,o=sql`
|
|
24
24
|
CASE
|
|
25
|
-
WHEN instr(${
|
|
25
|
+
WHEN instr(${t}, '/') > 0
|
|
26
26
|
AND ${n} IN ('cli', 'acp', 'api', 'plugin', 'remote')
|
|
27
|
-
THEN substr(${
|
|
28
|
-
ELSE ${
|
|
27
|
+
THEN substr(${t}, instr(${t}, '/') + 1)
|
|
28
|
+
ELSE ${t}
|
|
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(${
|
|
37
|
-
WHEN ${
|
|
38
|
-
WHEN trim(${
|
|
39
|
-
ELSE ${
|
|
32
|
+
WHEN ${i.metadata} IS NULL THEN ${r}
|
|
33
|
+
WHEN json_valid(${i.metadata}) = 0 THEN 'unknown'
|
|
34
|
+
WHEN json_type(${i.metadata}, '$') IS NOT 'object' THEN 'unknown'
|
|
35
|
+
WHEN json_type(${i.metadata}, '$.provider') IS NULL THEN ${r}
|
|
36
|
+
WHEN json_type(${i.metadata}, '$.provider') IS NOT 'text' THEN 'unknown'
|
|
37
|
+
WHEN ${t} = '' THEN 'unknown'
|
|
38
|
+
WHEN trim(${o}) = '' THEN 'unknown'
|
|
39
|
+
ELSE ${o}
|
|
40
40
|
END
|
|
41
|
-
`}var
|
|
41
|
+
`}var Go=new Set(["workflow","mcp"]),Dn=600*1e3,vt=class extends N{dbPath;taskLogRepository;pidNullObservedSince=new Map;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Ye({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}startTask(e){let t=this.openHandle(true);try{let n={id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,project_id:e.projectId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},o=s=>{t.db.insert(i).values(s).onConflictDoUpdate({target:i.id,set:{pid:sql`COALESCE(excluded.pid, ${i.pid})`},setWhere:eq(i.status,"running")}).run();};try{o(n);}catch(s){let a=s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s);if(!/log_storage/i.test(a)||!/no such column|no column named/i.test(a))throw s;t.runRaw(`INSERT INTO tasks (
|
|
42
|
+
id, agent_id, prompt, mode, status, started_at, pid,
|
|
43
|
+
parent_task_id, caller_agent_id, trace_id, command, metadata,
|
|
44
|
+
workspace_id, project_id, platform, crewx_version, thread_id,
|
|
45
|
+
model, rendered_prompt, coding_agent_command
|
|
46
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
47
|
+
ON CONFLICT(id) DO UPDATE SET pid = COALESCE(excluded.pid, tasks.pid)
|
|
48
|
+
WHERE tasks.status = 'running'`,[n.id,n.agent_id,n.prompt,n.mode,n.status,n.started_at,n.pid,n.parent_task_id,n.caller_agent_id,n.trace_id,n.command,n.metadata,n.workspace_id,n.project_id,n.platform,n.crewx_version,n.thread_id,n.model,n.rendered_prompt,n.coding_agent_command]);}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{t.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(eq(i.project_id,e)).orderBy(desc(i.started_at)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to list tasks by project",n)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{let n=e.runEpoch??null;t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
42
49
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
43
50
|
model=COALESCE(?, model)
|
|
44
|
-
WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[
|
|
51
|
+
WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{t.close();}}appendLog(e,t){this.taskLogRepository.appendLog(e,t);}appendLogs(e,t){this.taskLogRepository.appendLogs(e,t);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,t){return this.taskLogRepository.readLogsTail(e,t)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(i).where(eq(i.status,"running")).orderBy(desc(i.started_at)).all()}catch(t){throw new d("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(i).orderBy(desc(i.started_at)).limit(100).all()}catch(t){throw new d("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(i).where(eq(i.id,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let n=t.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(eq(i.id,e)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return t.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(i.id,e),eq(i.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{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:i.id,pid:i.pid,platform:i.platform,run_epoch:i.run_epoch}).from(i).where(eq(i.status,"running")).all(),n=Date.now(),o=new Set,s=0;for(let a of t){if(a.pid){let l=!1;try{process.kill(a.pid,0),l=!0;}catch{}l||(e.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(i.id,a.id),eq(i.status,"running"))).run(),s++);continue}if(Go.has(a.platform??"cli"))continue;let c=`${a.id}:${a.run_epoch??0}`;o.add(c);let u=this.pidNullObservedSince.get(c);if(u===void 0){this.pidNullObservedSince.set(c,n);continue}n-u>=Dn&&(e.db.update(i).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(i.id,a.id),eq(i.status,"running"))).run(),s++,this.pidNullObservedSince.delete(c));}for(let a of Array.from(this.pidNullObservedSince.keys()))o.has(a)||this.pidNullObservedSince.delete(a);return s}finally{e.close();}}reapRunningWorkflowTasks(e=Dn){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let n=new Date(Date.now()-e).toISOString();return t.db.update(i).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(i.status,"running"),eq(i.platform,"workflow"),isNull(i.pid),lt(i.started_at,n),or(isNull(i.metadata),and(notLike(i.metadata,'%"kind":"workflow_card"%'),notLike(i.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{t.close();}}findTaskStatus(e,t){let n=this.resolveDbPaths();for(let o of n){if(!existsSync(o))continue;let s=k(o);try{let a=t?eq(i.workspace_id,t):void 0,c=a?and(eq(i.id,e),a):eq(i.id,e),u=s.db.select().from(i).where(c).limit(1).get()??void 0;if(!u){let l=or(eq(i.thread_id,e),and(isNull(i.thread_id),like(i.command,`%--thread=${e}%`))),p=a?and(l,a):l;u=s.db.select().from(i).where(p).orderBy(desc(i.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{s.close();}}}findChildTasks(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!existsSync(a))continue;let c=k(a);try{let u=t?and(eq(i.parent_task_id,e),eq(i.workspace_id,t)):eq(i.parent_task_id,e),l=c.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(p));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{c.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(e?sql`
|
|
45
52
|
SELECT
|
|
46
53
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
47
54
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -49,7 +56,7 @@ ${n.join(`
|
|
|
49
56
|
COALESCE(SUM(cost_usd), 0) AS cost_usd,
|
|
50
57
|
COUNT(*) AS task_count
|
|
51
58
|
FROM tasks
|
|
52
|
-
WHERE workspace_id = ${
|
|
59
|
+
WHERE workspace_id = ${e}
|
|
53
60
|
GROUP BY workspace_id
|
|
54
61
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
55
62
|
`:sql`
|
|
@@ -62,7 +69,7 @@ ${n.join(`
|
|
|
62
69
|
FROM tasks
|
|
63
70
|
GROUP BY workspace_id
|
|
64
71
|
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{
|
|
72
|
+
`)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{t.close();}}getThreadTokenUsage(e,t){let n=this.resolveDbPaths(),o=new Set,s=0,a=0,c=0;for(let u of n){if(!existsSync(u))continue;let l=k(u);try{let p=or(eq(i.thread_id,e),and(isNull(i.thread_id),like(i.command,`%--thread=${e}%`))),_=t?and(p,eq(i.workspace_id,t)):p,g=l.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(_).all();for(let m of g)o.has(m.id)||(o.add(m.id),s+=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:s,outputTokens:a,costUsd:c}}findTasksByThread(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!existsSync(a))continue;let c=k(a);try{let u=or(eq(i.thread_id,e),and(isNull(i.thread_id),like(i.command,`%--thread=${e}%`))),l=t?and(u,eq(i.workspace_id,t)):u,p=c.db.select().from(i).where(l).orderBy(asc(i.started_at)).all();for(let _ of p)o.has(_.id)||(o.add(_.id),s.push(_));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{c.close();}}return s}parseWorkflowCardMetadata(e){if(!e)return {};try{let t=JSON.parse(e);return {kind:typeof t.kind=="string"?t.kind:void 0,workflowRunId:typeof t.workflowRunId=="string"?t.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let t of this.resolveDbPaths()){if(!existsSync(t))continue;let n=k(t);try{e.push(...n.db.select({id:i.id,agent_id:i.agent_id,thread_id:i.thread_id,workspace_id:i.workspace_id,platform:i.platform,status:i.status,error:i.error,completed_at:i.completed_at,duration_ms:i.duration_ms,started_at:i.started_at,metadata:i.metadata}).from(i).where(and(eq(i.platform,"workflow"),or(like(i.metadata,'%"kind":"workflow_card"%'),like(i.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(i.started_at)).all());}catch(o){throw new d("DB_ERROR","Failed to find workflow parent tasks",o)}finally{n.close();}}return e}batchFetchWorkflowCards(e,t){let n=new Map;if(e.length===0)return n;let o=new Set(e),s=new Map,a=t?eq(i.workspace_id,t):void 0,c=(u,l)=>{if(!u)return;let p=s.get(u);if(p&&l.started_at<=p)return;let _=this.parseWorkflowCardMetadata(l.metadata);_.kind!=="workflow_card"&&_.kind!=="workflow_ui_instance"||(s.set(u,l.started_at),n.set(u,{taskId:l.id,workflowRunId:_.workflowRunId,raw:l.result??void 0}));};for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let l=k(u);try{let p=and(inArray(i.thread_id,e),or(like(i.metadata,'%"kind":"workflow_card"%'),like(i.metadata,'%"kind":"workflow_ui_instance"%'))),_=l.db.select({id:i.id,thread_id:i.thread_id,metadata:i.metadata,result:i.result,started_at:i.started_at}).from(i).where(a?and(p,a):p).all();for(let j of _)c(j.thread_id,j);let g=and(isNull(i.thread_id),or(like(i.metadata,'%"kind":"workflow_card"%'),like(i.metadata,'%"kind":"workflow_ui_instance"%'))),m=l.db.select({id:i.id,command:i.command,metadata:i.metadata,result:i.result,started_at:i.started_at}).from(i).where(a?and(g,a):g).all();for(let j of m){let w=this.extractThreadIdFromCommand(j.command);!w||!o.has(w)||c(w,j);}}catch(p){throw new d("DB_ERROR","Failed to batch fetch workflow cards",p)}finally{l.close();}}return n}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let t=this.openHandle(false);try{let n=[];e.workspaceId&&n.push(eq(i.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&n.push(inArray(i.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&n.push(inArray(i.status,s));let a=e.q??e.search;a&&n.push(like(i.prompt,`%${a}%`)),e.from&&n.push(gte(i.started_at,e.from)),e.to&&n.push(lt(i.started_at,e.to));let c=n.length>0?and(...n):void 0,u=t.db.select({count:sql`count(*)`}).from(i).where(c).get(),l=(e.sortDir??"DESC")==="ASC"?asc(i.started_at):desc(i.started_at);return {rows:t.db.select().from(i).where(c).orderBy(l).limit(e.limit).offset(e.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{t.close();}}getAgentUsage(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.all(n?sql`
|
|
66
73
|
SELECT
|
|
67
74
|
t.agent_id,
|
|
68
75
|
t.workspace_id,
|
|
@@ -70,11 +77,11 @@ ${n.join(`
|
|
|
70
77
|
COALESCE(SUM(
|
|
71
78
|
COALESCE(t.input_tokens, 0)
|
|
72
79
|
+ CASE
|
|
73
|
-
WHEN t.started_at >= ${
|
|
80
|
+
WHEN t.started_at >= ${Ce}
|
|
74
81
|
AND (
|
|
75
82
|
t.crewx_version IS NULL
|
|
76
83
|
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, ${
|
|
84
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Le}) AS INTEGER) < ${Pe})
|
|
78
85
|
)
|
|
79
86
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
80
87
|
ELSE 0
|
|
@@ -85,19 +92,19 @@ ${n.join(`
|
|
|
85
92
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
86
93
|
FROM tasks t
|
|
87
94
|
WHERE t.status IN ('completed', 'success')
|
|
88
|
-
AND t.started_at >= ${
|
|
89
|
-
AND t.started_at < ${
|
|
95
|
+
AND t.started_at >= ${e}
|
|
96
|
+
AND t.started_at < ${t}
|
|
90
97
|
AND t.workspace_id = ${n}
|
|
91
98
|
GROUP BY t.agent_id, t.workspace_id
|
|
92
99
|
ORDER BY (
|
|
93
100
|
COALESCE(SUM(
|
|
94
101
|
COALESCE(t.input_tokens, 0)
|
|
95
102
|
+ CASE
|
|
96
|
-
WHEN t.started_at >= ${
|
|
103
|
+
WHEN t.started_at >= ${Ce}
|
|
97
104
|
AND (
|
|
98
105
|
t.crewx_version IS NULL
|
|
99
106
|
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, ${
|
|
107
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Le}) AS INTEGER) < ${Pe})
|
|
101
108
|
)
|
|
102
109
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
103
110
|
ELSE 0
|
|
@@ -113,11 +120,11 @@ ${n.join(`
|
|
|
113
120
|
COALESCE(SUM(
|
|
114
121
|
COALESCE(t.input_tokens, 0)
|
|
115
122
|
+ CASE
|
|
116
|
-
WHEN t.started_at >= ${
|
|
123
|
+
WHEN t.started_at >= ${Ce}
|
|
117
124
|
AND (
|
|
118
125
|
t.crewx_version IS NULL
|
|
119
126
|
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, ${
|
|
127
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Le}) AS INTEGER) < ${Pe})
|
|
121
128
|
)
|
|
122
129
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
123
130
|
ELSE 0
|
|
@@ -128,18 +135,18 @@ ${n.join(`
|
|
|
128
135
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
129
136
|
FROM tasks t
|
|
130
137
|
WHERE t.status IN ('completed', 'success')
|
|
131
|
-
AND t.started_at >= ${
|
|
132
|
-
AND t.started_at < ${
|
|
138
|
+
AND t.started_at >= ${e}
|
|
139
|
+
AND t.started_at < ${t}
|
|
133
140
|
GROUP BY t.agent_id, t.workspace_id
|
|
134
141
|
ORDER BY (
|
|
135
142
|
COALESCE(SUM(
|
|
136
143
|
COALESCE(t.input_tokens, 0)
|
|
137
144
|
+ CASE
|
|
138
|
-
WHEN t.started_at >= ${
|
|
145
|
+
WHEN t.started_at >= ${Ce}
|
|
139
146
|
AND (
|
|
140
147
|
t.crewx_version IS NULL
|
|
141
148
|
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, ${
|
|
149
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Le}) AS INTEGER) < ${Pe})
|
|
143
150
|
)
|
|
144
151
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
145
152
|
ELSE 0
|
|
@@ -147,18 +154,18 @@ ${n.join(`
|
|
|
147
154
|
), 0)
|
|
148
155
|
+ COALESCE(SUM(t.output_tokens), 0)
|
|
149
156
|
) 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(
|
|
157
|
+
`).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(s){throw new d("DB_ERROR","Failed to get agent usage",s)}finally{o.close();}}getAgentUsageTrendRaw(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.all(n?sql`
|
|
151
158
|
SELECT
|
|
152
159
|
date(t.started_at) AS date,
|
|
153
160
|
t.agent_id,
|
|
154
161
|
COALESCE(SUM(
|
|
155
162
|
COALESCE(t.input_tokens, 0)
|
|
156
163
|
+ CASE
|
|
157
|
-
WHEN t.started_at >= ${
|
|
164
|
+
WHEN t.started_at >= ${Ce}
|
|
158
165
|
AND (
|
|
159
166
|
t.crewx_version IS NULL
|
|
160
167
|
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, ${
|
|
168
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Le}) AS INTEGER) < ${Pe})
|
|
162
169
|
)
|
|
163
170
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
164
171
|
ELSE 0
|
|
@@ -169,8 +176,8 @@ ${n.join(`
|
|
|
169
176
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
170
177
|
FROM tasks t
|
|
171
178
|
WHERE t.status IN ('completed', 'success')
|
|
172
|
-
AND t.started_at >= ${
|
|
173
|
-
AND t.started_at < ${
|
|
179
|
+
AND t.started_at >= ${e}
|
|
180
|
+
AND t.started_at < ${t}
|
|
174
181
|
AND t.workspace_id = ${n}
|
|
175
182
|
GROUP BY date(t.started_at), t.agent_id
|
|
176
183
|
ORDER BY date(t.started_at) ASC
|
|
@@ -181,11 +188,11 @@ ${n.join(`
|
|
|
181
188
|
COALESCE(SUM(
|
|
182
189
|
COALESCE(t.input_tokens, 0)
|
|
183
190
|
+ CASE
|
|
184
|
-
WHEN t.started_at >= ${
|
|
191
|
+
WHEN t.started_at >= ${Ce}
|
|
185
192
|
AND (
|
|
186
193
|
t.crewx_version IS NULL
|
|
187
194
|
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, ${
|
|
195
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Le}) AS INTEGER) < ${Pe})
|
|
189
196
|
)
|
|
190
197
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
191
198
|
ELSE 0
|
|
@@ -196,78 +203,93 @@ ${n.join(`
|
|
|
196
203
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
197
204
|
FROM tasks t
|
|
198
205
|
WHERE t.status IN ('completed', 'success')
|
|
199
|
-
AND t.started_at >= ${
|
|
200
|
-
AND t.started_at < ${
|
|
206
|
+
AND t.started_at >= ${e}
|
|
207
|
+
AND t.started_at < ${t}
|
|
201
208
|
GROUP BY date(t.started_at), t.agent_id
|
|
202
209
|
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(${
|
|
210
|
+
`).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(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(and(eq(i.id,e),eq(i.workspace_id,t))).limit(1).get()??void 0}catch(o){throw new d("DB_ERROR","Failed to find task for stop",o)}finally{n.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let t=this.openHandle(false);try{return t.db.select({id:i.id,thread_id:i.thread_id,status:i.status,result:i.result,error:i.error,started_at:i.started_at,completed_at:i.completed_at,metadata:i.metadata}).from(i).where(and(eq(i.agent_id,e.agentId),eq(i.workspace_id,e.workspaceId),sql`${i.metadata} IS NOT NULL AND json_valid(${i.metadata}) AND json_extract(${i.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(desc(i.started_at)).limit(1).get()??null}catch(n){throw new d("DB_ERROR","Failed to find latest task by metadata",n)}finally{t.close();}}markTaskFailed(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString(),a=n?and(eq(i.id,e),eq(i.status,"running"),eq(i.workspace_id,n)):and(eq(i.id,e),eq(i.status,"running"));o.db.update(i).set({status:"failed",error:t,completed_at:s}).where(a).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{o.close();}}findTasksByPromptHint(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!existsSync(a))continue;let c=k(a);try{let u=t?and(like(i.prompt,`%${e}%`),eq(i.workspace_id,t)):like(i.prompt,`%${e}%`),l=c.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(p));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{c.close();}}return s}getProviderUsage(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Nn(),a=sql`
|
|
211
|
+
COALESCE(${i.input_tokens}, 0)
|
|
205
212
|
+ CASE
|
|
206
|
-
WHEN ${
|
|
213
|
+
WHEN ${i.started_at} >= ${Ce}
|
|
207
214
|
AND (
|
|
208
|
-
${
|
|
209
|
-
OR (${
|
|
210
|
-
OR (${
|
|
215
|
+
${i.crewx_version} IS NULL
|
|
216
|
+
OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
|
|
217
|
+
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Le}) AS INTEGER) < ${Pe})
|
|
211
218
|
)
|
|
212
|
-
THEN COALESCE(${
|
|
219
|
+
THEN COALESCE(${i.cached_input_tokens}, 0)
|
|
213
220
|
ELSE 0
|
|
214
221
|
END
|
|
215
|
-
`,c=n?sql`WHERE ${
|
|
222
|
+
`,c=n?sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t} AND ${i.workspace_id} = ${n}`:sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t}`;return o.db.all(sql`
|
|
216
223
|
SELECT
|
|
217
|
-
${
|
|
224
|
+
${s} AS provider,
|
|
218
225
|
COUNT(*) AS total_tasks,
|
|
219
226
|
COALESCE(SUM(${a}), 0) AS input_tokens,
|
|
220
|
-
COALESCE(SUM(${
|
|
221
|
-
COALESCE(SUM(${
|
|
222
|
-
COALESCE(SUM(${
|
|
223
|
-
COALESCE(SUM(${
|
|
224
|
-
MAX(${
|
|
225
|
-
FROM ${
|
|
227
|
+
COALESCE(SUM(${i.output_tokens}), 0) AS output_tokens,
|
|
228
|
+
COALESCE(SUM(${i.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
229
|
+
COALESCE(SUM(${i.cost_usd}), 0) AS cost_usd,
|
|
230
|
+
COALESCE(SUM(${i.duration_ms}), 0) AS active_duration_ms,
|
|
231
|
+
MAX(${i.completed_at}) AS last_active_at
|
|
232
|
+
FROM ${i}
|
|
226
233
|
${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(${
|
|
234
|
+
GROUP BY ${s}
|
|
235
|
+
ORDER BY (COALESCE(SUM(${a}), 0) + COALESCE(SUM(${i.output_tokens}), 0)) DESC
|
|
236
|
+
`).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(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Nn(),a=sql`
|
|
237
|
+
COALESCE(${i.input_tokens}, 0)
|
|
231
238
|
+ CASE
|
|
232
|
-
WHEN ${
|
|
239
|
+
WHEN ${i.started_at} >= ${Ce}
|
|
233
240
|
AND (
|
|
234
|
-
${
|
|
235
|
-
OR (${
|
|
236
|
-
OR (${
|
|
241
|
+
${i.crewx_version} IS NULL
|
|
242
|
+
OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
|
|
243
|
+
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Le}) AS INTEGER) < ${Pe})
|
|
237
244
|
)
|
|
238
|
-
THEN COALESCE(${
|
|
245
|
+
THEN COALESCE(${i.cached_input_tokens}, 0)
|
|
239
246
|
ELSE 0
|
|
240
247
|
END
|
|
241
|
-
`,c=n?sql`WHERE ${
|
|
248
|
+
`,c=n?sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t} AND ${i.workspace_id} = ${n}`:sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t}`,u=o.db.all(sql`
|
|
242
249
|
SELECT
|
|
243
|
-
${
|
|
244
|
-
${
|
|
250
|
+
${i.model} AS model,
|
|
251
|
+
${s} AS provider,
|
|
245
252
|
COUNT(*) AS total_tasks,
|
|
246
253
|
COALESCE(SUM(${a}), 0) AS input_tokens,
|
|
247
|
-
COALESCE(SUM(${
|
|
248
|
-
COALESCE(SUM(${
|
|
249
|
-
COALESCE(SUM(${
|
|
250
|
-
COALESCE(SUM(${
|
|
251
|
-
MAX(${
|
|
252
|
-
FROM ${
|
|
254
|
+
COALESCE(SUM(${i.output_tokens}), 0) AS output_tokens,
|
|
255
|
+
COALESCE(SUM(${i.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
256
|
+
COALESCE(SUM(${i.cost_usd}), 0) AS cost_usd,
|
|
257
|
+
COALESCE(SUM(${i.duration_ms}), 0) AS active_duration_ms,
|
|
258
|
+
MAX(${i.completed_at}) AS last_active_at
|
|
259
|
+
FROM ${i}
|
|
253
260
|
${c}
|
|
254
|
-
GROUP BY ${
|
|
255
|
-
`),l=new Map;for(let p of u){let
|
|
261
|
+
GROUP BY ${i.model}, ${s}
|
|
262
|
+
`),l=new Map;for(let p of u){let _=bn(p.model??""),g=JSON.stringify([p.provider,_]),m=l.get(g);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(g,{model:_,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,_)=>_.costUsd-p.costUsd)}catch(s){throw new d("DB_ERROR","Failed to get model usage",s)}finally{o.close();}}getTasksForReport(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=n?sql`WHERE ${i.started_at} >= ${e} AND ${i.started_at} < ${t} AND ${i.workspace_id} = ${n}`:sql`WHERE ${i.started_at} >= ${e} AND ${i.started_at} < ${t}`;return o.db.all(sql`
|
|
256
263
|
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(
|
|
264
|
+
${i.thread_id} AS thread_id,
|
|
265
|
+
${i.agent_id} AS agent_id,
|
|
266
|
+
${i.started_at} AS started_at,
|
|
267
|
+
${i.status} AS status,
|
|
268
|
+
${i.error} AS error,
|
|
269
|
+
${i.exit_code} AS exit_code
|
|
270
|
+
FROM ${i}
|
|
271
|
+
${s}
|
|
272
|
+
ORDER BY ${i.started_at} ASC
|
|
273
|
+
`).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(s){throw new d("DB_ERROR","Failed to get tasks for report",s)}finally{o.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let n=[];e.workspaceId&&n.push(eq(i.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&n.push(inArray(i.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&n.push(inArray(i.status,e.statuses)),e.from&&n.push(gte(i.started_at,e.from)),e.to&&n.push(lt(i.started_at,e.to));let o=n.length>0?and(...n):void 0,s=(e.order??"DESC")==="ASC"?asc(i.started_at):desc(i.started_at),a={id:i.id,agent_id:i.agent_id,status:i.status,prompt:i.prompt,started_at:i.started_at,completed_at:i.completed_at,thread_id:i.thread_id};return e.limit?t.db.select(a).from(i).where(o).orderBy(s).limit(e.limit).all():t.db.select(a).from(i).where(o).orderBy(s).all()}catch(n){throw new d("DB_ERROR","Failed to find task evidence",n)}finally{t.close();}}findThreadChains(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let n=e.maxThreads??8,o=e.maxTurnsPerThread??4,s=[isNotNull(i.thread_id),isNull(i.parent_task_id),isNull(i.caller_agent_id),or(isNull(i.platform),ne(i.platform,"workflow")),or(isNull(i.metadata),and(notLike(i.metadata,'%"kind":"workflow_card"%'),notLike(i.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(i.metadata),notLike(i.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(eq(i.workspace_id,e.workspaceId)),e.from&&s.push(gte(i.started_at,e.from)),e.to&&s.push(lt(i.started_at,e.to));let a=t.db.select({id:i.id,agent_id:i.agent_id,status:i.status,prompt:i.prompt,started_at:i.started_at,completed_at:i.completed_at,thread_id:i.thread_id}).from(i).where(and(...s)).orderBy(asc(i.started_at),asc(i.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},_=c.get(l.thread_id);_?_.push(p):c.set(l.thread_id,[p]);}let u=[];for(let[l,p]of c){let _=p.filter(g=>g.agentId===e.targetAgentId).length;_<2||u.push({threadId:l,targetAgentTurnCount:_,turns:p});}return u.sort((l,p)=>{let _=l.turns[l.turns.length-1].startedAt,g=p.turns[p.turns.length-1].startedAt;return _<g?1:_>g?-1:0}),u.slice(0,n).map(l=>({threadId:l.threadId,targetAgentTurnCount:l.targetAgentTurnCount,turns:l.turns.slice(-o)}))}catch(n){throw new d("DB_ERROR","Failed to find thread chains",n)}finally{t.close();}}};var Ln=["success","failed","completed"],gt=10*1024*1024*1024,Pn=256,ts=new Set(Ln),W=class extends Error{constructor(t,n,o="metadata"){super(n);this.taskId=t;this.kind=o;this.name="MigrationTaskError";}taskId;kind};function On(r){return r||(process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(homedir(),".crewx","crewx.db"))}function ns(){return qe("better-sqlite3")}function jn(r,e){let t=r===":memory:";if(!t&&!existsSync(r))throw new Error(`Database not found: ${r}`);let n=new(ns())(r,{readonly:e,fileMustExist:!t,timeout:5e3});return n.pragma("foreign_keys = ON"),n.pragma("busy_timeout = 5000"),n}function ze(r,e,t=[]){return r.prepare(e).all(...t)}function He(r,e,t=[]){return r.prepare(e).get(...t)}function rs(r,e,t=[]){return r.prepare(e).run(...t)}function os(r,e,t=[]){return r.prepare(e).iterate(...t)}function ss(r){return typeof r=="string"&&r.length>0?r:"<unknown>"}function $n(r){return typeof r=="string"&&ts.has(r)}function In(r,e){r.set(e,(r.get(e)??0)+1);}function An(r){return Object.fromEntries([...r.entries()].sort(([e],[t])=>e.localeCompare(t)))}function is(r){let e=new Set(ze(r,"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('tasks', 'task_log_events')").map(a=>a.name)),t=["tasks","task_log_events"].filter(a=>!e.has(a));if(t.length>0)throw new Error(`Database schema is missing required table(s): ${t.join(", ")}`);let n=new Set(ze(r,"PRAGMA table_info('tasks')").map(a=>a.name)),s=["id","status","logs","log_storage","last_log_seq","log_revision"].filter(a=>!n.has(a));if(s.length>0)throw new Error(`Database schema is missing required tasks column(s): ${s.join(", ")}`)}function Bn(r,e){if(e==null)return {entries:[]};if(typeof e!="string")throw new W(r,"Malformed task logs: tasks.logs must be JSON text or null","malformed");if(e.trim()==="")return {entries:[]};let t;try{t=JSON.parse(e);}catch(o){let s=o instanceof Error?o.message:String(o);throw new W(r,`Malformed JSON in tasks.logs (${s})`,"malformed")}if(!Array.isArray(t))throw new W(r,"Malformed task logs: expected a JSON array","malformed");let n=[];for(let[o,s]of t.entries()){if(s===null||typeof s!="object"||typeof s.timestamp!="string"||typeof s.level!="string"||typeof s.message!="string")throw new W(r,`Malformed task logs: entry ${o} must contain string timestamp, level, and message fields`,"malformed");let a=s;n.push({timestamp:a.timestamp,level:a.level,message:a.message});}return {entries:n}}function Dt(r,e){if(!Number.isInteger(r.last_log_seq)||r.last_log_seq<0)throw new W(r.id,"Invalid last_log_seq metadata","metadata");if(!Number.isInteger(r.log_revision)||r.log_revision<0)throw new W(r.id,"Invalid log_revision metadata","metadata");if(e==="blob"&&r.last_log_seq!==0)throw new W(r.id,"Blob source must have last_log_seq=0","metadata")}function as(r){let e=ze(r,`SELECT task_id, COUNT(*) AS event_count
|
|
274
|
+
FROM task_log_events GROUP BY task_id`);return new Map(e.map(t=>[t.task_id,t.event_count]))}function ds(r){let e=as(r),t=new Map,n=[],o=[],s=[],a=new Map,c=new Map,u=0,l=0,p=0,_=0,g=0,m=0;for(let j of os(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
275
|
+
FROM tasks ORDER BY id`)){let w=j,$=ss(w.status);if(In(a,$),t.set(w.id,{id:w.id,status:w.status,log_storage:w.log_storage,last_log_seq:w.last_log_seq,log_revision:w.log_revision}),u+=1,w.log_storage==="events"){_+=1;try{Dt(w,"events");}catch(ke){s.push(It(ke,w.id));}w.logs!==null&&s.push({taskId:w.id,reason:"Event source still has a non-null tasks.logs blob",kind:"mixed-source"});continue}if(w.log_storage!=="blob"){s.push({taskId:w.id,reason:`Unknown log_storage value: ${w.log_storage}`,kind:"invalid-source"});continue}l+=1;let T=$n(w.status);T||(p+=1,In(c,$)),typeof w.logs=="string"?m+=Buffer.byteLength(w.logs,"utf8"):Buffer.isBuffer(w.logs)&&(m+=w.logs.byteLength);let K=e.get(w.id)??0;K>0&&s.push({taskId:w.id,reason:`Blob source already has ${K} task_log_events row(s)`,kind:"mixed-source"});let Ne;try{Ne=Bn(w.id,w.logs),g+=Ne.entries.length,Dt(w,"blob");}catch(ke){let ye=It(ke,w.id);s.push(ye),ye.kind==="malformed"&&o.push(ye);continue}K>0||T&&n.push(w.id);}return {taskCount:u,candidateTaskCount:l,eligibleTaskCount:n.length,eventSourceTasks:_,statusCounts:An(a),deferredTaskCount:p,deferredStatusCounts:An(c),entryCount:g,sourceBytes:m,candidateIds:n,malformedRows:o,failures:s,tasks:t}}function It(r,e){return r instanceof W?{taskId:r.taskId,reason:r.message,kind:r.kind}:{taskId:e,reason:r instanceof Error?r.message:String(r),kind:"metadata"}}function cs(r){return He(r,"SELECT COUNT(*) AS count FROM tasks WHERE status IN ('pending', 'running')")?.count??0}function ls(r){return He(r,"SELECT COUNT(*) AS count FROM tasks WHERE log_storage = 'blob'")?.count??0}function us(r){if(r===":memory:")return 0;let e=t=>{try{return statSync(t).size}catch{return 0}};return e(r)+e(`${r}-wal`)}function ps(r,e){return us(r)+e*Pn}function qn(r,e){return Number.isFinite(r)&&Number.isFinite(e)&&r>=e+gt}function Cn(r){let e=dirname(resolve(r));for(;!existsSync(e);){let t=dirname(e);if(t===e)break;e=t;}return e}function Mn(r,e,t){let n=[...new Set([Cn(r),...t?[Cn(t)]:[]])],o=[],s=Number.POSITIVE_INFINITY;for(let u of n)try{let l=statfsSync(u);s=Math.min(s,l.bavail*l.bsize);}catch(l){s=0,o.push(`Unable to inspect free space for ${u}: ${l instanceof Error?l.message:String(l)}`);}let a=ps(r,e),c=a+gt;return {estimatedFreeSpaceBytes:a,requiredFreeSpaceBytes:c,availableFreeSpaceBytes:Number.isFinite(s)?Math.floor(s):0,minimumFreeSpaceReserveBytes:gt,freeSpaceGatePassed:qn(Number.isFinite(s)?Math.floor(s):0,a),warnings:o}}function Un(r){return new Set(r.map(e=>e.taskId)).size}function Fn(r){try{let e=r.pragma("wal_checkpoint(TRUNCATE)"),t=Array.isArray(e)?e[0]:e,n=t!==null&&typeof t=="object"&&"busy"in t?Number(t.busy):0;return n>0?`WAL checkpoint(TRUNCATE) busy (${n}); continuing without failing migration`:void 0}catch(e){return `WAL checkpoint(TRUNCATE) warning; continuing without failing migration: ${e instanceof Error?e.message:String(e)}`}}function pt(r,e,t,n,o=Mn(e,t.entryCount)){let s=n.failures??t.failures,a=n.malformedRows??t.malformedRows,{ok:c,...u}=n;return {mode:r,ok:c,dbPath:e,activeTaskCount:n.activeTaskCount??0,taskCount:t.taskCount,candidateTaskCount:t.candidateTaskCount,eligibleTaskCount:t.eligibleTaskCount,statusCounts:t.statusCounts,deferredTaskCount:t.deferredTaskCount,deferredStatusCounts:t.deferredStatusCounts,entryCount:t.entryCount,sourceBytes:t.sourceBytes,estimatedFreeSpaceBytes:o.estimatedFreeSpaceBytes,requiredFreeSpaceBytes:o.requiredFreeSpaceBytes,availableFreeSpaceBytes:o.availableFreeSpaceBytes,minimumFreeSpaceReserveBytes:o.minimumFreeSpaceReserveBytes,freeSpaceGatePassed:o.freeSpaceGatePassed,migratedTasks:n.migratedTasks??0,migratedEntries:n.migratedEntries??0,skippedTasks:n.skippedTasks??t.eventSourceTasks,failedTasks:n.failedTasks??Un(s),malformedRows:a,failures:s,logicalSourceBytesRemoved:n.logicalSourceBytesRemoved??0,warnings:n.warnings??o.warnings,remainingTaskCount:n.remainingTaskCount??t.candidateTaskCount,...u}}function _s(r,e){return r.length!==e.length?false:r.every((t,n)=>{let o=e[n];return t.seq===n+1&&t.timestamp===o.timestamp&&t.level===o.level&&t.message===o.message})}function gs(r,e){return r.transaction(()=>{let n=He(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
276
|
+
FROM tasks WHERE id = ?`,[e]);if(!n)throw new W(e,"Task disappeared before migration","metadata");if(n.log_storage==="events")return {status:"skipped",entryCount:0,sourceBytes:0};if(n.log_storage!=="blob")throw new W(e,`Unknown log_storage value: ${n.log_storage}`,"invalid-source");if(!$n(n.status))return {status:"deferred",entryCount:0,sourceBytes:0};let o=n.logs,s=Bn(e,o);Dt(n,"blob");let a=He(r,"SELECT COUNT(*) AS count FROM task_log_events WHERE task_id = ?",[e])?.count??0;if(a!==0)throw new W(e,`Blob source already has ${a} task_log_events row(s)`,"mixed-source");let c=r.prepare(`INSERT INTO task_log_events (task_id, seq, timestamp, level, message)
|
|
277
|
+
VALUES (?, ?, ?, ?, ?)`);for(let[_,g]of s.entries.entries())c.run(e,_+1,g.timestamp,g.level,g.message);let u=ze(r,`SELECT seq, timestamp, level, message
|
|
278
|
+
FROM task_log_events WHERE task_id = ? ORDER BY seq`,[e]);if(!_s(u,s.entries))throw new W(e,"Event parity check failed before source clear","metadata");if(rs(r,`UPDATE tasks
|
|
279
|
+
SET log_storage = 'events', last_log_seq = ?, log_revision = log_revision + 1, logs = NULL
|
|
280
|
+
WHERE id = ? AND log_storage = 'blob' AND logs IS ?`,[s.entries.length,e,o]).changes!==1)throw new W(e,"Task changed while migration was in progress","metadata");let p=He(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
281
|
+
FROM tasks WHERE id = ?`,[e]);if(!p||p.log_storage!=="events"||p.logs!==null||p.last_log_seq!==s.entries.length||p.log_revision!==n.log_revision+1)throw new W(e,"Final task metadata parity check failed","metadata");return {status:"migrated",entryCount:s.entries.length,sourceBytes:typeof o=="string"?Buffer.byteLength(o,"utf8"):Buffer.isBuffer(o)?o.byteLength:0}}).immediate()}function Hn(r){let e=new Date().toISOString().replace(/[-:.TZ]/g,"").slice(0,14),t=randomBytes(6).toString("hex");return `${r}.task-log-backup-${e}-${t}.sqlite`}async function fs(r,e,t){let n=t??Hn(e);if(resolve(n)===resolve(e))throw new Error("Backup path must be different from the source database");if(existsSync(n))throw new Error(`Refusing to overwrite existing backup: ${n}`);if(mkdirSync(dirname(n),{recursive:true}),await r.backup(n),!existsSync(n))throw new Error(`SQLite backup was not created: ${n}`);let o=jn(n,true);try{let s=o.pragma("integrity_check",{simple:!0});if(s!=="ok")throw new Error(`Backup integrity check failed: ${s}`)}finally{o.close();}return n}function ms(r){let e=ze(r,`SELECT task_id AS taskId,
|
|
282
|
+
COUNT(*) AS eventCount,
|
|
283
|
+
COUNT(DISTINCT seq) AS distinctSeqCount,
|
|
284
|
+
MIN(seq) AS minSeq,
|
|
285
|
+
MAX(seq) AS maxSeq
|
|
286
|
+
FROM task_log_events GROUP BY task_id`),t=e.reduce((n,o)=>n+o.eventCount,0);return {rows:e,eventCount:t}}function xe(r,e,t,n={}){return {taskId:r,kind:e,reason:t,...n}}function hs(r,e,t){let n=[];for(let _ of t.failures)_.kind==="malformed"?n.push(xe(_.taskId,"malformed-blob",_.reason)):_.kind==="mixed-source"?n.push(xe(_.taskId,"mixed-source",_.reason)):n.push(xe(_.taskId,"source-invariant",_.reason));let o=ms(r),s=new Map(o.rows.map(_=>[_.taskId,_]));for(let _ of o.rows){let g=t.tasks.get(_.taskId);if(!g){n.push(xe(null,"orphan-event",`Event rows reference missing task ${_.taskId}`,{actual:_.eventCount}));continue}(_.minSeq===null||_.minSeq<1||_.distinctSeqCount!==_.maxSeq)&&n.push(xe(g.id,"seq-gap","Task event sequence has a gap or invalid starting sequence",{expected:_.maxSeq??0,actual:_.distinctSeqCount})),g.log_storage==="events"&&g.last_log_seq!==_.eventCount&&n.push(xe(g.id,"count-mismatch","last_log_seq does not match task_log_events row count",{expected:g.last_log_seq??0,actual:_.eventCount}));}for(let _ of t.tasks.values())_.log_storage==="events"&&!s.has(_.id)&&_.last_log_seq!==0&&n.push(xe(_.id,"count-mismatch","Event-source task has no rows for its last_log_seq",{expected:_.last_log_seq??0,actual:0}));for(let _ of ze(r,`SELECT task_id AS taskId, seq, COUNT(*) AS duplicateCount
|
|
287
|
+
FROM task_log_events GROUP BY task_id, seq HAVING COUNT(*) > 1`))n.push(xe(_.taskId,"duplicate-seq",`Duplicate task event sequence ${_.seq}`,{actual:_.duplicateCount,seq:_.seq}));let a=He(r,`SELECT COUNT(*) AS count FROM task_log_events
|
|
288
|
+
WHERE seq IS NULL OR seq < 1 OR timestamp IS NULL OR level IS NULL OR message IS NULL`)?.count??0;a>0&&n.push(xe(null,"invalid-event","Event rows contain invalid sequence or null payload fields",{actual:a}));let c=new Set(n.flatMap(_=>_.taskId?[_.taskId]:[])),u=n.map(_=>({taskId:_.taskId??"(orphan)",reason:_.reason,kind:_.kind==="malformed-blob"?"malformed":_.kind==="mixed-source"?"mixed-source":"metadata"})),l=u.filter(_=>_.kind==="malformed"),p={checkedTasks:t.taskCount,eventSourceTasks:t.eventSourceTasks,blobSourceTasks:t.candidateTaskCount,eventCount:o.eventCount,orphanEventCount:n.filter(_=>_.kind==="orphan-event").length,failedTasks:c.size,issues:n};return pt("verify",e,t,{ok:n.length===0,migratedTasks:t.eventSourceTasks,migratedEntries:o.eventCount,skippedTasks:t.candidateTaskCount,failedTasks:c.size,malformedRows:l,failures:u,remainingTaskCount:t.candidateTaskCount,verification:p})}function ws(r){if(r.mode!=="apply"&&r.batchTasks!==void 0)throw new Error("--batch-tasks is only valid with --apply");if(r.batchTasks!==void 0&&(!Number.isInteger(r.batchTasks)||r.batchTasks<1))throw new Error("--batch-tasks must be a positive integer")}async function ks(r){ws(r);let e=On(r.dbPath),t=jn(e,r.mode!=="apply");try{is(t);let n=ds(t),o=cs(t);if(r.mode==="verify")return {...hs(t,e,n),activeTaskCount:o};if(r.mode==="dry-run")return pt("dry-run",e,n,{ok:n.failures.length===0,activeTaskCount:o,skippedTasks:n.eventSourceTasks,remainingTaskCount:n.candidateTaskCount});let s=r.backupPath??Hn(e),a=Mn(e,n.entryCount,s);if(!a.freeSpaceGatePassed)return pt("apply",e,n,{ok:!1,activeTaskCount:o,blockedReason:`Apply blocked: available free space (${a.availableFreeSpaceBytes} bytes) is below the required ${a.requiredFreeSpaceBytes} bytes (including a ${a.minimumFreeSpaceReserveBytes} byte reserve)`,skippedTasks:n.eventSourceTasks,remainingTaskCount:n.candidateTaskCount},a);let c=await fs(t,e,s),u=[...n.failures],l=r.batchTasks===void 0?n.candidateIds:n.candidateIds.slice(0,r.batchTasks),p=r.batchTasks??Math.max(l.length,1),_=0,g=0,m=0,j=[...a.warnings];for(let[w,$]of l.entries()){try{let T=gs(t,$);T.status==="migrated"&&(_+=1,g+=T.entryCount,m+=T.sourceBytes);}catch(T){u.push(It(T,$));}if((w+1)%p===0||w===l.length-1){let T=Fn(t);T&&j.push(T);}}return pt("apply",e,n,{ok:u.length===0,activeTaskCount:o,backupPath:c,backupMethod:"sqlite-online-backup",migratedTasks:_,migratedEntries:g,logicalSourceBytesRemoved:m,failedTasks:Un(u),failures:u,malformedRows:n.malformedRows,remainingTaskCount:ls(t),skippedTasks:n.eventSourceTasks,warnings:j},a)}finally{t.close();}}function ys(r){return basename(r)}var At=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}validateWorkspaceId(e,t){return e.db.select({id:h.id}).from(h).where(eq(h.id,t)).limit(1).get()?t:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
267
289
|
SELECT 1 FROM tasks parent
|
|
268
|
-
WHERE parent.id = ${
|
|
269
|
-
AND parent.thread_id = ${
|
|
270
|
-
)`)}findAllThreads(
|
|
290
|
+
WHERE parent.id = ${e}.parent_task_id
|
|
291
|
+
AND parent.thread_id = ${e}.thread_id
|
|
292
|
+
)`)}findAllThreads(e){let t=this.resolveDbPaths(),n=new Set,o=[];for(let s of t){if(!existsSync(s))continue;let a=k(s);try{let c=e?eq(f.workspace_id,e):void 0,u=a.db.select().from(f).where(c).orderBy(desc(f.updated_at)).all();for(let l of u)n.has(l.id)||(n.add(l.id),o.push(l));}catch(c){throw new d("DB_ERROR","Failed to find all threads",c)}finally{a.close();}}return o}findThreadsByIdsOrTitles(e,t){if(e.length===0)return [];let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!existsSync(a))continue;let c=k(a);try{let u=or(inArray(f.id,e),inArray(f.title,e)),l=t?and(u,eq(f.workspace_id,t)):u,p=c.db.select().from(f).where(l).orderBy(desc(f.updated_at)).all();for(let _ of p)o.has(_.id)||(o.add(_.id),s.push(_));}catch(u){throw new d("DB_ERROR","Failed to find threads by ids or titles",u)}finally{c.close();}}return s}findThreadById(e,t){let n=this.resolveDbPaths();for(let o of n){if(!existsSync(o))continue;let s=k(o);try{let a=eq(f.id,e),c=t?and(a,eq(f.workspace_id,t)):a,u=s.db.select().from(f).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{s.close();}}}threadExists(e,t){let n=this.resolveDbPaths();for(let o of n){if(!existsSync(o))continue;let s=k(o);try{let a=eq(f.id,e),c=t?and(a,eq(f.workspace_id,t)):a;if(s.db.select({id:f.id}).from(f).where(c).limit(1).get())return !0}catch(a){throw new d("DB_ERROR","Failed to check thread existence",a)}finally{s.close();}}return false}aggregateTaskStats(e,t){let n=this.resolveDbPaths(),o=0,s=0,a=0,c=0,u=0,l=new Set;for(let p of n){if(!existsSync(p))continue;let _=k(p);try{let g=_.db.get(sql`
|
|
271
293
|
SELECT
|
|
272
294
|
count(*) AS cnt,
|
|
273
295
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -275,48 +297,48 @@ ${n.join(`
|
|
|
275
297
|
COALESCE(SUM(child.cached_input_tokens), 0) AS total_cached,
|
|
276
298
|
COALESCE(SUM(child.cost_usd), 0) AS total_cost
|
|
277
299
|
FROM tasks child
|
|
278
|
-
WHERE child.thread_id = ${
|
|
300
|
+
WHERE child.thread_id = ${e}
|
|
279
301
|
AND ${this.topLevelTaskPredicateSql()}
|
|
280
|
-
${
|
|
281
|
-
`);
|
|
302
|
+
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
303
|
+
`);g&&(o+=g.cnt,s+=g.total_input,a+=g.total_output,c+=g.total_cached,u+=g.total_cost);let m=_.db.all(sql`
|
|
282
304
|
SELECT DISTINCT child.agent_id FROM tasks child
|
|
283
|
-
WHERE child.thread_id = ${
|
|
305
|
+
WHERE child.thread_id = ${e}
|
|
284
306
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
285
307
|
AND ${this.topLevelTaskPredicateSql()}
|
|
286
|
-
${
|
|
287
|
-
`);for(let
|
|
308
|
+
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
309
|
+
`);for(let j of m)l.add(j.agent_id);}catch(g){throw new d("DB_ERROR","Failed to aggregate task stats",g)}finally{_.close();}}return {taskCount:o,inputTokens:s,outputTokens:a,cachedInputTokens:c,costUsd:u,agentIds:Array.from(l)}}findTopLevelTasks(e,t,n){let o=this.resolveDbPaths(),s=new Set,a=[];for(let c of o){if(!existsSync(c))continue;let u=k(c);try{let l;n!==void 0?l=u.db.all(sql`
|
|
288
310
|
SELECT * FROM (
|
|
289
311
|
SELECT child.*,
|
|
290
312
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
291
313
|
FROM tasks child
|
|
292
|
-
WHERE child.thread_id = ${
|
|
314
|
+
WHERE child.thread_id = ${e}
|
|
293
315
|
AND ${this.topLevelTaskPredicateSql()}
|
|
294
|
-
${
|
|
316
|
+
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
295
317
|
) ranked
|
|
296
318
|
WHERE rn <= ${n}
|
|
297
319
|
ORDER BY started_at ASC
|
|
298
320
|
`):l=u.db.all(sql`
|
|
299
321
|
SELECT child.* FROM tasks child
|
|
300
|
-
WHERE child.thread_id = ${
|
|
322
|
+
WHERE child.thread_id = ${e}
|
|
301
323
|
AND ${this.topLevelTaskPredicateSql()}
|
|
302
|
-
${
|
|
324
|
+
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
303
325
|
ORDER BY child.started_at ASC
|
|
304
|
-
`);for(let p of l)
|
|
326
|
+
`);for(let p of l)s.has(p.id)||(s.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&&o.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(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!existsSync(a))continue;let c=k(a);try{let u=eq(i.thread_id,e),l=t?and(u,eq(i.workspace_id,t)):u,p=c.db.select().from(i).where(l).orderBy(asc(i.started_at)).all();for(let _ of p)o.has(_.id)||(o.add(_.id),s.push(_));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{c.close();}}return s}findTaskById(e,t,n){let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let a=k(s);try{let c=and(eq(i.id,t),eq(i.thread_id,e)),u=n?and(c,eq(i.workspace_id,n)):c,l=a.db.select().from(i).where(u).limit(1).get();if(!l)continue;let p=a.db.select().from(i).where(eq(i.parent_task_id,l.id)).orderBy(asc(i.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(e,t){return sql`
|
|
305
327
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
306
328
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
307
329
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
308
330
|
child.cost_usd, child.error
|
|
309
331
|
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
310
|
-
WHERE child.thread_id IN (${sql.join(
|
|
332
|
+
WHERE child.thread_id IN (${sql.join(e.map(n=>sql`${n}`),sql`, `)})
|
|
311
333
|
AND ${this.topLevelTaskPredicateSql()}
|
|
312
|
-
${
|
|
334
|
+
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
313
335
|
ORDER BY child.started_at ASC
|
|
314
|
-
`}batchFetchTasks(t
|
|
336
|
+
`}batchFetchTasks(e,t){let n=new Map;if(e.length===0)return n;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let a=k(s);try{let c=a.db.all(this.batchFetchTasksQuery(e,t));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(e,t){let n=this.resolveDbPaths();for(let o of n){if(!existsSync(o))continue;let s=k(o);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,t)}`).map(c=>c.detail)}finally{s.close();}}return []}updateThreadTitle(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=eq(f.id,e),a=n?and(s,eq(f.workspace_id,n)):s;if(!o.db.select({id:f.id}).from(f).where(a).limit(1).get())return;o.db.update(f).set({title:t,title_locked:1,updated_at:new Date().toISOString()}).where(eq(f.id,e)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,t){let n=this.openHandle(true);try{let o=t.workspaceId?this.validateWorkspaceId(n,t.workspaceId):null,s=new Date().toISOString();if(n.db.select({id:f.id,message_count:f.message_count}).from(f).where(eq(f.id,e)).limit(1).get()){let c={updated_at:s};t.title!==void 0&&(c.title=t.title),t.titleLocked!==void 0&&(c.title_locked=t.titleLocked?1:0),n.db.update(f).set(c).where(eq(f.id,e)).run();}else n.db.insert(f).values({id:e,platform:t.platform,workspace_id:o,title:t.title??null,title_locked:t.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to upsert thread",o)}finally{n.close();}}ensureThread(e,t,n){let o=this.openHandle(true);try{let s=n?this.validateWorkspaceId(o,n):null,a=o.db.select({id:f.id,platform:f.platform,workspace_id:f.workspace_id}).from(f).where(eq(f.id,e)).limit(1).get();if(a){s&&!a.workspace_id&&o.db.update(f).set({workspace_id:s}).where(eq(f.id,e)).run();return}let c=new Date().toISOString();o.db.insert(f).values({id:e,platform:t,workspace_id:s,message_count:0,created_at:c,updated_at:c}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to ensure thread",s)}finally{o.close();}}saveUserMessage(e,t,n){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:o.db.transaction(c=>{let l=c.select({message_count:f.message_count}).from(f).where(eq(f.id,e)).limit(1).get()?.message_count===0;return c.run(sql`
|
|
315
337
|
UPDATE threads
|
|
316
|
-
SET first_message = COALESCE(first_message, ${
|
|
317
|
-
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${
|
|
318
|
-
last_message = ${
|
|
338
|
+
SET first_message = COALESCE(first_message, ${t}),
|
|
339
|
+
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${t}, 1, 60) ELSE title END,
|
|
340
|
+
last_message = ${t},
|
|
319
341
|
message_count = message_count + 1,
|
|
320
|
-
updated_at = ${
|
|
321
|
-
WHERE id = ${
|
|
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};
|
|
342
|
+
updated_at = ${s}
|
|
343
|
+
WHERE id = ${e}
|
|
344
|
+
`),l},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(f).set({last_message:t,updated_at:s}).where(eq(f.id,e)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,t){if(!this.dbExists())return;let n=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};t.title!==void 0&&(o.title=t.title,o.title_locked=1),t.titleLocked!==void 0&&(o.title_locked=t.titleLocked?1:0),n.db.update(f).set(o).where(eq(f.id,e)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update thread",o)}finally{n.close();}}togglePin(e,t){let n=this.openHandle(true);try{let o=t?and(eq(f.id,e),eq(f.workspace_id,t)):eq(f.id,e),s=n.db.select({pinned:f.pinned,metadata:f.metadata}).from(f).where(o).get();if(!s)return null;let a=s.pinned?0:1,c=s.metadata?JSON.parse(s.metadata):{};if(a){let u=t?and(eq(f.pinned,1),eq(f.workspace_id,t)):eq(f.pinned,1),l=n.db.select({metadata:f.metadata}).from(f).where(u).all(),p=null;for(let _ of l){let g=_.metadata?JSON.parse(_.metadata):{};typeof g.pinOrder=="number"&&(p===null||g.pinOrder<p)&&(p=g.pinOrder);}c.pinOrder=p===null?0:p-1;}else delete c.pinOrder;return n.db.update(f).set({pinned:a,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(o).run(),{pinned:!!a}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to toggle pin",o)}finally{n.close();}}reorderPins(e,t){let n=this.openHandle(true);try{for(let o=0;o<e.length;o++){let s=t?and(eq(f.id,e[o]),eq(f.workspace_id,t)):eq(f.id,e[o]),a=n.db.select({metadata:f.metadata}).from(f).where(s).get();if(!a)continue;let c=a.metadata?JSON.parse(a.metadata):{};c.pinOrder=o+1,n.db.update(f).set({metadata:JSON.stringify(c)}).where(s).run();}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to reorder pins",o)}finally{n.close();}}toggleStar(e,t){let n=this.openHandle(true);try{let o=t?and(eq(f.id,e),eq(f.workspace_id,t)):eq(f.id,e),s=n.db.select({starred:f.starred}).from(f).where(o).get();if(!s)return null;let a=s.starred?0:1;return n.db.update(f).set({starred:a}).where(o).run(),{starred:!!a}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to toggle star",o)}finally{n.close();}}resolveOverdriveForRequest(e,t,n,o){let a=this.openHandle(true);try{let c=t?and(eq(f.id,e),eq(f.workspace_id,t)):eq(f.id,e);return a.db.transaction(l=>{let p=l.select({metadata:f.metadata}).from(f).where(c).get();if(!p)return null;let _=p.metadata?JSON.parse(p.metadata):{},g=_.overdrive??{},m=o?.defaultTurns??g.defaultTurns??3,j=o?.updatedBy??"ui",w=new Date().toISOString(),$,T,K,Ne;switch(n){case "enable-count":{let ke=o?.turns??m,ye=o?.consumeCurrent?Math.max(ke-1,0):ke;$=ye>0?"count":"off",T=ye,K=!0,Ne="count";break}case "enable-latch":{$="latch",T=0,K=!0,Ne="latch";break}case "disable":{$="off",T=0,K=!1;break}default:{let ke=g.state??"off",ye=typeof g.remaining=="number"?g.remaining:0;if(ke==="count"&&ye>0){let Ut=ye-1;Ut<=0?($="off",T=0):($="count",T=Ut),K=!0,Ne="count";}else ke==="latch"?($="latch",T=0,K=!0,Ne="latch"):($="off",T=0,K=!1);break}}return _.overdrive={state:$,remaining:T,defaultTurns:m,updatedAt:w,updatedBy:j},l.update(f).set({metadata:JSON.stringify(_),updated_at:w}).where(c).run(),{applied:K,appliedMode:Ne,state:$,remaining:T}},{behavior:"immediate"})}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to resolve overdrive",c)}finally{a.close();}}};var Ct=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}insertSpan(e){let t=this.openHandle(true);try{t.db.insert(Se).values(e).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Se).where(eq(Se.task_id,e)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(Se).where(eq(Se.id,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{t.close();}}};var Lt=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}insertToolCall(e){let t=this.openHandle(true);try{t.db.insert(_e).values(e).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(_e).where(eq(_e.task_id,e)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{t.close();}}aggregateByName(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select({toolName:_e.tool_name,count:sql`count(*)`}).from(_e).where(eq(_e.task_id,e)).groupBy(_e.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{t.close();}}};var Pt=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}ensureThreadExists(e,t){if(!e.db.select({id:f.id}).from(f).where(eq(f.id,t)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${t}`)}findByThreadId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return this.ensureThreadExists(t,e),t.db.select().from(re).where(eq(re.thread_id,e)).orderBy(asc(re.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{t.close();}}findById(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(re).where(and(eq(re.id,t),eq(re.thread_id,e))).limit(1).get()??void 0}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to find box by id",o)}finally{n.close();}}insert(e){let t=this.openHandle(true);try{this.ensureThreadExists(t,e.threadId);try{t.db.insert(re).values({id:e.id,thread_id:e.threadId,seq:e.seq,first_task_id:e.first_task_id,mid_task_id:e.mid_task_id,last_task_id:e.last_task_id,task_count:e.task_count,summary:e.summary??null,source_tokens:e.source_tokens,summary_tokens:e.summary_tokens??null,created_at:e.created_at}).run();}catch(o){throw o instanceof Error&&/UNIQUE constraint failed/i.test(o.message)?new d("CONFLICT",`Duplicate seq ${String(e.seq)} for thread ${e.threadId}`,o):o}let n=t.db.select().from(re).where(eq(re.id,e.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{t.close();}}};var Ot=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}bulkInsert(e){if(e.length===0)return;let t=this.openHandle(true);try{let n=new Date().toISOString();t.db.transaction(o=>{for(let s of e)o.insert(Ue).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{t.close();}}findRecent(e=100){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Ue).orderBy(desc(Ue.timestamp)).limit(e).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{t.close();}}};function er(r){return new Date(Math.floor(r/3e5)*3e5).toISOString()}var jt=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}upsert(e){let t=this.openHandle(true);try{let n=er(e.bucketStartMs),o=e.accountRef??"default";t.db.insert(F).values({id:e.id,provider:e.provider,account_ref:o,limit_window:e.limitWindow,bucket_start:n,captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,source:e.source,metadata:e.metadata??null}).onConflictDoUpdate({target:[F.provider,F.account_ref,F.limit_window,F.bucket_start],set:{captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,metadata:e.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{t.close();}}getTrends(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let n=t.db.select({provider:F.provider,bucket_start:F.bucket_start,used_percent:F.used_percent,remaining_percent:F.remaining_percent,resets_at:F.resets_at}).from(F).where(and(eq(F.limit_window,e.window),gte(F.bucket_start,e.fromIso),lte(F.bucket_start,e.toIso))).orderBy(asc(F.bucket_start)).all(),o=new Map;for(let s of n)o.has(s.provider)||o.set(s.provider,[]),o.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(o.entries()).map(([s,a])=>({provider:s,points:a}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{t.close();}}};var $t=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}publish(e){let t=this.openHandle(true);try{t.db.insert(Y).values({id:e.id,workspace_id:e.workspaceId,month:e.month,generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}).onConflictDoUpdate({target:[Y.workspace_id,Y.month],set:{generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}}).run();let n=t.db.select().from(Y).where(and(eq(Y.workspace_id,e.workspaceId),eq(Y.month,e.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{t.close();}}findByMonth(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(Y).where(and(eq(Y.workspace_id,e),eq(Y.month,t))).limit(1).get()??void 0}catch(o){throw new d("DB_ERROR","Failed to find usage report",o)}finally{n.close();}}listByWorkspace(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Y).where(eq(Y.workspace_id,e)).orderBy(desc(Y.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{t.close();}}};var ar=500,dr=50,Bt=class extends N{dbPath;cap;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.cap=e.cap??ar;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}create(e){let t=this.openHandle(true);try{let n=Ie("ntf"),o=new Date().toISOString();return t.db.insert(E).values({id:n,workspace_id:e.workspaceId,agent_id:e.agentId??null,task_id:e.taskId??null,thread_id:e.threadId??null,source:e.source??"agent",level:e.level??"info",title:e.title,body:e.body??null,target_user_id:e.targetUserId??null,created_at:o,metadata:e.metadata??null}).run(),this.enforceCap(t,e.workspaceId),{id:n}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create notification",n)}finally{t.close();}}enforceCap(e,t){let s=(e.db.select({count:sql`count(*)`}).from(E).where(eq(E.workspace_id,t)).get()?.count??0)-this.cap;if(s<=0)return;let c=e.db.select({id:E.id}).from(E).innerJoin(B,eq(B.notification_id,E.id)).where(eq(E.workspace_id,t)).groupBy(E.id).orderBy(asc(E.created_at)).limit(s).all().map(u=>u.id);c.length!==0&&(e.db.delete(B).where(inArray(B.notification_id,c)).run(),e.db.delete(E).where(inArray(E.id,c)).run());}list(e){if(!this.dbExists())return [];let t=e.limit??dr,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:B.read_at}).from(E).leftJoin(B,and(eq(B.notification_id,E.id),eq(B.user_id,e.userId))).where(eq(E.workspace_id,e.workspaceId)).orderBy(desc(E.created_at)).limit(t).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(o){throw new d("DB_ERROR","Failed to list notifications",o)}finally{n.close();}}unreadCount(e){if(!this.dbExists())return 0;let t=this.openHandle(false);try{return t.db.select({count:sql`count(*)`}).from(E).leftJoin(B,and(eq(B.notification_id,E.id),eq(B.user_id,e.userId))).where(and(eq(E.workspace_id,e.workspaceId),isNull(B.notification_id))).get()?.count??0}catch(n){throw new d("DB_ERROR","Failed to count unread notifications",n)}finally{t.close();}}markRead(e){let t=this.openHandle(true);try{if(!t.db.select({id:E.id}).from(E).where(and(eq(E.id,e.notificationId),eq(E.workspace_id,e.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return t.db.insert(B).values({notification_id:e.notificationId,user_id:e.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{t.close();}}markAllRead(e){let t=this.openHandle(true);try{let n=t.db.select({id:E.id}).from(E).leftJoin(B,and(eq(B.notification_id,E.id),eq(B.user_id,e.userId))).where(and(eq(E.workspace_id,e.workspaceId),isNull(B.notification_id))).all();if(n.length===0)return 0;let o=new Date().toISOString();return t.db.transaction(s=>{for(let a of n)s.insert(B).values({notification_id:a.id,user_id:e.userId,read_at:o}).onConflictDoNothing().run();}),n.length}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark all notifications read",n)}finally{t.close();}}};var ur=50,Mt=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{L(n.db,t);}catch(o){throw n.close(),o}return n}create(e){let t=this.openHandle(true);try{let n=new Date().toISOString(),o=[],s=e.map(a=>{let c=Ie("sug");return o.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&&t.db.insert(v).values(s).run(),{ids:o}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create agent suggestions",n)}finally{t.close();}}findLatestSet(e,t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let o=n.db.select({task_id:v.task_id}).from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t))).orderBy(desc(v.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?isNull(v.task_id):eq(v.task_id,o.task_id);return n.db.select().from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),s)).orderBy(asc(v.created_at)).all()}catch(o){throw new d("DB_ERROR","Failed to find latest agent suggestion set",o)}finally{n.close();}}findSetByTaskId(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),eq(v.task_id,n))).orderBy(asc(v.created_at)).all()}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{o.close();}}findById(e,t,n){if(!this.dbExists())return null;let o=this.openHandle(false);try{return o.db.select().from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),eq(v.id,n))).get()??null}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion by id",s)}finally{o.close();}}updateStatus(e,t,n){let o=this.openHandle(true);try{let s={status:t,updated_at:new Date().toISOString()};return n!==void 0&&(s.applied_commit_sha=n),o.db.update(v).set(s).where(eq(v.id,e)).run().changes>0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update agent suggestion status",s)}finally{o.close();}}listByAgent(e,t,n=ur){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t))).orderBy(desc(v.created_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to list agent suggestions",s)}finally{o.close();}}findDismissed(e,t,n=20){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),eq(v.status,"dismissed"))).orderBy(desc(v.updated_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};export{Mt as AgentSuggestionRepository,N as BaseSqliteRepository,zt as CREWX_JOURNAL_SIZE_LIMIT_BYTES,ur as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,ar as DEFAULT_NOTIFICATION_CAP,dr as DEFAULT_NOTIFICATION_LIST_LIMIT,Bt as NotificationRepository,St as ProjectRepository,d as RepositoryError,Ot as RequestLogRepository,Ct as SpanRepository,Pn as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,gt as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,Ln as TASK_LOG_MIGRATION_TERMINAL_STATUSES,Ye as TaskLogRepository,vt as TaskRepository,Pt as ThreadBoxRepository,At as ThreadRepository,Lt as ToolCallRepository,jt as UsageLimitSnapshotRepository,$t as UsageReportRepository,Et as WorkspaceRepository,er as calcBucketStart,qn as hasSufficientTaskLogMigrationFreeSpace,k as openDrizzleDb,Co as pushSchema,kr as reclaimTemporaryJournal,On as resolveTaskLogMigrationDbPath,Me as runMigrations,L as runMigrationsOnce,ks as runTaskLogMigration,ys as taskLogBackupName,i as tasks,Fn as tryCheckpointTaskLogWal};
|