@crewx/sdk 0.9.0-rc.75 → 0.9.0-rc.76
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +1 -1
- package/dist/esm/plugins/index.js +18 -18
- package/dist/esm/repository/index.js +2 -2
- package/dist/index.js +1 -1
- package/dist/plugins/index.js +17 -17
- package/dist/plugins/sqlite-tracing.d.ts +22 -0
- package/dist/repository/index.js +2 -2
- package/dist/repository/request-log.repository.d.ts +1 -0
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import*as Ae from'path';import Ae__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as Bn from'fs';import Bn__default,{existsSync,mkdirSync,readFileSync,statfsSync,statSync}from'fs';import rs,{homedir}from'os';import {randomUUID,createHash,randomBytes}from'crypto';import {sql,and,eq,asc,ne,isNull,desc,isNotNull,gt,lt as lt$1,or as or$1,notLike,like,inArray,gte,lte}from'drizzle-orm';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var tt=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Qo=()=>fileURLToPath(import.meta.url),Zo=()=>Ae__default.dirname(Qo()),y=Zo();var D=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(rs.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 c=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};var Yr=n=>{try{return Bn.statSync(`${n}-wal`).size}catch{return 0}},Qr=32*1024*1024;function k(n){let e=tt("better-sqlite3"),{drizzle:t}=tt("drizzle-orm/better-sqlite3"),r=new e(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${Qr}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),
|
|
1
|
+
import*as Ae from'path';import Ae__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as Bn from'fs';import Bn__default,{existsSync,mkdirSync,readFileSync,statfsSync,statSync}from'fs';import rs,{homedir}from'os';import {randomUUID,createHash,randomBytes}from'crypto';import {sql,and,eq,asc,ne,isNull,desc,isNotNull,gt,lt as lt$1,or as or$1,notLike,like,inArray,gte,lte}from'drizzle-orm';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var tt=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Qo=()=>fileURLToPath(import.meta.url),Zo=()=>Ae__default.dirname(Qo()),y=Zo();var D=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(rs.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 c=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};var Yr=n=>{try{return Bn.statSync(`${n}-wal`).size}catch{return 0}},Qr=32*1024*1024;function k(n){let e=tt("better-sqlite3"),{drizzle:t}=tt("drizzle-orm/better-sqlite3"),r=new e(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${Qr}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),{db:t(r),runRaw:(o,s=[])=>r.prepare(o).run(...s),close:()=>r.close()}}function ns(n,e="TRUNCATE"){if(e!=="PASSIVE"&&e!=="TRUNCATE")throw new Error(`Unsupported journal reclaim mode: ${e}`);let t=tt("better-sqlite3"),r=Yr(n),o;try{o=new t(n),o.pragma("busy_timeout = 1000");let s=o.pragma(`wal_checkpoint(${e})`),i=Yr(n);return {busy:s[0]?.busy===1,walBytesBefore:r,walBytesAfter:i}}finally{o?.close();}}var Zr=new Set,os={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT"};function ar(n,e){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function ss(n,e){if(e>0||!ar(n,"tasks"))return;let t=n.all("PRAGMA table_info(tasks)"),r=new Set(t.map(o=>o.name));for(let[o,s]of Object.entries(os))r.has(o)||n.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var is={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"}};function as(n,e,t){if(!ar(n,"__drizzle_migrations")||!ar(n,"tasks"))return;let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(Ae__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=is[i.tag];if(!d)continue;let l=Ae__default.join(e,`${i.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),p=createHash("sha256").update(u).digest("hex");if(o.has(p))continue;let _=n.all("PRAGMA table_info(tasks)"),g=new Set(_.map(f=>f.name));for(let[f,C]of Object.entries(d))g.has(f)||(n.run(`ALTER TABLE tasks ADD COLUMN ${f} ${C}`),g.add(f));}}function ds(n,e,t){let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(Ae__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=Ae__default.join(e,`${i.tag}.sql`);if(!existsSync(d))continue;let l=readFileSync(d,"utf-8"),u=createHash("sha256").update(l).digest("hex");if(o.has(u))continue;let p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,_=[],g;for(;(g=p.exec(l))!==null;)_.push({table:g[1],column:g[2]});if(_.length===0||!l.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:I})=>n.all(`PRAGMA table_info("${w}")`).some(z=>z.name===I))&&n.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${i.when})`);}}function rt(n){let{migrate:e}=tt("drizzle-orm/better-sqlite3/migrator"),{sql:t}=tt("drizzle-orm"),r=[Ae__default.join(y,"../migrations"),Ae__default.join(y,"migrations"),Ae__default.join(y,"../../../../drizzle/migrations"),Ae__default.join(process.cwd(),"drizzle/migrations")],o=r.find(u=>existsSync(Ae__default.join(u,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
2
2
|
${r.join(`
|
|
3
3
|
`)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ss(n,i),s?.cnt&&(ds(n,o,t),as(n,o,t)),e(n,{migrationsFolder:o});let l=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let u=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${u} (${l} migration${l>1?"s":""} applied).`);}}function x(n,e){Zr.has(e)||(rt(n),Zr.add(e));}var T=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 a=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)},n=>({log_storage_check:check("tasks_log_storage_ck",sql`${n.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));var Re=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},n=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(n.task_id,n.seq)}));var ws="json_extract(metadata, '$.threadTitle.state')",ks="json_extract(metadata, '$.threadTitle.priority')",h=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>T.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)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(n.workspace_id,n.updated_at),idx_threads_title:index("idx_threads_title").on(n.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(n.workspace_id,sql.raw(ws)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(n.workspace_id,sql.raw(ks))}));var Pe=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Pe.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")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));var Ee=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.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()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));var fe=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>h.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()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));var ot=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")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));var Q=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")},n=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.bucket_start)}));var ie=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")},n=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(n.workspace_id,n.month)}));var v=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")},n=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(n.workspace_id,sql`${n.created_at} DESC`)})),K=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},n=>({pk:primaryKey({columns:[n.notification_id,n.user_id]})}));var O=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()},n=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(n.workspace_id,n.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(n.workspace_id,n.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()},n=>({idCheck:check("ui_instances_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128 AND ${n.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${n.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${n.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${n.definition_hash}) = 64 AND ${n.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${n.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${n.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${n.domain_ref_json}) AND json_type(${n.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${n.state_json}) AND json_type(${n.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${n.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${n.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${n.granted_capabilities_json}) AND json_type(${n.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${n.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${n.updated_at} >= ${n.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(n.workspace_id,n.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")},n=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${n.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${n.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${n.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${n.actor_json}) AND json_type(${n.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${n.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${n.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${n.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${n.after_revision} IS NULL OR ${n.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${n.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${n.outcome} IS NULL OR ${n.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${n.input_json}) AND json_type(${n.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${n.result_json} IS NULL OR (json_valid(${n.result_json}) AND json_type(${n.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${n.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${n.settled_at} IS NULL OR ${n.settled_at} >= ${n.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
4
4
|
(${n.status} = 'requested' AND ${n.after_revision} IS NULL AND ${n.outcome} IS NULL AND ${n.settled_at} IS NULL)
|
|
@@ -368,4 +368,4 @@ ${r.join(`
|
|
|
368
368
|
`),u},{behavior:"immediate"})}}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,t,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(h).set({last_message:t,updated_at:s}).where(eq(h.id,e)).run();}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,t){if(!this.dbExists())return;let r=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),r.db.update(h).set(o).where(eq(h.id,e)).run();}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,t,r){let o=t;if(!o||typeof o!="object"||Array.isArray(o))return new et("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new et("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new et("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let l of [i.priority,i.state])if(l!=null&&(typeof l!="string"||l.length===0))return new et("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let l=r?and(eq(h.id,e),eq(h.workspace_id,r)):eq(h.id,e);return d.db.transaction(u=>{let p=u.select({metadata:h.metadata}).from(h).where(l).get();if(!p)return null;let _=St(p.metadata),g=_.threadTitle,f=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};i.priority===null?delete f.priority:i.priority!==void 0&&(f.priority=i.priority),i.state===null?delete f.state:i.state!==void 0&&(f.state=i.state),Object.keys(f).length>0?_.threadTitle=f:delete _.threadTitle;let C=Object.keys(_).length>0?JSON.stringify(_):null,w=new Date().toISOString();u.update(h).set({metadata:C,updated_at:w}).where(l).run();let I=u.select({metadata:h.metadata}).from(h).where(l).get();if(!I)throw new c("DB_ERROR","Thread-title metadata update could not be read back");let R=Ea(I.metadata);return {threadId:e,priority:R.priority,state:R.state}},{behavior:"immediate"})}catch(l){throw l instanceof c?l:new c("DB_ERROR","Failed to patch thread-title metadata",l)}finally{d.close();}}togglePin(e,t){let r=this.openHandle(true);try{let o=t?and(eq(h.id,e),eq(h.workspace_id,t)):eq(h.id,e);return r.db.transaction(s=>{let i=s.select({pinned:h.pinned,metadata:h.metadata}).from(h).where(o).get();if(!i)return null;let d=i.pinned?0:1,l=St(i.metadata);if(d){let u=t?and(eq(h.pinned,1),eq(h.workspace_id,t)):eq(h.pinned,1),p=s.select({metadata:h.metadata}).from(h).where(u).all(),_=null;for(let g of p){let f=St(g.metadata);typeof f.pinOrder=="number"&&(_===null||f.pinOrder<_)&&(_=f.pinOrder);}l.pinOrder=_===null?0:_-1;}else delete l.pinOrder;return s.update(h).set({pinned:d,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(o).run(),{pinned:!!d}},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,t){let r=this.openHandle(true);try{r.db.transaction(o=>{for(let s=0;s<e.length;s++){let i=t?and(eq(h.id,e[s]),eq(h.workspace_id,t)):eq(h.id,e[s]),d=o.select({metadata:h.metadata}).from(h).where(i).get();if(!d)continue;let l=St(d.metadata);l.pinOrder=s+1,o.update(h).set({metadata:JSON.stringify(l)}).where(i).run();}},{behavior:"immediate"});}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,t){let r=this.openHandle(true);try{let o=t?and(eq(h.id,e),eq(h.workspace_id,t)):eq(h.id,e),s=r.db.select({starred:h.starred}).from(h).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(h).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,t,r,o){let i=this.openHandle(true);try{let d=t?and(eq(h.id,e),eq(h.workspace_id,t)):eq(h.id,e);return i.db.transaction(u=>{let p=u.select({metadata:h.metadata}).from(h).where(d).get();if(!p)return null;let _=p.metadata?JSON.parse(p.metadata):{},g=_.overdrive??{},f=o?.defaultTurns??g.defaultTurns??3,C=o?.updatedBy??"ui",w=new Date().toISOString(),I,R,z,ze;switch(r){case "enable-count":{let Oe=o?.turns??f,Ne=o?.consumeCurrent?Math.max(Oe-1,0):Oe;I=Ne>0?"count":"off",R=Ne,z=!0,ze="count";break}case "enable-latch":{I="latch",R=0,z=!0,ze="latch";break}case "disable":{I="off",R=0,z=!1;break}default:{let Oe=g.state??"off",Ne=typeof g.remaining=="number"?g.remaining:0;if(Oe==="count"&&Ne>0){let Jr=Ne-1;Jr<=0?(I="off",R=0):(I="count",R=Jr),z=!0,ze="count";}else Oe==="latch"?(I="latch",R=0,z=!0,ze="latch"):(I="off",R=0,z=!1);break}}return _.overdrive={state:I,remaining:R,defaultTurns:f,updatedAt:w,updatedBy:C},u.update(h).set({metadata:JSON.stringify(_),updated_at:w}).where(d).run(),{applied:z,appliedMode:ze,state:I,remaining:R}},{behavior:"immediate"})}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to resolve overdrive",d)}finally{i.close();}}};var lt="THREAD_STATE",Zt="custom:";function Da(n){return n.dbPath?n.dbPath:n.dbRoot?join(n.dbRoot,".crewx","crewx.db"):process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(homedir(),".crewx","crewx.db")}function xr(n){if(!n)return null;try{let e=JSON.parse(n);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function mo(n){let t=xr(n)?.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.state;return typeof r=="string"&&r.startsWith(Zt)?r:null}function Nr(n){let e=[...n].length;return e>=1&&e<=20}function Oa(n){let e=n.select({id:h.id,workspace_id:h.workspace_id,metadata:h.metadata}).from(h).all(),t=[];for(let r of e){let o=mo(r.metadata);o!==null&&t.push({id:r.id,workspace_id:r.workspace_id,metadata:r.metadata,label:o.slice(Zt.length)});}return t}function Na(n){return n===null?isNull(m.workspace_id):eq(m.workspace_id,n)}function Aa(n){return n===null?isNull(m.workspace_id):or$1(isNull(m.workspace_id),eq(m.workspace_id,n))}function xa(n,e,t){let r=n.select().from(m).where(and(eq(m.code_group,lt),eq(m.code_name,e),Na(t),eq(m.is_builtin,0))).limit(1).get();if(r)return {code:r.code,created:false};let o=n.select({maxSortOrder:sql`max(${m.sort_order})`}).from(m).where(and(eq(m.code_group,lt),Aa(t))).get(),s=it();for(;n.select({code:m.code}).from(m).where(and(eq(m.code_group,lt),eq(m.code,s))).limit(1).get();)s=it();let i=new Date().toISOString();return n.insert(m).values({code_group:lt,code:s,code_name:e,color:"gray",sort_order:(o?.maxSortOrder??-1)+1,workspace_id:t,is_builtin:0,is_archived:0,metadata:null,created_at:i,updated_at:i}).run(),{code:s,created:true}}function La(n,e,t,r){let o=n.select({id:h.id,workspace_id:h.workspace_id,metadata:h.metadata}).from(h).all(),s=`${Zt}${e}`,i=0,d=new Date().toISOString();for(let l of o){if(r!==null&&l.workspace_id!==r||mo(l.metadata)!==s)continue;let u=xr(l.metadata)??{},p=u.threadTitle,_=p&&typeof p=="object"&&!Array.isArray(p)?{...p}:{};_.state=t,u.threadTitle=_,n.update(h).set({metadata:JSON.stringify(u),updated_at:d}).where(eq(h.id,l.id)).run(),i+=1;}return i}function Ar(n,e,t){return n.transaction(r=>{let o=xa(r,e,t),s=La(r,e,o.code,t);return {...o,migratedRows:s}},{behavior:"immediate"})}function Pa(n,e){return n.select({code:m.code}).from(m).where(and(eq(m.code_group,lt),eq(m.code_name,e),isNull(m.workspace_id),eq(m.is_builtin,0))).limit(1).get()?.code??null}function $a(n){let e=new Set(n.select({code:m.code}).from(m).where(eq(m.code_group,lt)).all().map(s=>s.code)),t=n.select({metadata:h.metadata}).from(h).all(),r=0,o=0;for(let s of t){let d=xr(s.metadata)?.threadTitle;if(!d||typeof d!="object"||Array.isArray(d))continue;let l=d.state;typeof l=="string"&&(l.startsWith(Zt)&&(r+=1),e.has(l)||(o+=1));}return {remainingCustomReferences:r,orphanReferences:o}}function wo(n={}){let e=Da(n);if(!existsSync(e))return {migratedRows:0,createdCodes:0,remainingCustomReferences:0,orphanReferences:0};let t=k(e);try{x(t.db,e);let r=Oa(t.db),o=new Set;for(let p of n.configuredLabels??[])typeof p=="string"&&o.add(p);let s=new Set(o),i=new Map;for(let p of r)if(Nr(p.label))if(p.workspace_id===null)s.add(p.label);else {let _=i.get(p.workspace_id)??new Set;_.add(p.label),i.set(p.workspace_id,_);}let d=0,l=0,u=new Map;for(let p of [...s].sort()){if(!Nr(p))continue;let _=Ar(t.db,p,null);u.set(p,_.code),d+=_.migratedRows,_.created&&(l+=1);}for(let p of [...i.keys()].sort())for(let _ of [...i.get(p)].sort()){if(!Nr(_)||u.has(_))continue;if(Pa(t.db,_)){let f=Ar(t.db,_,null);u.set(_,f.code),d+=f.migratedRows,f.created&&(l+=1);continue}let g=Ar(t.db,_,p);d+=g.migratedRows,g.created&&(l+=1);}return {migratedRows:d,createdCodes:l,...$a(t.db)}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to migrate legacy thread-title common codes",r)}finally{t.close();}}var ja=wo;var yo=["urgent","high","medium","low"],To=["investigating","in-progress","in-review","on-hold","done"],vt="custom:";var Ma=new Set(yo),Ba=new Set(To),Ha={urgent:"U \uAE34\uAE09 Urgent",high:"P0 \uAE09\uD568 High",medium:"P1 \uC911\uC694 Medium",low:"P2 \uBCF4\uD1B5 Low"},Lr={investigating:"\uC870\uC0AC\uC911 Looking into","in-progress":"\uC9C4\uD589\uC911 In progress","in-review":"\uAC80\uD1A0\uC911 In review","on-hold":"\uBCF4\uB958 On hold",done:"\uC644\uB8CC Done"};function ko(n,e){return !e||e.includes(n)?e??n:`${n} ${e}`}function It(n){return typeof n=="string"&&Ma.has(n)}function Ct(n){if(typeof n!="string")return false;if(Ba.has(n))return true;if(n.startsWith("c_"))return n.length>2;if(!n.startsWith(vt))return false;let e=n.slice(vt.length);return e.length>=1&&e.length<=20}function bo(n){if(n.startsWith(vt))return n.slice(vt.length)}function Pr(n){if(!n)return null;try{let e=JSON.parse(n);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function qa(n){let e=Pr(n);return !!e&&Object.prototype.hasOwnProperty.call(e,"threadTitle")}function er(n){let e=Pr(n);if(!e)return {};let t=e.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return {};let r=t,o={};return It(r.priority)&&(o.priority=r.priority),Ct(r.state)&&(o.state=r.state),o}function $r(n,e){let t=Pr(n)??{},r={...er(n)};return e.priority===null?delete r.priority:e.priority!==void 0&&(r.priority=e.priority),e.state===null?delete r.state:e.state!==void 0&&(r.state=e.state),r.priority===void 0&&r.state===void 0?delete t.threadTitle:t.threadTitle=r,Object.keys(t).length===0?null:JSON.stringify(t)}function Fa(n,e=new Map){let t=[];return n.priority&&t.push(ko(Ha[n.priority],e.get(n.priority))),n.state&&(n.state.startsWith(vt)?t.push(bo(n.state)??""):Lr[n.state]?t.push(ko(Lr[n.state],e.get(n.state))):e.has(n.state)?t.push(n.state,e.get(n.state)??""):n.state.startsWith("c_")?t.push(n.state):t.push(Lr[n.state]??"")),t.filter(Boolean).join(" ")}function Ro(n,e){if(!n||n.trim().length===0)return;let t=new Set,r=false,o=false;for(let s of n.split(",")){let i=s.trim();if(i){if(i==="none"){r=true,o=true;continue}e(i)&&(t.add(i),o=true);}}if(o)return {values:t,includeNone:r}}function Ua(n){return Ro(n,It)}function za(n){return Ro(n,Ct)}function Wa(n,e){return e?n?e.values.has(n):e.includeNone:true}var ir=class extends c{threadId;highlightId;expectedRevision;currentRevision;constructor(e,t,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=t,this.expectedRevision=r,this.currentRevision=o;}},ht=class extends ir{},Ja=new Set(mn),Ya=new Set(fn),Xa=new Set(wn),Qa=new Set(kn),Za=50,Io=100,Co=280;function U(n){throw new c("VALIDATION",n)}function pt(n){throw new c("NOT_FOUND",n)}function G(n,e){(typeof n!="string"||n.trim().length===0)&&U(`${e} is required`);}function tr(n={}){let e=n.actor??n,t=e.actorType??"system";return Ja.has(t)||U(`invalid actorType: ${String(t)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&U("actorId must be a string or null"),{actorType:t,actorId:e.actorId??null}}function ed(n){G(n.threadId,"threadId"),n.workspaceId!==void 0&&n.workspaceId!==null&&G(n.workspaceId,"workspaceId"),n.title!==void 0&&n.title!==null&&((typeof n.title!="string"||n.title.trim().length===0)&&U("title must not be empty"),n.title.length>120&&U("title must be at most 120 characters")),n.priority!==void 0&&n.priority!==null&&!It(n.priority)&&U(`invalid priority: ${String(n.priority)}`),n.state!==void 0&&n.state!==null&&!Ct(n.state)&&U(`invalid state: ${String(n.state)}`);}function td(n){n.beforeSeq!==void 0&&n.afterSeq!==void 0&&U("beforeSeq and afterSeq cannot be used together");for(let[t,r]of [["beforeSeq",n.beforeSeq],["afterSeq",n.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&U(`${t} must be a non-negative integer`);let e=n.limit??Za;return (!Number.isInteger(e)||e<1||e>Io)&&U(`limit must be between 1 and ${Io}`),e}function Do(n){typeof n!="string"&&U("text is required");let e=n.trim();return e.length===0&&U("text must not be empty"),e.length>Co&&U(`text must be at most ${Co} characters`),e}function _t(n,e){return G(n??"",e),n}function Oo(n){Qa.has(n)||U(`invalid highlight kind: ${String(n)}`);}function rd(n){Xa.has(n)||U(`invalid highlight source: ${String(n)}`);}function nd(n){G(n.threadId,"threadId"),G(n.workspaceId,"workspaceId");let e=n.source??"manual";rd(e),Oo(n.kind);let t=Do(n.text),r=n.coversFromTaskId??n.fromTaskId??n.taskId,o=n.coversToTaskId??n.toTaskId??n.taskId;if(e==="manual"){let p=n.taskId??(r&&o&&r===o?r:void 0),_=_t(p,"taskId");return (r!==_||o!==_)&&U("manual highlights must cover exactly one task"),{source:e,kind:n.kind,text:t,coversFromTaskId:_,coversToTaskId:_,agentId:n.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=_t(r,"coversFromTaskId"),i=_t(o,"coversToTaskId"),d=n.sourceTaskId??s,l=n.detectorVersion??(n.idempotencyKey!==void 0?"default":null),u=n.contentFingerprint??n.idempotencyKey??null;return _t(d??void 0,"sourceTaskId"),_t(l??void 0,"detectorVersion"),_t(u??void 0,"contentFingerprint"),{source:e,kind:n.kind,text:t,coversFromTaskId:s,coversToTaskId:i,agentId:n.agentId??null,sourceTaskId:d,detectorVersion:l,contentFingerprint:u}}function sr(n){let e=er(n.metadata);return {threadId:n.id,workspaceId:n.workspace_id,title:n.title,priority:e.priority??null,state:e.state??null,metadata:n.metadata,titleLocked:n.title_locked===1,updatedAt:n.updated_at}}function od(n){try{let e=JSON.stringify(n);return (!e||e==="null"||e.startsWith("["))&&U("event payload must be a JSON object"),e}catch(e){throw new c("VALIDATION","event payload must be JSON serializable",e)}}function rr(n,e){return n.select({maxSeq:sql`COALESCE(MAX(${P.seq}), 0)`}).from(P).where(eq(P.thread_id,e)).get()?.maxSeq??0}function nr(n,e){return !!n.select({id:P.id}).from(P).where(eq(P.thread_id,e)).limit(1).get()}function Nt(n,e){Ya.has(e.type)||U(`invalid thread event type: ${String(e.type)}`);let t=be("the");n.insert(P).values({id:t,thread_id:e.threadId,seq:e.seq,type:e.type,actor_type:e.actorType,actor_id:e.actorId,task_id:e.taskId??null,highlight_id:e.highlightId??null,payload_json:od(e.payload),created_at:e.createdAt}).run();let r=n.select().from(P).where(eq(P.id,t)).get();if(!r)throw new c("DB_ERROR","Thread event insert did not return a row");return r}function or(n,e,t,r,o){let s=sr(e);Nt(n,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:t.actorType,actorId:t.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function jr(n){return {highlightId:n.id,source:n.source,kind:n.kind,status:n.status,coversFromTaskId:n.covers_from_task_id,coversToTaskId:n.covers_to_task_id,revision:n.revision,...n.dismissed_at===null?{}:{dismissedAt:n.dismissed_at}}}function Mr(n,e,t,r,o,s,i){let d=o==="thread.highlight.created"?jr(e):{before:i?jr({...e,...i,id:e.id}):void 0,after:jr(e)};return Nt(n,{threadId:e.thread_id,seq:s,type:o,actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:d})}var Br=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 c("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}findThread(e,t,r){let o=eq(h.id,t),s=r===void 0?o:r===null?and(o,isNull(h.workspace_id)):and(o,eq(h.workspace_id,r));return e.select().from(h).where(s).limit(1).get()}resolveWorkspaceId(e){if(G(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let t=this.openHandle(false);try{return t.db.select({workspaceId:h.workspace_id}).from(h).where(eq(h.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to resolve thread workspace",r)}finally{t.close();}}updateSnapshot(e){ed(e);let t=tr(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||pt(`Thread ${e.threadId} not found`);let d=sr(i),l=e.title!==void 0,u=l&&e.title!==d.title,p=l&&i.title_locked!==1,_=e.priority!==void 0&&e.priority!==d.priority,g=e.state!==void 0&&e.state!==d.state,f=u||_||g;if(!f&&!p)return d;let C=i.metadata;(_||g)&&(C=$r(i.metadata,{priority:e.priority,state:e.state}));let w={};if(f&&(w.metadata=C,w.updated_at=r),u&&(w.title=e.title),l&&(w.title_locked=1),s.update(h).set(w).where(e.workspaceId===void 0?eq(h.id,e.threadId):e.workspaceId===null?and(eq(h.id,e.threadId),isNull(h.workspace_id)):and(eq(h.id,e.threadId),eq(h.workspace_id,e.workspaceId))).run(),!f){let z={...i,title_locked:1};return sr(z)}let I=rr(s,i.id)+1;nr(s,i.id)||(or(s,i,t,r,I),I+=1),u&&(Nt(s,{threadId:i.id,seq:I,type:"thread.title.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),I+=1),_&&(Nt(s,{threadId:i.id,seq:I,type:"thread.priority.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),I+=1),g&&Nt(s,{threadId:i.id,seq:I,type:"thread.state.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let R={...i,title:u?e.title:i.title,metadata:C,title_locked:l?1:i.title_locked,updated_at:r};return sr(R)},{behavior:"immediate"})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,t){if(G(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,t)?r.db.select({maxSeq:sql`COALESCE(MAX(${P.seq}), 0)`}).from(P).where(eq(P.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listTimeline(e,t,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:t}:e;G(o.threadId,"threadId"),G(o.workspaceId,"workspaceId");let s=td(o);if(!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let d=i.db.select({maxSeq:sql`COALESCE(MAX(${P.seq}), 0)`}).from(P).where(eq(P.thread_id,o.threadId)).get()?.maxSeq??0,l;o.beforeSeq!==void 0?l=i.db.select().from(P).where(and(eq(P.thread_id,o.threadId),lt$1(P.seq,o.beforeSeq))).orderBy(desc(P.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?l=i.db.select().from(P).where(and(eq(P.thread_id,o.threadId),sql`${P.seq} > ${o.afterSeq}`)).orderBy(asc(P.seq)).limit(s+1).all():l=i.db.select().from(P).where(eq(P.thread_id,o.threadId)).orderBy(desc(P.seq)).limit(s+1).all().reverse();let u=l.length>s,p=o.afterSeq!==void 0?l.slice(0,s):u?l.slice(1):l,_=!1,g=p[0];return g&&(_=!!i.db.select({id:P.id}).from(P).where(and(eq(P.thread_id,o.threadId),lt$1(P.seq,g.seq))).limit(1).get()),{items:p,latestSeq:d,hasMoreOlder:_}}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to list thread timeline",d)}finally{i.close();}}listEvents(e,t,r){return this.listTimeline(e,t,r)}getTimeline(e,t,r){return this.listTimeline(e,t,r)}createHighlight(e){let t=nd(e),r=tr(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);if(d||pt(`Thread ${e.threadId} not found`),t.source==="auto"){let g=i.select().from(A).where(and(eq(A.thread_id,e.threadId),eq(A.source_task_id,t.sourceTaskId),eq(A.detector_version,t.detectorVersion),eq(A.content_fingerprint,t.contentFingerprint))).orderBy(asc(A.created_at),asc(A.id)).limit(1).get();if(g)return g}let l=e.id??be("thl"),u={id:l,thread_id:e.threadId,source:t.source,kind:t.kind,status:"active",text:t.text,covers_from_task_id:t.coversFromTaskId,covers_to_task_id:t.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:t.agentId,source_task_id:t.sourceTaskId,detector_version:t.detectorVersion,content_fingerprint:t.contentFingerprint,dismissed_at:null};i.insert(A).values(u).run();let p=i.select().from(A).where(eq(A.id,l)).get();if(!p)throw new c("DB_ERROR","Highlight insert did not return a row");let _=rr(i,d.id)+1;return nr(i,d.id)||(or(i,d,r,o,_),_+=1),Mr(i,p,r,o,"thread.highlight.created",_),p},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){G(e.threadId,"threadId"),G(e.workspaceId,"workspaceId"),G(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&U("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&U("highlight update requires at least one field"),e.kind!==void 0&&Oo(e.kind);let t=e.text===void 0?void 0:Do(e.text),r=tr(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);d||pt(`Thread ${e.threadId} not found`);let l=i.select().from(A).where(and(eq(A.id,e.highlightId),eq(A.thread_id,d.id))).limit(1).get();if(l||pt(`Highlight ${e.highlightId} not found`),l.revision!==e.expectedRevision)throw new ht(d.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new ht(d.id,l.id,e.expectedRevision,l.revision);let u=e.kind??l.kind,p=t??l.text,_=e.coversFromTaskId??l.covers_from_task_id,g=e.coversToTaskId??l.covers_to_task_id;(!p||_.length===0||g.length===0)&&U("highlight projection is incomplete");let f=u!==l.kind||p!==l.text||_!==l.covers_from_task_id||g!==l.covers_to_task_id,C=r.actorType==="user"&&l.source==="auto"&&f?"manual":l.source;if(!(f||C!==l.source))return l;let I=l.revision+1;i.update(A).set({source:C,kind:u,text:p,covers_from_task_id:_,covers_to_task_id:g,revision:I,updated_at:o}).where(and(eq(A.id,l.id),eq(A.revision,l.revision))).run();let R=i.select().from(A).where(eq(A.id,l.id)).get();if(!R)throw new c("DB_ERROR","Highlight update did not return a row");let z=rr(i,d.id)+1;return nr(i,d.id)||(or(i,d,r,o,z),z+=1),Mr(i,R,r,o,"thread.highlight.updated",z,l),R},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){G(e.threadId,"threadId"),G(e.workspaceId,"workspaceId"),G(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&U("expectedRevision must be a non-negative integer");let t=tr(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||pt(`Thread ${e.threadId} not found`);let d=s.select().from(A).where(and(eq(A.id,e.highlightId),eq(A.thread_id,i.id))).limit(1).get();if(d||pt(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new ht(i.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let l=d.revision+1;s.update(A).set({status:"dismissed",text:null,revision:l,updated_at:r,dismissed_at:r}).where(and(eq(A.id,d.id),eq(A.revision,d.revision))).run();let u=s.select().from(A).where(eq(A.id,d.id)).get();if(!u)throw new c("DB_ERROR","Highlight dismissal did not return a row");let p=rr(s,i.id)+1;return nr(s,i.id)||(or(s,i,t,r,p),p+=1),Mr(s,u,t,r,"thread.highlight.deleted",p,d),u},{behavior:"immediate"})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,t,r={}){if(G(e,"threadId"),G(t,"workspaceId"),r.taskId!==void 0&&G(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&G(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&G(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,t))return null;let i=o.db.select().from(A).where(and(eq(A.thread_id,e),eq(A.status,"active"))).orderBy(asc(A.created_at),asc(A.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let d=o.db.all(sql`
|
|
369
369
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
370
370
|
ORDER BY started_at ASC, id ASC
|
|
371
|
-
`),l=new Map(d.map((g,f)=>[g.id,f])),u=r.taskId===void 0?void 0:l.get(r.taskId),p=r.coversFromTaskId===void 0?void 0:l.get(r.coversFromTaskId),_=r.coversToTaskId===void 0?void 0:l.get(r.coversToTaskId);return i.filter(g=>{let f=l.get(g.covers_from_task_id),C=l.get(g.covers_to_task_id);if(f===void 0||C===void 0)return !1;let w=Math.min(f,C),I=Math.max(f,C);return !(u!==void 0&&(u<w||u>I)||p!==void 0&&I<p||_!==void 0&&w>_)})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,t,r){return this.listActiveHighlights(e,t,r)}getActiveHighlights(e,t,r){return this.listActiveHighlights(e,t,r)}};var Hr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}insertSpan(e){let t=this.openHandle(true);try{t.db.insert(Pe).values(e).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert span",r)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Pe).where(eq(Pe.task_id,e)).all()}catch(r){throw new c("DB_ERROR","Failed to find spans by task id",r)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(Pe).where(eq(Pe.id,e)).limit(1).get()??void 0}catch(r){throw new c("DB_ERROR","Failed to find span by id",r)}finally{t.close();}}};var qr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}insertToolCall(e){let t=this.openHandle(true);try{t.db.insert(Ee).values(e).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert tool call",r)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Ee).where(eq(Ee.task_id,e)).all()}catch(r){throw new c("DB_ERROR","Failed to find tool calls by task id",r)}finally{t.close();}}aggregateByName(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select({toolName:Ee.tool_name,count:sql`count(*)`}).from(Ee).where(eq(Ee.task_id,e)).groupBy(Ee.tool_name).all().map(r=>({toolName:r.toolName,count:r.count}))}catch(r){throw new c("DB_ERROR","Failed to aggregate tool calls by name",r)}finally{t.close();}}};var Fr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}ensureThreadExists(e,t){if(!e.db.select({id:h.id}).from(h).where(eq(h.id,t)).limit(1).get())throw new c("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(fe).where(eq(fe.thread_id,e)).orderBy(asc(fe.seq)).all()}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to find boxes by thread id",r)}finally{t.close();}}findById(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(fe).where(and(eq(fe.id,t),eq(fe.thread_id,e))).limit(1).get()??void 0}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to find box by id",o)}finally{r.close();}}insert(e){let t=this.openHandle(true);try{this.ensureThreadExists(t,e.threadId);try{t.db.insert(fe).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 c("CONFLICT",`Duplicate seq ${String(e.seq)} for thread ${e.threadId}`,o):o}let r=t.db.select().from(fe).where(eq(fe.id,e.id)).limit(1).get();if(!r)throw new c("DB_ERROR","Insert did not return a row");return r}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert thread box",r)}finally{t.close();}}};var Ur=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}bulkInsert(e){if(e.length===0)return;let t=this.openHandle(true);try{let r=new Date().toISOString();t.db.transaction(o=>{for(let s of e)o.insert(ot).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:r,metadata:s.metadata??null}).run();});}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to bulk insert request logs",r)}finally{t.close();}}findRecent(e=100){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(ot).orderBy(desc(ot.timestamp)).limit(e).all()}catch(r){throw new c("DB_ERROR","Failed to find recent request logs",r)}finally{t.close();}}};function Mo(n){return new Date(Math.floor(n/3e5)*3e5).toISOString()}var zr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}upsert(e){let t=this.openHandle(true);try{let r=Mo(e.bucketStartMs),o=e.accountRef??"default";t.db.insert(Q).values({id:e.id,provider:e.provider,account_ref:o,limit_window:e.limitWindow,bucket_start:r,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:[Q.provider,Q.account_ref,Q.limit_window,Q.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(r){throw r instanceof c?r:new c("DB_ERROR","Failed to upsert usage limit snapshot",r)}finally{t.close();}}getTrends(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let r=t.db.select({provider:Q.provider,bucket_start:Q.bucket_start,used_percent:Q.used_percent,remaining_percent:Q.remaining_percent,resets_at:Q.resets_at}).from(Q).where(and(eq(Q.limit_window,e.window),gte(Q.bucket_start,e.fromIso),lte(Q.bucket_start,e.toIso))).orderBy(asc(Q.bucket_start)).all(),o=new Map;for(let s of r)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,i])=>({provider:s,points:i}))}catch(r){throw new c("DB_ERROR","Failed to get usage limit trends",r)}finally{t.close();}}};var Wr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}publish(e){let t=this.openHandle(true);try{t.db.insert(ie).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:[ie.workspace_id,ie.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 r=t.db.select().from(ie).where(and(eq(ie.workspace_id,e.workspaceId),eq(ie.month,e.month))).limit(1).get();if(!r)throw new c("DB_ERROR","Failed to read back published usage report");return r}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to publish usage report",r)}finally{t.close();}}findByMonth(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(ie).where(and(eq(ie.workspace_id,e),eq(ie.month,t))).limit(1).get()??void 0}catch(o){throw new c("DB_ERROR","Failed to find usage report",o)}finally{r.close();}}listByWorkspace(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(ie).where(eq(ie.workspace_id,e)).orderBy(desc(ie.month)).all()}catch(r){throw new c("DB_ERROR","Failed to list usage reports",r)}finally{t.close();}}};var Wo=500,Go=50,Gr=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??Wo;}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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}create(e){let t=this.openHandle(true);try{let r=be("ntf"),o=new Date().toISOString();return t.db.insert(v).values({id:r,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:r}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to create notification",r)}finally{t.close();}}enforceCap(e,t){let s=(e.db.select({count:sql`count(*)`}).from(v).where(eq(v.workspace_id,t)).get()?.count??0)-this.cap;if(s<=0)return;let d=e.db.select({id:v.id}).from(v).innerJoin(K,eq(K.notification_id,v.id)).where(eq(v.workspace_id,t)).groupBy(v.id).orderBy(asc(v.created_at)).limit(s).all().map(l=>l.id);d.length!==0&&(e.db.delete(K).where(inArray(K.notification_id,d)).run(),e.db.delete(v).where(inArray(v.id,d)).run());}list(e){if(!this.dbExists())return [];let t=e.limit??Go,r=this.openHandle(false);try{return r.db.select({id:v.id,workspace_id:v.workspace_id,agent_id:v.agent_id,task_id:v.task_id,thread_id:v.thread_id,source:v.source,level:v.level,title:v.title,body:v.body,target_user_id:v.target_user_id,created_at:v.created_at,metadata:v.metadata,read_at:K.read_at}).from(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(eq(v.workspace_id,e.workspaceId)).orderBy(desc(v.created_at)).limit(t).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(o){throw new c("DB_ERROR","Failed to list notifications",o)}finally{r.close();}}unreadCount(e){if(!this.dbExists())return 0;let t=this.openHandle(false);try{return t.db.select({count:sql`count(*)`}).from(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(and(eq(v.workspace_id,e.workspaceId),isNull(K.notification_id))).get()?.count??0}catch(r){throw new c("DB_ERROR","Failed to count unread notifications",r)}finally{t.close();}}markRead(e){let t=this.openHandle(true);try{if(!t.db.select({id:v.id}).from(v).where(and(eq(v.id,e.notificationId),eq(v.workspace_id,e.workspaceId))).get())throw new c("NOT_FOUND","Notification not found in workspace");return t.db.insert(K).values({notification_id:e.notificationId,user_id:e.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark notification read",r)}finally{t.close();}}markAllRead(e){let t=this.openHandle(true);try{let r=t.db.select({id:v.id}).from(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(and(eq(v.workspace_id,e.workspaceId),isNull(K.notification_id))).all();if(r.length===0)return 0;let o=new Date().toISOString();return t.db.transaction(s=>{for(let i of r)s.insert(K).values({notification_id:i.id,user_id:e.userId,read_at:o}).onConflictDoNothing().run();}),r.length}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark all notifications read",r)}finally{t.close();}}};var Jo=50,Vr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}create(e){let t=this.openHandle(true);try{let r=new Date().toISOString(),o=[],s=e.map(i=>{let d=be("sug");return o.push(d),{id:d,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:r,updated_at:r}});return s.length>0&&t.db.insert(O).values(s).run(),{ids:o}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to create agent suggestions",r)}finally{t.close();}}findLatestSet(e,t){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=r.db.select({task_id:O.task_id}).from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t))).orderBy(desc(O.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?isNull(O.task_id):eq(O.task_id,o.task_id);return r.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),s)).orderBy(asc(O.created_at)).all()}catch(o){throw new c("DB_ERROR","Failed to find latest agent suggestion set",o)}finally{r.close();}}findSetByTaskId(e,t,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.task_id,r))).orderBy(asc(O.created_at)).all()}catch(s){throw new c("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{o.close();}}findById(e,t,r){if(!this.dbExists())return null;let o=this.openHandle(false);try{return o.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.id,r))).get()??null}catch(s){throw new c("DB_ERROR","Failed to find agent suggestion by id",s)}finally{o.close();}}updateStatus(e,t,r){let o=this.openHandle(true);try{let s={status:t,updated_at:new Date().toISOString()};return r!==void 0&&(s.applied_commit_sha=r),o.db.update(O).set(s).where(eq(O.id,e)).run().changes>0}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to update agent suggestion status",s)}finally{o.close();}}listByAgent(e,t,r=Jo){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t))).orderBy(desc(O.created_at)).limit(r).all()}catch(s){throw new c("DB_ERROR","Failed to list agent suggestions",s)}finally{o.close();}}findDismissed(e,t,r=20){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.status,"dismissed"))).orderBy(desc(O.updated_at)).limit(r).all()}catch(s){throw new c("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};export{Vr as AgentSuggestionRepository,To as BUILTIN_THREAD_STATES,D as BaseSqliteRepository,qt as COMMON_CODE_COLORS,Ht as COMMON_CODE_GROUPS,Qr as CREWX_JOURNAL_SIZE_LIMIT_BYTES,fr as CommonCodeRepository,J as CommonCodeRepositoryError,Jo as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,Wo as DEFAULT_NOTIFICATION_CAP,Go as DEFAULT_NOTIFICATION_LIST_LIMIT,Pn as DEFAULT_PROJECT_STAGES,br as DEFAULT_PROJECT_STAGE_KEYS,Gr as NotificationRepository,Tr as ProjectRepository,c as RepositoryError,Ur as RequestLogRepository,Hr as SpanRepository,ro as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,Yt as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,to as TASK_LOG_MIGRATION_TERMINAL_STATUSES,yo as THREAD_PRIORITIES,bt as TaskLogRepository,Sr as TaskRepository,Fr as ThreadBoxRepository,ht as ThreadHighlightConflictError,ir as ThreadHistoryConflictError,Br as ThreadHistoryRepository,Or as ThreadRepository,et as ThreadTitleMetadataPatchError,qr as ToolCallRepository,zr as UsageLimitSnapshotRepository,Wr as UsageReportRepository,yr as WorkspaceRepository,Mo as calcBucketStart,bo as customStateLabel,it as generateCommonCodeId,ao as hasSufficientTaskLogMigrationFreeSpace,qa as hasThreadTitleKey,It as isThreadPriority,Ct as isThreadState,Wa as matchesThreadTitleFilter,$r as mergeThreadTitleMeta,wo as migrateLegacyThreadTitleCommonCodes,ja as migrateThreadTitleCommonCodes,k as openDrizzleDb,Ua as parseThreadPriorityFilter,za as parseThreadStateFilter,Ni as pushSchema,er as readThreadTitleMeta,ns as reclaimTemporaryJournal,no as resolveTaskLogMigrationDbPath,rt as runMigrations,x as runMigrationsOnce,wa as runTaskLogMigration,ka as taskLogBackupName,a as tasks,Fa as threadTitleSearchHaystack,uo as tryCheckpointTaskLogWal};
|
|
371
|
+
`),l=new Map(d.map((g,f)=>[g.id,f])),u=r.taskId===void 0?void 0:l.get(r.taskId),p=r.coversFromTaskId===void 0?void 0:l.get(r.coversFromTaskId),_=r.coversToTaskId===void 0?void 0:l.get(r.coversToTaskId);return i.filter(g=>{let f=l.get(g.covers_from_task_id),C=l.get(g.covers_to_task_id);if(f===void 0||C===void 0)return !1;let w=Math.min(f,C),I=Math.max(f,C);return !(u!==void 0&&(u<w||u>I)||p!==void 0&&I<p||_!==void 0&&w>_)})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,t,r){return this.listActiveHighlights(e,t,r)}getActiveHighlights(e,t,r){return this.listActiveHighlights(e,t,r)}};var Hr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}insertSpan(e){let t=this.openHandle(true);try{t.db.insert(Pe).values(e).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert span",r)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Pe).where(eq(Pe.task_id,e)).all()}catch(r){throw new c("DB_ERROR","Failed to find spans by task id",r)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(Pe).where(eq(Pe.id,e)).limit(1).get()??void 0}catch(r){throw new c("DB_ERROR","Failed to find span by id",r)}finally{t.close();}}};var qr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}insertToolCall(e){let t=this.openHandle(true);try{t.db.insert(Ee).values(e).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert tool call",r)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Ee).where(eq(Ee.task_id,e)).all()}catch(r){throw new c("DB_ERROR","Failed to find tool calls by task id",r)}finally{t.close();}}aggregateByName(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select({toolName:Ee.tool_name,count:sql`count(*)`}).from(Ee).where(eq(Ee.task_id,e)).groupBy(Ee.tool_name).all().map(r=>({toolName:r.toolName,count:r.count}))}catch(r){throw new c("DB_ERROR","Failed to aggregate tool calls by name",r)}finally{t.close();}}};var Fr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}ensureThreadExists(e,t){if(!e.db.select({id:h.id}).from(h).where(eq(h.id,t)).limit(1).get())throw new c("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(fe).where(eq(fe.thread_id,e)).orderBy(asc(fe.seq)).all()}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to find boxes by thread id",r)}finally{t.close();}}findById(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(fe).where(and(eq(fe.id,t),eq(fe.thread_id,e))).limit(1).get()??void 0}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to find box by id",o)}finally{r.close();}}insert(e){let t=this.openHandle(true);try{this.ensureThreadExists(t,e.threadId);try{t.db.insert(fe).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 c("CONFLICT",`Duplicate seq ${String(e.seq)} for thread ${e.threadId}`,o):o}let r=t.db.select().from(fe).where(eq(fe.id,e.id)).limit(1).get();if(!r)throw new c("DB_ERROR","Insert did not return a row");return r}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert thread box",r)}finally{t.close();}}};var Ur=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}bulkInsert(e){if(e.length===0)return;let t=this.openHandle(true);try{t.db.transaction(r=>{for(let o of e)r.insert(ot).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:o.timestamp??new Date().toISOString(),metadata:o.metadata??null}).run();});}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to bulk insert request logs",r)}finally{t.close();}}findRecent(e=100){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(ot).orderBy(desc(ot.timestamp)).limit(e).all()}catch(r){throw new c("DB_ERROR","Failed to find recent request logs",r)}finally{t.close();}}};function Mo(n){return new Date(Math.floor(n/3e5)*3e5).toISOString()}var zr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}upsert(e){let t=this.openHandle(true);try{let r=Mo(e.bucketStartMs),o=e.accountRef??"default";t.db.insert(Q).values({id:e.id,provider:e.provider,account_ref:o,limit_window:e.limitWindow,bucket_start:r,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:[Q.provider,Q.account_ref,Q.limit_window,Q.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(r){throw r instanceof c?r:new c("DB_ERROR","Failed to upsert usage limit snapshot",r)}finally{t.close();}}getTrends(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let r=t.db.select({provider:Q.provider,bucket_start:Q.bucket_start,used_percent:Q.used_percent,remaining_percent:Q.remaining_percent,resets_at:Q.resets_at}).from(Q).where(and(eq(Q.limit_window,e.window),gte(Q.bucket_start,e.fromIso),lte(Q.bucket_start,e.toIso))).orderBy(asc(Q.bucket_start)).all(),o=new Map;for(let s of r)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,i])=>({provider:s,points:i}))}catch(r){throw new c("DB_ERROR","Failed to get usage limit trends",r)}finally{t.close();}}};var Wr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}publish(e){let t=this.openHandle(true);try{t.db.insert(ie).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:[ie.workspace_id,ie.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 r=t.db.select().from(ie).where(and(eq(ie.workspace_id,e.workspaceId),eq(ie.month,e.month))).limit(1).get();if(!r)throw new c("DB_ERROR","Failed to read back published usage report");return r}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to publish usage report",r)}finally{t.close();}}findByMonth(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(ie).where(and(eq(ie.workspace_id,e),eq(ie.month,t))).limit(1).get()??void 0}catch(o){throw new c("DB_ERROR","Failed to find usage report",o)}finally{r.close();}}listByWorkspace(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(ie).where(eq(ie.workspace_id,e)).orderBy(desc(ie.month)).all()}catch(r){throw new c("DB_ERROR","Failed to list usage reports",r)}finally{t.close();}}};var Wo=500,Go=50,Gr=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??Wo;}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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}create(e){let t=this.openHandle(true);try{let r=be("ntf"),o=new Date().toISOString();return t.db.insert(v).values({id:r,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:r}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to create notification",r)}finally{t.close();}}enforceCap(e,t){let s=(e.db.select({count:sql`count(*)`}).from(v).where(eq(v.workspace_id,t)).get()?.count??0)-this.cap;if(s<=0)return;let d=e.db.select({id:v.id}).from(v).innerJoin(K,eq(K.notification_id,v.id)).where(eq(v.workspace_id,t)).groupBy(v.id).orderBy(asc(v.created_at)).limit(s).all().map(l=>l.id);d.length!==0&&(e.db.delete(K).where(inArray(K.notification_id,d)).run(),e.db.delete(v).where(inArray(v.id,d)).run());}list(e){if(!this.dbExists())return [];let t=e.limit??Go,r=this.openHandle(false);try{return r.db.select({id:v.id,workspace_id:v.workspace_id,agent_id:v.agent_id,task_id:v.task_id,thread_id:v.thread_id,source:v.source,level:v.level,title:v.title,body:v.body,target_user_id:v.target_user_id,created_at:v.created_at,metadata:v.metadata,read_at:K.read_at}).from(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(eq(v.workspace_id,e.workspaceId)).orderBy(desc(v.created_at)).limit(t).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(o){throw new c("DB_ERROR","Failed to list notifications",o)}finally{r.close();}}unreadCount(e){if(!this.dbExists())return 0;let t=this.openHandle(false);try{return t.db.select({count:sql`count(*)`}).from(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(and(eq(v.workspace_id,e.workspaceId),isNull(K.notification_id))).get()?.count??0}catch(r){throw new c("DB_ERROR","Failed to count unread notifications",r)}finally{t.close();}}markRead(e){let t=this.openHandle(true);try{if(!t.db.select({id:v.id}).from(v).where(and(eq(v.id,e.notificationId),eq(v.workspace_id,e.workspaceId))).get())throw new c("NOT_FOUND","Notification not found in workspace");return t.db.insert(K).values({notification_id:e.notificationId,user_id:e.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark notification read",r)}finally{t.close();}}markAllRead(e){let t=this.openHandle(true);try{let r=t.db.select({id:v.id}).from(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(and(eq(v.workspace_id,e.workspaceId),isNull(K.notification_id))).all();if(r.length===0)return 0;let o=new Date().toISOString();return t.db.transaction(s=>{for(let i of r)s.insert(K).values({notification_id:i.id,user_id:e.userId,read_at:o}).onConflictDoNothing().run();}),r.length}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark all notifications read",r)}finally{t.close();}}};var Jo=50,Vr=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 c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}create(e){let t=this.openHandle(true);try{let r=new Date().toISOString(),o=[],s=e.map(i=>{let d=be("sug");return o.push(d),{id:d,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:r,updated_at:r}});return s.length>0&&t.db.insert(O).values(s).run(),{ids:o}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to create agent suggestions",r)}finally{t.close();}}findLatestSet(e,t){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=r.db.select({task_id:O.task_id}).from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t))).orderBy(desc(O.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?isNull(O.task_id):eq(O.task_id,o.task_id);return r.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),s)).orderBy(asc(O.created_at)).all()}catch(o){throw new c("DB_ERROR","Failed to find latest agent suggestion set",o)}finally{r.close();}}findSetByTaskId(e,t,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.task_id,r))).orderBy(asc(O.created_at)).all()}catch(s){throw new c("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{o.close();}}findById(e,t,r){if(!this.dbExists())return null;let o=this.openHandle(false);try{return o.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.id,r))).get()??null}catch(s){throw new c("DB_ERROR","Failed to find agent suggestion by id",s)}finally{o.close();}}updateStatus(e,t,r){let o=this.openHandle(true);try{let s={status:t,updated_at:new Date().toISOString()};return r!==void 0&&(s.applied_commit_sha=r),o.db.update(O).set(s).where(eq(O.id,e)).run().changes>0}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to update agent suggestion status",s)}finally{o.close();}}listByAgent(e,t,r=Jo){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t))).orderBy(desc(O.created_at)).limit(r).all()}catch(s){throw new c("DB_ERROR","Failed to list agent suggestions",s)}finally{o.close();}}findDismissed(e,t,r=20){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.status,"dismissed"))).orderBy(desc(O.updated_at)).limit(r).all()}catch(s){throw new c("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};export{Vr as AgentSuggestionRepository,To as BUILTIN_THREAD_STATES,D as BaseSqliteRepository,qt as COMMON_CODE_COLORS,Ht as COMMON_CODE_GROUPS,Qr as CREWX_JOURNAL_SIZE_LIMIT_BYTES,fr as CommonCodeRepository,J as CommonCodeRepositoryError,Jo as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,Wo as DEFAULT_NOTIFICATION_CAP,Go as DEFAULT_NOTIFICATION_LIST_LIMIT,Pn as DEFAULT_PROJECT_STAGES,br as DEFAULT_PROJECT_STAGE_KEYS,Gr as NotificationRepository,Tr as ProjectRepository,c as RepositoryError,Ur as RequestLogRepository,Hr as SpanRepository,ro as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,Yt as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,to as TASK_LOG_MIGRATION_TERMINAL_STATUSES,yo as THREAD_PRIORITIES,bt as TaskLogRepository,Sr as TaskRepository,Fr as ThreadBoxRepository,ht as ThreadHighlightConflictError,ir as ThreadHistoryConflictError,Br as ThreadHistoryRepository,Or as ThreadRepository,et as ThreadTitleMetadataPatchError,qr as ToolCallRepository,zr as UsageLimitSnapshotRepository,Wr as UsageReportRepository,yr as WorkspaceRepository,Mo as calcBucketStart,bo as customStateLabel,it as generateCommonCodeId,ao as hasSufficientTaskLogMigrationFreeSpace,qa as hasThreadTitleKey,It as isThreadPriority,Ct as isThreadState,Wa as matchesThreadTitleFilter,$r as mergeThreadTitleMeta,wo as migrateLegacyThreadTitleCommonCodes,ja as migrateThreadTitleCommonCodes,k as openDrizzleDb,Ua as parseThreadPriorityFilter,za as parseThreadStateFilter,Ni as pushSchema,er as readThreadTitleMeta,ns as reclaimTemporaryJournal,no as resolveTaskLogMigrationDbPath,rt as runMigrations,x as runMigrationsOnce,wa as runTaskLogMigration,ka as taskLogBackupName,a as tasks,Fa as threadTitleSearchHaystack,uo as tryCheckpointTaskLogWal};
|
package/dist/index.js
CHANGED
|
@@ -67,7 +67,7 @@ ${t??""}
|
|
|
67
67
|
---
|
|
68
68
|
`)}u();function Jm(){let t=new Date,e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return `${e}-${n}-${r}`}async function _l(t,e=Mn){let n=e.resolvePath(t,`${Jm()}.md`);return await e.exists(n)?e.readFile(n):""}u();rr();un();function wa(t){if(t.startsWith("cli/"))return exports.BUILTIN_ADAPTERS[t.slice(4)]}function Xm(t,e={}){if(!t.startsWith("cli/"))return true;let r=(e.lookupAdapter??wa)(t);if(!r?.command)return false;let o=Ur(r.command,{env:e.env});return pe__namespace.default.isAbsolute(o)}function wl(t,e={}){if(!Array.isArray(t))return t;if(t.length===0)return "cli/claude";for(let n of t)if(Xm(n,e))return n;return t[0]}u();var eo=new async_hooks.AsyncLocalStorage;function ka(t){if(t)return {parentTaskId:t.parentTaskId??null,rootTraceId:t.rootTraceId,callerAgentId:t.callerAgentId??null}}u();u();var Ri="<crewx_card";function to(t){return t===" "||t===" "||t===`
|
|
69
69
|
`||t==="\r"||t==="\f"}function Zm(t){if(!t)return false;let e=t.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||t==="_"||t===":"||t==="-"}function eh(t){return t===void 0||to(t)||t==="/"||t===">"}function kl(t,e){let n=t[e],r=e+1;for(;r<t.length;){if(t[r]===n)return {end:r+1,value:t.slice(e+1,r)};r++;}return {end:t.length,value:t.slice(e+1)}}function th(t,e){if(t[e]==='"'||t[e]==="'")return kl(t,e);let n=e;for(;n<t.length&&!to(t[n])&&t[n]!==">";)n++;return {end:n,value:t.slice(e,n)}}function nh(t,e){let n=Object.create(null),r=e+Ri.length,o=false;for(;r<t.length;){let i=t[r];if(i===">")return {end:r+1,closed:true,attrs:n,privileged:o};if(to(i)||i==="/"){r++;continue}if(i==='"'||i==="'"){r=kl(t,r).end;continue}let s=r;for(;r<t.length&&Zm(t[r]);)r++;if(r===s){r++;continue}let a=t.slice(s,r);for(a==="proof"&&(o=true);r<t.length&&to(t[r]);)r++;if(t[r]!=="="){n[a]="";continue}for(r++;r<t.length&&to(t[r]);)r++;let d=th(t,r);n[a]=d.value,r=d.end;}return {end:t.length,closed:false,attrs:n,privileged:o}}function va(t,e){let n=nh(t,e);return {start:e,end:n.end,raw:t.slice(e,n.end),closed:n.closed,attrs:n.attrs,privileged:n.privileged}}function no(t){let e=[],n=0;for(;n<t.length;){let r=t.indexOf(Ri,n);if(r<0)break;if(!eh(t[r+Ri.length])){n=r+Ri.length;continue}let o=va(t,r);if(e.push(o),!o.closed)break;n=o.end;}return e}function vl(t){return t&&no(t).find(r=>!!r.attrs.run_id?.trim())?.attrs.run_id?.trim()||void 0}u();u();var A=class extends Error{constructor(n,r=n,o){super(r);this.code=n;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"},Ve=class extends Error{constructor(n){super("UI instance database operation will be retried");this.cause=n;}cause;name="UiRetryableDatabaseError"},dt=class extends Error{constructor(n){super("UI instance revision reservation conflict");this.currentRevision=n;}currentRevision;name="UiReservationConflictError"};var rh=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,oh=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|directory|dir|folder)$/i,ih=/<\/?[A-Za-z][^>]*>/,sh=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ah=/^(?:https?|file|ftp|ws|wss):\/\//i;function Dt(){throw new A("INPUT_INVALID","JSON value is not projection-safe")}function dh(t){let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Ta(t,e,n,r){if(e>8&&Dt(),t===null||typeof t=="string"||typeof t=="boolean")return typeof t=="string"&&(ih.test(t)||ah.test(t)||sh.test(t))&&Dt(),t;if(typeof t=="number")return Number.isFinite(t)||Dt(),t;(typeof t!="object"||t===void 0||typeof t=="function"||typeof t=="bigint")&&Dt();let o=t;n.has(o)&&Dt(),n.add(o);try{if(Array.isArray(t))return t.map(s=>Ta(s,e+1,n));dh(o)||Dt();let i={};for(let[s,a]of Object.entries(t))(rh.test(s)||oh.test(s))&&Dt(),i[s]=Ta(a,e+1,n,s);return i}finally{n.delete(o);}}function Ae(t){let e=Ta(t,0,new Set);return (e===null||Array.isArray(e)||typeof e!="object")&&Dt(),e}function He(t){try{let e=JSON.stringify(t);return e===void 0&&Dt(),e}catch{Dt();}}function Ea(t){return Array.isArray(t)?t.map(Ea):t!==null&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(e=>[e,Ea(t[e])])):t}function Tl(t){return He(Ea(t))}function ro(t){return Buffer.byteLength(t,"utf8")}var El="[workflow card omitted from AI context]",ch="[workflow UI instance omitted from AI context]",lh=/\{\s*"instanceId"\s*:\s*"uic_[A-Za-z0-9_-]+"\s*\}/g;function Ii(t){return typeof t=="string"?t.replace(lh,ch):""}function xi(t){if(typeof t!="string"||t.length===0)return "";let e="",n=0;for(let r of no(t))if(e+=t.slice(n,r.start),e+=r.privileged?El:r.raw,n=r.end,!r.closed)break;return e+=t.slice(n),e}function uh(t){return t.replace(/</g,"<").replace(/>/g,">")}function ph(t,e){if(typeof t!="string")return "";let n=e?xi(t):t,r=e?Ii(n):n;return uh(r)}function ba(t){return t.map(e=>({...e,text:ph(e.text,e.isAssistant)}))}function cr(t,e){let n=ba(t);if(!e||e.length===0)return n;let r=[];for(let o of e)try{if(Object.keys(o).sort().join(",")!=="availableActions,definition,facts,instanceId,pendingDecision,recentChanges,revision"||!/^uic_[A-Za-z0-9_-]+$/.test(o.instanceId))continue;let s=Ae(o),a=JSON.stringify(s);if(typeof a!="string"||ro(a)>64*1024)continue;r.push(s);}catch{}return r.length===0?n:[...n,{text:`CrewX workflow context:
|
|
70
|
-
${JSON.stringify(r)}`,isAssistant:true}]}function Ra(t){return ba(t.messages.map(e=>({id:e.id,text:e.text,isAssistant:e.isAssistant,taskId:e.taskId,timestamp:e.timestamp,metadata:e.metadata,files:void 0})))}u();un();pn();u();u();var he=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:pe.join(Ka__namespace.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return Ql.existsSync(e??this.resolveDbPath())}};u();var bl=32*1024*1024;function $(t){let e=Be("better-sqlite3"),{drizzle:n}=Be("drizzle-orm/better-sqlite3"),r=new e(t);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${bl}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),
|
|
70
|
+
${JSON.stringify(r)}`,isAssistant:true}]}function Ra(t){return ba(t.messages.map(e=>({id:e.id,text:e.text,isAssistant:e.isAssistant,taskId:e.taskId,timestamp:e.timestamp,metadata:e.metadata,files:void 0})))}u();un();pn();u();u();var he=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:pe.join(Ka__namespace.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return Ql.existsSync(e??this.resolveDbPath())}};u();var bl=32*1024*1024;function $(t){let e=Be("better-sqlite3"),{drizzle:n}=Be("drizzle-orm/better-sqlite3"),r=new e(t);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${bl}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),{db:n(r),runRaw:(o,i=[])=>r.prepare(o).run(...i),close:()=>r.close()}}u();var Rl=new Set,_h={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT"};function xa(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function wh(t,e){if(e>0||!xa(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,i]of Object.entries(_h))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${i}`);}var kh={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"}};function vh(t,e,n){if(!xa(t,"__drizzle_migrations")||!xa(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(s=>s.hash)),i=JSON.parse(Ql.readFileSync(pe__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let s of i.entries){let a=kh[s.tag];if(!a)continue;let d=pe__namespace.default.join(e,`${s.tag}.sql`);if(!Ql.existsSync(d))continue;let c=Ql.readFileSync(d,"utf-8"),l=crypto$1.createHash("sha256").update(c).digest("hex");if(o.has(l))continue;let p=t.all("PRAGMA table_info(tasks)"),f=new Set(p.map(m=>m.name));for(let[m,T]of Object.entries(a))f.has(m)||(t.run(`ALTER TABLE tasks ADD COLUMN ${m} ${T}`),f.add(m));}}function Th(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(s=>s.hash)),i=JSON.parse(Ql.readFileSync(pe__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let s of i.entries){let a=pe__namespace.default.join(e,`${s.tag}.sql`);if(!Ql.existsSync(a))continue;let d=Ql.readFileSync(a,"utf-8"),c=crypto$1.createHash("sha256").update(d).digest("hex");if(o.has(c))continue;let l=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,p=[],f;for(;(f=l.exec(d))!==null;)p.push({table:f[1],column:f[2]});if(p.length===0||!d.split(/-->\s*statement-breakpoint/).map(h=>h.trim()).filter(Boolean).every(h=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(h)))continue;p.every(({table:h,column:k})=>t.all(`PRAGMA table_info("${h}")`).some(v=>v.name===k))&&t.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${s.when})`);}}function Ai(t){let{migrate:e}=Be("drizzle-orm/better-sqlite3/migrator"),{sql:n}=Be("drizzle-orm"),r=[pe__namespace.default.join(__dirname,"../migrations"),pe__namespace.default.join(__dirname,"migrations"),pe__namespace.default.join(__dirname,"../../../../drizzle/migrations"),pe__namespace.default.join(process.cwd(),"drizzle/migrations")],o=r.find(c=>Ql.existsSync(pe__namespace.default.join(c,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
71
71
|
${r.join(`
|
|
72
72
|
`)}`);let i=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),s=0;i?.cnt&&(s=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),wh(t,s),i?.cnt&&(Th(t,o,n),vh(t,o,n)),e(t,{migrationsFolder:o});let d=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-s;if(d>0){let c=i?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${d} migration${d>1?"s":""} applied).`);}}function ge(t,e){Rl.has(e)||(Ai(t),Rl.add(e));}u();var w=class extends Error{code;cause;constructor(e,n,r){super(n),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};u();u();var gn=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});u();var g=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0)},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(t.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(t.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(t.workspace_id,t.started_at)}));u();var Nt=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>g.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},t=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq)}));u();var Oh="json_extract(metadata, '$.threadTitle.state')",Dh="json_extract(metadata, '$.threadTitle.priority')",E=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>gn.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:sqliteCore.index("idx_threads_workspace_thread_state").on(t.workspace_id,drizzleOrm.sql.raw(Oh)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(Dh))}));u();var fn=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>g.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>fn.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},t=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(t.parent_span_id)}));u();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>g.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},t=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(t.timestamp)}));u();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>E.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(t.thread_id,t.seq)}));u();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},t=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(t.partition_key)}));u();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));u();sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},t=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));u();sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)}));sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));u();sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));u();sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${t.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${t.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${t.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id)}));u();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},t=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${t.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${t.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${t.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${t.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.sql`(
|
|
73
73
|
(${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
|