@crewx/sdk 0.9.0-rc.67 → 0.9.0-rc.69
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/model-compat.d.ts +10 -0
- package/dist/config/models.generated.d.ts +2 -2
- package/dist/config/pricing.generated.d.ts +2 -2
- package/dist/esm/index.js +107 -83
- package/dist/esm/plugins/index.js +69 -45
- package/dist/esm/repository/index.js +61 -37
- package/dist/esm/testing/index.js +1 -1
- package/dist/index.browser.d.ts +2 -1
- package/dist/index.browser.js +4 -4
- package/dist/index.d.ts +2 -1
- package/dist/index.js +108 -84
- package/dist/plugins/index.js +69 -45
- package/dist/provider/cli/adapters/cli-knob.util.d.ts +2 -0
- package/dist/repository/index.d.ts +1 -1
- package/dist/repository/index.js +64 -40
- package/dist/repository/task.repository.d.ts +12 -0
- package/dist/testing/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import*as be from'path';import be__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as
|
|
1
|
+
import*as be from'path';import be__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as wn from'fs';import wn__default,{existsSync,mkdirSync,readFileSync,statfsSync,statSync}from'fs';import kr,{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 fr=()=>fileURLToPath(import.meta.url),mr=()=>be__default.dirname(fr()),y=mr();var D=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(kr.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 Ht=r=>{try{return wn.statSync(`${r}-wal`).size}catch{return 0}},Wt=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 = ${Wt}`),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 yr(r,e="TRUNCATE"){if(e!=="PASSIVE"&&e!=="TRUNCATE")throw new Error(`Unsupported journal reclaim mode: ${e}`);let t=qe("better-sqlite3"),n=Ht(r),o;try{o=new t(r),o.pragma("busy_timeout = 1000");let s=o.pragma(`wal_checkpoint(${e})`),a=Ht(r);return {busy:s[0]?.busy===1,walBytesBefore:n,walBytesAfter:a}}finally{o?.close();}}var Kt=new Set,br={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 Rr(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(br))n.has(o)||r.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var Er={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"}};function Sr(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=Er[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,$]of Object.entries(c))g.has(m)||(r.run(`ALTER TABLE tasks ADD COLUMN ${m} ${$}`),g.add(m));}}function Tr(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:j})=>r.all(`PRAGMA table_info("${w}")`).some(K=>K.name===j))&&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 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`(
|
|
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),Rr(r,a),s?.cnt&&(Tr(r,o,t),Sr(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){Kt.has(e)||(Me(r),Kt.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
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
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
|
|
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 sn(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 D{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=sn(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
10
|
WHERE t.workspace_id = ${e}
|
|
11
11
|
ORDER BY t.updated_at DESC
|
|
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`
|
|
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 ln="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function lo(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+=ln[o%62]);}for(;t.length<r;)t+=ln[randomBytes(1)[0]%62];return t}function Le(r){return `${r}_${lo(8)}`}var ho=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),wo=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),ko=new Set(["pending","verifying","passed","failed"]),yo=new Set(["user","project_manager","system"]),bo=new Set(["task","wi","url"]),Ro=/^\d{4}-\d{2}-\d{2}$/;function O(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)&&O(`${e} is required`);}function Eo(r){if(r==null)return;Ro.test(r)||O("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)&&O("dueDate must be a valid calendar date");}function So(r){(!Array.isArray(r)||r.length===0)&&O("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)&&O(`duplicate stage key: ${t.key}`),e.add(t.key);}function To(r){Array.isArray(r)||O("criteria must be an array");for(let e of r)M(e,"criterion.statement");}function Fe(r={}){let e=r.actorType??"system";yo.has(e)||O(`invalid actorType: ${String(e)}`);let t=r.actorId??null;return (e==="user"||e==="project_manager")&&(!t||t.trim().length===0)&&O(`actorId is required for ${e}`),{actorType:e,actorId:t}}function mn(r,e){let t=r??{};if((t===null||typeof t!="object"||Array.isArray(t))&&O("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)&&O(`accepted payload requires ${n}`);try{return JSON.stringify(t)}catch(n){throw new d("VALIDATION","event payload must be JSON serializable",n)}}function vo(r){return Array.isArray(r)||O("evidence must be an array"),r.map(e=>((!e||typeof e!="object")&&O("evidence item must be an object"),bo.has(e.kind)||O(`invalid evidence kind: ${String(e.kind)}`),M(e.ref,"evidence.ref"),e.label!==void 0&&typeof e.label!="string"&&O("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 fn(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 hn(r){return M(r.projectId,"projectId"),M(r.title,"title"),ho.has(r.type)||O(`invalid project event type: ${String(r.type)}`),{...Fe(r),payloadJson:mn(r.payload,r.type)}}function je(r,e,t){let n=hn(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=Le("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 D{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:fn(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"),Eo(e.dueDate),So(e.stages),To(e.criteria);let t=Le("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:Le("pjc"),project_id:t,position:c+1,statement:a,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:n,updated_at:n}).run();}),je(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"),wo.has(t)||O(`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(),je(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)||O("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=fn(u.stages_json);(t<1||t>l.length)&&O("stage index is outside the project stages"),c.update(x).set({stage_index:t,updated_at:s}).where(eq(x.id,e)).run(),je(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||!ko.has(a))&&O(`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(),je(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=vo(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(),je(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;hn(n);let o=new Date().toISOString(),s=this.openHandle(true),a;try{s.db.transaction(c=>{a=je(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)&&O("afterSeq must be a non-negative integer"),t.limit!==void 0&&(!Number.isInteger(t.limit)||t.limit<1)&&O("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};mn(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(),je(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 yn=[h,i,f,Se,_e,re,Ue];function Do(){return be__default.join(kr.homedir(),".crewx","crewx.db")}function Ao(r){if(!wn__default.existsSync(r))return null;let e=Math.floor(Date.now()/1e3),t=`${r}.bak-${e}`;return wn__default.copyFileSync(r,t),t}function bn(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 Co(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 Lo(r,e){let t=e?.dbPath??Do(),n=e?.force??false,o=e?.dryRun??false,s=o?null:Ao(t);if(n&&!o)try{r.run("DELETE FROM __drizzle_migrations");}catch{}let a=bn(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=yn.map(g=>getTableConfig(g).name).filter(g=>!a.has(g)),u=a):(u=bn(r),c=[...u].filter(_=>!a.has(_)));let l=[],p=[];for(let _ of yn){let g=getTableConfig(_),m=g.name;if(!u.has(m))continue;let $=r.all(`PRAGMA table_info("${m}")`),w=new Set($.map(T=>T.name)),j=new Set(g.columns.map(T=>T.name));for(let T of g.columns)if(!w.has(T.name)){if(!o){let K=Co(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 Rn(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 xn(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 Tn(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)=>xn(n,o))}catch(n){throw n instanceof d?new d("DB_ERROR",`Malformed legacy task logs: ${r}`,n):n}}function Nn(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 vn(r){return {taskId:r.id,source:Nn(r),revision:r.log_revision,lastSeq:r.last_log_seq}}function Uo(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 D{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)=>xn(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=Nn(c);if(u==="blob"){let g=Tn(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?vn(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 Uo(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=vn(s);if(a.source==="blob"){let p=Tn(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 vt=40,xe="2026-05-09",Go="0.8.9-rc.13",Ne=10,De=parseInt(Go.split("rc.")[1]);function Dn(){let r=sql`
|
|
13
13
|
CASE
|
|
14
14
|
WHEN ${i.model} LIKE 'claude-%' OR ${i.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
15
15
|
WHEN ${i.model} LIKE 'gpt-%' OR ${i.model} LIKE 'codex-%' THEN 'codex'
|
|
@@ -38,7 +38,7 @@ ${n.join(`
|
|
|
38
38
|
WHEN trim(${o}) = '' THEN 'unknown'
|
|
39
39
|
ELSE ${o}
|
|
40
40
|
END
|
|
41
|
-
`}var
|
|
41
|
+
`}var Vo=new Set(["workflow","mcp"]),An=600*1e3,xt=class extends D{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
42
|
id, agent_id, prompt, mode, status, started_at, pid,
|
|
43
43
|
parent_task_id, caller_agent_id, trace_id, command, metadata,
|
|
44
44
|
workspace_id, project_id, platform, crewx_version, thread_id,
|
|
@@ -48,7 +48,7 @@ ${n.join(`
|
|
|
48
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=?,
|
|
49
49
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
50
50
|
model=COALESCE(?, model)
|
|
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(
|
|
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(Vo.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>=An&&(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=An){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`
|
|
52
52
|
SELECT
|
|
53
53
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
54
54
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -69,7 +69,7 @@ ${n.join(`
|
|
|
69
69
|
FROM tasks
|
|
70
70
|
GROUP BY workspace_id
|
|
71
71
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
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
|
|
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 $ of _)c($.thread_id,$);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 $ of m){let w=this.extractThreadIdFromCommand($.command);!w||!o.has(w)||c(w,$);}}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`
|
|
73
73
|
SELECT
|
|
74
74
|
t.agent_id,
|
|
75
75
|
t.workspace_id,
|
|
@@ -77,11 +77,11 @@ ${n.join(`
|
|
|
77
77
|
COALESCE(SUM(
|
|
78
78
|
COALESCE(t.input_tokens, 0)
|
|
79
79
|
+ CASE
|
|
80
|
-
WHEN t.started_at >= ${
|
|
80
|
+
WHEN t.started_at >= ${xe}
|
|
81
81
|
AND (
|
|
82
82
|
t.crewx_version IS NULL
|
|
83
83
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
84
|
-
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, ${Ne}) AS INTEGER) < ${De})
|
|
85
85
|
)
|
|
86
86
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
87
87
|
ELSE 0
|
|
@@ -100,11 +100,11 @@ ${n.join(`
|
|
|
100
100
|
COALESCE(SUM(
|
|
101
101
|
COALESCE(t.input_tokens, 0)
|
|
102
102
|
+ CASE
|
|
103
|
-
WHEN t.started_at >= ${
|
|
103
|
+
WHEN t.started_at >= ${xe}
|
|
104
104
|
AND (
|
|
105
105
|
t.crewx_version IS NULL
|
|
106
106
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
107
|
-
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, ${Ne}) AS INTEGER) < ${De})
|
|
108
108
|
)
|
|
109
109
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
110
110
|
ELSE 0
|
|
@@ -120,11 +120,11 @@ ${n.join(`
|
|
|
120
120
|
COALESCE(SUM(
|
|
121
121
|
COALESCE(t.input_tokens, 0)
|
|
122
122
|
+ CASE
|
|
123
|
-
WHEN t.started_at >= ${
|
|
123
|
+
WHEN t.started_at >= ${xe}
|
|
124
124
|
AND (
|
|
125
125
|
t.crewx_version IS NULL
|
|
126
126
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
127
|
-
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, ${Ne}) AS INTEGER) < ${De})
|
|
128
128
|
)
|
|
129
129
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
130
130
|
ELSE 0
|
|
@@ -142,11 +142,11 @@ ${n.join(`
|
|
|
142
142
|
COALESCE(SUM(
|
|
143
143
|
COALESCE(t.input_tokens, 0)
|
|
144
144
|
+ CASE
|
|
145
|
-
WHEN t.started_at >= ${
|
|
145
|
+
WHEN t.started_at >= ${xe}
|
|
146
146
|
AND (
|
|
147
147
|
t.crewx_version IS NULL
|
|
148
148
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
149
|
-
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, ${Ne}) AS INTEGER) < ${De})
|
|
150
150
|
)
|
|
151
151
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
152
152
|
ELSE 0
|
|
@@ -161,11 +161,11 @@ ${n.join(`
|
|
|
161
161
|
COALESCE(SUM(
|
|
162
162
|
COALESCE(t.input_tokens, 0)
|
|
163
163
|
+ CASE
|
|
164
|
-
WHEN t.started_at >= ${
|
|
164
|
+
WHEN t.started_at >= ${xe}
|
|
165
165
|
AND (
|
|
166
166
|
t.crewx_version IS NULL
|
|
167
167
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
168
|
-
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, ${Ne}) AS INTEGER) < ${De})
|
|
169
169
|
)
|
|
170
170
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
171
171
|
ELSE 0
|
|
@@ -188,11 +188,11 @@ ${n.join(`
|
|
|
188
188
|
COALESCE(SUM(
|
|
189
189
|
COALESCE(t.input_tokens, 0)
|
|
190
190
|
+ CASE
|
|
191
|
-
WHEN t.started_at >= ${
|
|
191
|
+
WHEN t.started_at >= ${xe}
|
|
192
192
|
AND (
|
|
193
193
|
t.crewx_version IS NULL
|
|
194
194
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
195
|
-
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, ${Ne}) AS INTEGER) < ${De})
|
|
196
196
|
)
|
|
197
197
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
198
198
|
ELSE 0
|
|
@@ -207,14 +207,14 @@ ${n.join(`
|
|
|
207
207
|
AND t.started_at < ${t}
|
|
208
208
|
GROUP BY date(t.started_at), t.agent_id
|
|
209
209
|
ORDER BY date(t.started_at) ASC
|
|
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=
|
|
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=Dn(),a=sql`
|
|
211
211
|
COALESCE(${i.input_tokens}, 0)
|
|
212
212
|
+ CASE
|
|
213
|
-
WHEN ${i.started_at} >= ${
|
|
213
|
+
WHEN ${i.started_at} >= ${xe}
|
|
214
214
|
AND (
|
|
215
215
|
${i.crewx_version} IS NULL
|
|
216
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}, ${
|
|
217
|
+
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Ne}) AS INTEGER) < ${De})
|
|
218
218
|
)
|
|
219
219
|
THEN COALESCE(${i.cached_input_tokens}, 0)
|
|
220
220
|
ELSE 0
|
|
@@ -233,14 +233,14 @@ ${n.join(`
|
|
|
233
233
|
${c}
|
|
234
234
|
GROUP BY ${s}
|
|
235
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=
|
|
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=Dn(),a=sql`
|
|
237
237
|
COALESCE(${i.input_tokens}, 0)
|
|
238
238
|
+ CASE
|
|
239
|
-
WHEN ${i.started_at} >= ${
|
|
239
|
+
WHEN ${i.started_at} >= ${xe}
|
|
240
240
|
AND (
|
|
241
241
|
${i.crewx_version} IS NULL
|
|
242
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}, ${
|
|
243
|
+
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Ne}) AS INTEGER) < ${De})
|
|
244
244
|
)
|
|
245
245
|
THEN COALESCE(${i.cached_input_tokens}, 0)
|
|
246
246
|
ELSE 0
|
|
@@ -259,7 +259,7 @@ ${n.join(`
|
|
|
259
259
|
FROM ${i}
|
|
260
260
|
${c}
|
|
261
261
|
GROUP BY ${i.model}, ${s}
|
|
262
|
-
`),l=new Map;for(let p of u){let _=
|
|
262
|
+
`),l=new Map;for(let p of u){let _=Rn(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`
|
|
263
263
|
SELECT
|
|
264
264
|
${i.thread_id} AS thread_id,
|
|
265
265
|
${i.agent_id} AS agent_id,
|
|
@@ -270,22 +270,46 @@ ${n.join(`
|
|
|
270
270
|
FROM ${i}
|
|
271
271
|
${s}
|
|
272
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();}}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
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();}}getDelegationMatrix(e,t,n){if(!this.dbExists())return {edges:[],truncated:false};let o=this.openHandle(false);try{let s=sql`
|
|
274
|
+
COALESCE(${i.input_tokens}, 0)
|
|
275
|
+
+ CASE
|
|
276
|
+
WHEN ${i.started_at} >= ${xe}
|
|
277
|
+
AND (
|
|
278
|
+
${i.crewx_version} IS NULL
|
|
279
|
+
OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
|
|
280
|
+
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Ne}) AS INTEGER) < ${De})
|
|
281
|
+
)
|
|
282
|
+
THEN COALESCE(${i.cached_input_tokens}, 0)
|
|
283
|
+
ELSE 0
|
|
284
|
+
END
|
|
285
|
+
`,a=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}`,c=o.db.all(sql`
|
|
286
|
+
SELECT
|
|
287
|
+
${i.caller_agent_id} AS caller_agent_id,
|
|
288
|
+
${i.agent_id} AS agent_id,
|
|
289
|
+
COUNT(*) AS task_count,
|
|
290
|
+
COALESCE(SUM(${s}), 0) AS input_tokens,
|
|
291
|
+
COALESCE(SUM(${i.output_tokens}), 0) AS output_tokens
|
|
292
|
+
FROM ${i}
|
|
293
|
+
${a}
|
|
294
|
+
GROUP BY ${i.caller_agent_id}, ${i.agent_id}
|
|
295
|
+
ORDER BY task_count DESC, ${i.caller_agent_id} ASC, ${i.agent_id} ASC
|
|
296
|
+
LIMIT ${vt+1}
|
|
297
|
+
`),u=c.length>vt;return {edges:c.slice(0,vt).map(p=>({callerAgentId:p.caller_agent_id??null,agentId:p.agent_id,taskCount:p.task_count,totalTokens:p.input_tokens+p.output_tokens,outputTokens:p.output_tokens})),truncated:u}}catch(s){throw new d("DB_ERROR","Failed to get delegation matrix",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 On=["success","failed","completed"],gt=10*1024*1024*1024,Pn=256,ns=new Set(On),W=class extends Error{constructor(t,n,o="metadata"){super(n);this.taskId=t;this.kind=o;this.name="MigrationTaskError";}taskId;kind};function $n(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 rs(){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(rs())(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 os(r,e,t=[]){return r.prepare(e).run(...t)}function ss(r,e,t=[]){return r.prepare(e).iterate(...t)}function is(r){return typeof r=="string"&&r.length>0?r:"<unknown>"}function Bn(r){return typeof r=="string"&&ns.has(r)}function In(r,e){r.set(e,(r.get(e)??0)+1);}function Cn(r){return Object.fromEntries([...r.entries()].sort(([e],[t])=>e.localeCompare(t)))}function as(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 qn(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 At(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 ds(r){let e=ze(r,`SELECT task_id, COUNT(*) AS event_count
|
|
298
|
+
FROM task_log_events GROUP BY task_id`);return new Map(e.map(t=>[t.task_id,t.event_count]))}function cs(r){let e=ds(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 $ of ss(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
299
|
+
FROM tasks ORDER BY id`)){let w=$,j=is(w.status);if(In(a,j),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{At(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=Bn(w.status);T||(p+=1,In(c,j)),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 Ie;try{Ie=qn(w.id,w.logs),g+=Ie.entries.length,At(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:Cn(a),deferredTaskCount:p,deferredStatusCounts:Cn(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 ls(r){return He(r,"SELECT COUNT(*) AS count FROM tasks WHERE status IN ('pending', 'running')")?.count??0}function us(r){return He(r,"SELECT COUNT(*) AS count FROM tasks WHERE log_storage = 'blob'")?.count??0}function ps(r){if(r===":memory:")return 0;let e=t=>{try{return statSync(t).size}catch{return 0}};return e(r)+e(`${r}-wal`)}function _s(r,e){return ps(r)+e*Pn}function Mn(r,e){return Number.isFinite(r)&&Number.isFinite(e)&&r>=e+gt}function Ln(r){let e=dirname(resolve(r));for(;!existsSync(e);){let t=dirname(e);if(t===e)break;e=t;}return e}function Un(r,e,t){let n=[...new Set([Ln(r),...t?[Ln(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=_s(r,e),c=a+gt;return {estimatedFreeSpaceBytes:a,requiredFreeSpaceBytes:c,availableFreeSpaceBytes:Number.isFinite(s)?Math.floor(s):0,minimumFreeSpaceReserveBytes:gt,freeSpaceGatePassed:Mn(Number.isFinite(s)?Math.floor(s):0,a),warnings:o}}function Fn(r){return new Set(r.map(e=>e.taskId)).size}function Hn(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=Un(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??Fn(s),malformedRows:a,failures:s,logicalSourceBytesRemoved:n.logicalSourceBytesRemoved??0,warnings:n.warnings??o.warnings,remainingTaskCount:n.remainingTaskCount??t.candidateTaskCount,...u}}function gs(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 fs(r,e){return r.transaction(()=>{let n=He(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
300
|
+
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(!Bn(n.status))return {status:"deferred",entryCount:0,sourceBytes:0};let o=n.logs,s=qn(e,o);At(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
301
|
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(!
|
|
302
|
+
FROM task_log_events WHERE task_id = ? ORDER BY seq`,[e]);if(!gs(u,s.entries))throw new W(e,"Event parity check failed before source clear","metadata");if(os(r,`UPDATE tasks
|
|
279
303
|
SET log_storage = 'events', last_log_seq = ?, log_revision = log_revision + 1, logs = NULL
|
|
280
304
|
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
|
|
305
|
+
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 zn(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 ms(r,e,t){let n=t??zn(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 hs(r){let e=ze(r,`SELECT task_id AS taskId,
|
|
282
306
|
COUNT(*) AS eventCount,
|
|
283
307
|
COUNT(DISTINCT seq) AS distinctSeqCount,
|
|
284
308
|
MIN(seq) AS minSeq,
|
|
285
309
|
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
|
|
287
|
-
FROM task_log_events GROUP BY task_id, seq HAVING COUNT(*) > 1`))n.push(
|
|
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(
|
|
310
|
+
FROM task_log_events GROUP BY task_id`),t=e.reduce((n,o)=>n+o.eventCount,0);return {rows:e,eventCount:t}}function Ae(r,e,t,n={}){return {taskId:r,kind:e,reason:t,...n}}function ws(r,e,t){let n=[];for(let _ of t.failures)_.kind==="malformed"?n.push(Ae(_.taskId,"malformed-blob",_.reason)):_.kind==="mixed-source"?n.push(Ae(_.taskId,"mixed-source",_.reason)):n.push(Ae(_.taskId,"source-invariant",_.reason));let o=hs(r),s=new Map(o.rows.map(_=>[_.taskId,_]));for(let _ of o.rows){let g=t.tasks.get(_.taskId);if(!g){n.push(Ae(null,"orphan-event",`Event rows reference missing task ${_.taskId}`,{actual:_.eventCount}));continue}(_.minSeq===null||_.minSeq<1||_.distinctSeqCount!==_.maxSeq)&&n.push(Ae(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(Ae(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(Ae(_.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
|
|
311
|
+
FROM task_log_events GROUP BY task_id, seq HAVING COUNT(*) > 1`))n.push(Ae(_.taskId,"duplicate-seq",`Duplicate task event sequence ${_.seq}`,{actual:_.duplicateCount,seq:_.seq}));let a=He(r,`SELECT COUNT(*) AS count FROM task_log_events
|
|
312
|
+
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(Ae(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 ks(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 ys(r){ks(r);let e=$n(r.dbPath),t=jn(e,r.mode!=="apply");try{as(t);let n=cs(t),o=ls(t);if(r.mode==="verify")return {...ws(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??zn(e),a=Un(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 ms(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,$=[...a.warnings];for(let[w,j]of l.entries()){try{let T=fs(t,j);T.status==="migrated"&&(_+=1,g+=T.entryCount,m+=T.sourceBytes);}catch(T){u.push(It(T,j));}if((w+1)%p===0||w===l.length-1){let T=Hn(t);T&&$.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:Fn(u),failures:u,malformedRows:n.malformedRows,remainingTaskCount:us(t),skippedTasks:n.eventSourceTasks,warnings:$},a)}finally{t.close();}}function bs(r){return basename(r)}var Ct=class extends D{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 (
|
|
289
313
|
SELECT 1 FROM tasks parent
|
|
290
314
|
WHERE parent.id = ${e}.parent_task_id
|
|
291
315
|
AND parent.thread_id = ${e}.thread_id
|
|
@@ -306,7 +330,7 @@ ${n.join(`
|
|
|
306
330
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
307
331
|
AND ${this.topLevelTaskPredicateSql()}
|
|
308
332
|
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
309
|
-
`);for(let
|
|
333
|
+
`);for(let $ of m)l.add($.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`
|
|
310
334
|
SELECT * FROM (
|
|
311
335
|
SELECT child.*,
|
|
312
336
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -341,4 +365,4 @@ ${n.join(`
|
|
|
341
365
|
message_count = message_count + 1,
|
|
342
366
|
updated_at = ${s}
|
|
343
367
|
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};
|
|
368
|
+
`),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,$=o?.updatedBy??"ui",w=new Date().toISOString(),j,T,K,Ie;switch(n){case "enable-count":{let ke=o?.turns??m,ye=o?.consumeCurrent?Math.max(ke-1,0):ke;j=ye>0?"count":"off",T=ye,K=!0,Ie="count";break}case "enable-latch":{j="latch",T=0,K=!0,Ie="latch";break}case "disable":{j="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 Ft=ye-1;Ft<=0?(j="off",T=0):(j="count",T=Ft),K=!0,Ie="count";}else ke==="latch"?(j="latch",T=0,K=!0,Ie="latch"):(j="off",T=0,K=!1);break}}return _.overdrive={state:j,remaining:T,defaultTurns:m,updatedAt:w,updatedBy:$},l.update(f).set({metadata:JSON.stringify(_),updated_at:w}).where(c).run(),{applied:K,appliedMode:Ie,state:j,remaining:T}},{behavior:"immediate"})}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to resolve overdrive",c)}finally{a.close();}}};var Lt=class extends D{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 Ot=class extends D{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 D{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 $t=class extends D{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 tr(r){return new Date(Math.floor(r/3e5)*3e5).toISOString()}var jt=class extends D{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=tr(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 Bt=class extends D{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 dr=500,cr=50,qt=class extends D{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??dr;}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=Le("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??cr,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 pr=50,Ut=class extends D{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=Le("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=pr){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{Ut as AgentSuggestionRepository,D as BaseSqliteRepository,Wt as CREWX_JOURNAL_SIZE_LIMIT_BYTES,pr as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,dr as DEFAULT_NOTIFICATION_CAP,cr as DEFAULT_NOTIFICATION_LIST_LIMIT,qt as NotificationRepository,St as ProjectRepository,d as RepositoryError,$t as RequestLogRepository,Lt as SpanRepository,Pn as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,gt as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,On as TASK_LOG_MIGRATION_TERMINAL_STATUSES,Ye as TaskLogRepository,xt as TaskRepository,Pt as ThreadBoxRepository,Ct as ThreadRepository,Ot as ToolCallRepository,jt as UsageLimitSnapshotRepository,Bt as UsageReportRepository,Et as WorkspaceRepository,tr as calcBucketStart,Mn as hasSufficientTaskLogMigrationFreeSpace,k as openDrizzleDb,Lo as pushSchema,yr as reclaimTemporaryJournal,$n as resolveTaskLogMigrationDbPath,Me as runMigrations,L as runMigrationsOnce,ys as runTaskLogMigration,bs as taskLogBackupName,i as tasks,Hn as tryCheckpointTaskLogWal};
|