@crewx/sdk 0.8.9-rc.9 → 0.9.0-rc.0

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.
Files changed (36) hide show
  1. package/dist/activity-log/builder.d.ts +23 -0
  2. package/dist/config/pricing.d.ts +9 -0
  3. package/dist/conversation/sqlite-provider.d.ts +1 -0
  4. package/dist/esm/index.js +168 -45
  5. package/dist/esm/plugins/index.js +154 -27
  6. package/dist/esm/repository/index.js +150 -24
  7. package/dist/facade/Crewx.d.ts +1 -0
  8. package/dist/index.browser.d.ts +1 -0
  9. package/dist/index.browser.js +2 -2
  10. package/dist/index.d.ts +3 -1
  11. package/dist/index.js +168 -45
  12. package/dist/migrations/0006_add_task_run_epoch.sql +1 -0
  13. package/dist/migrations/meta/_journal.json +7 -0
  14. package/dist/plugins/index.js +154 -27
  15. package/dist/provider/acp/adapters/index.d.ts +0 -1
  16. package/dist/provider/acp/index.d.ts +1 -1
  17. package/dist/provider/acp/meta.d.ts +3 -0
  18. package/dist/provider/bridge.browser.d.ts +1 -10
  19. package/dist/provider/bridge.d.ts +2 -10
  20. package/dist/provider/cli/adapter.types.d.ts +23 -2
  21. package/dist/provider/cli/adapters/claude.d.ts +1 -0
  22. package/dist/provider/cli/adapters/cli-knob.util.d.ts +7 -0
  23. package/dist/provider/cli/adapters/gemini.d.ts +4 -2
  24. package/dist/provider/cli/adapters/index.d.ts +0 -1
  25. package/dist/provider/cli/index.d.ts +1 -1
  26. package/dist/provider/cli/meta.d.ts +4 -0
  27. package/dist/provider/errors.d.ts +20 -0
  28. package/dist/provider/order.d.ts +3 -0
  29. package/dist/repository/index.d.ts +2 -1
  30. package/dist/repository/index.js +150 -24
  31. package/dist/repository/task.repository.d.ts +15 -0
  32. package/dist/repository/thread.repository.d.ts +1 -1
  33. package/dist/schema/tasks.d.ts +17 -0
  34. package/dist/types/index.d.ts +2 -0
  35. package/package.json +4 -4
  36. package/templates/agents/default.yaml +8 -4
@@ -1,7 +1,6 @@
1
1
  import type { CliProviderAdapter } from '../adapter.types.js';
2
2
  import type { TaskLogEntry } from '../../../types/task-log.types.js';
3
3
  export { claudeAdapter } from './claude.js';
4
- export { geminiAdapter } from './gemini.js';
5
4
  export { copilotAdapter } from './copilot.js';
6
5
  export { codexAdapter } from './codex.js';
7
6
  export { opencodeAdapter } from './opencode.js';
@@ -1,3 +1,3 @@
1
- export { BUILTIN_ADAPTERS, parseStdoutEvent, claudeAdapter, geminiAdapter, copilotAdapter, codexAdapter, opencodeAdapter, antigravityAdapter, isAgentCallCommand, parseAgentCall, } from './adapters/index.js';
1
+ export { BUILTIN_ADAPTERS, parseStdoutEvent, claudeAdapter, copilotAdapter, codexAdapter, opencodeAdapter, antigravityAdapter, isAgentCallCommand, parseAgentCall, } from './adapters/index.js';
2
2
  export type { CliProviderAdapter } from './adapter.types.js';
3
3
  export { RateLimitError } from './adapter.types.js';
@@ -0,0 +1,4 @@
1
+ import type { AcpProviderMetaResult } from '../acp/meta.js';
2
+ import type { CliProviderAdapter } from './adapter.types.js';
3
+ export declare function cliAdapterMetaToProviderMeta(key: string, adapter: CliProviderAdapter): AcpProviderMetaResult | null;
4
+ export declare function queryAllCliProviderMetas(): AcpProviderMetaResult[];
@@ -0,0 +1,20 @@
1
+ export type ProviderErrorKind = 'transient' | 'permanent' | 'config';
2
+ export type ProviderErrorCode = 'QUOTA_EXHAUSTED' | 'RATE_LIMITED' | 'EMPTY_OUTPUT' | 'AUTH_REQUIRED' | 'MODEL_UNAVAILABLE' | 'TIMEOUT_IDLE' | 'TIMEOUT_TOTAL' | 'PROVIDER_NOT_FOUND' | 'INVALID_PROVIDER_FORMAT' | 'PROVIDER_CRASHED' | 'UNKNOWN';
3
+ export interface ProviderErrorOptions {
4
+ code?: ProviderErrorCode;
5
+ kind?: ProviderErrorKind;
6
+ retryAfterMs?: number;
7
+ }
8
+ export declare class ProviderError extends Error {
9
+ readonly providerStr: string;
10
+ readonly code: ProviderErrorCode;
11
+ readonly kind?: ProviderErrorKind;
12
+ readonly retryAfterMs?: number;
13
+ constructor(message: string, providerStr: string, options?: ProviderErrorOptions);
14
+ }
15
+ export declare class IdleTimeoutError extends ProviderError {
16
+ constructor(message: string, providerStr: string);
17
+ }
18
+ export declare class TotalTimeoutError extends ProviderError {
19
+ constructor(message: string, providerStr: string);
20
+ }
@@ -0,0 +1,3 @@
1
+ export declare const PROVIDER_ORDER: readonly ["codex", "claude", "opencode", "antigravity", "copilot"];
2
+ export declare function providerRank(id: string): number;
3
+ export declare function compareProviders(a: string, b: string): number;
@@ -9,8 +9,9 @@ export { runMigrations, runMigrationsOnce } from './migrate.js';
9
9
  export { pushSchema } from './push.js';
10
10
  export type { PushResult } from './push.js';
11
11
  export type { Workspace, NewWorkspace } from '../schema/index.js';
12
+ export { tasks } from '../schema/index.js';
12
13
  export { TaskRepository } from './task.repository.js';
13
- export type { TaskRow, NewTask, AgentUsageRow, TrendRow } from './task.repository.js';
14
+ export type { TaskRow, NewTask, AgentUsageRow, TrendRow, ProviderUsageRow } from './task.repository.js';
14
15
  export { ThreadRepository } from './thread.repository.js';
15
16
  export type { ThreadRow, NewThread } from './thread.repository.js';
16
17
  export { SpanRepository } from './span.repository.js';
@@ -1,13 +1,14 @@
1
- 'use strict';var Lt=require('fs'),z=require('path'),Jt=require('os'),drizzleOrm=require('drizzle-orm'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Lt__default=/*#__PURE__*/_interopDefault(Lt);var z__namespace=/*#__PURE__*/_interopNamespace(z);var Jt__default=/*#__PURE__*/_interopDefault(Jt);var Q=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var E=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:z.join(Jt__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return Lt.existsSync(t??this.resolveDbPath())}};var a=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function k(i){let t=Q("better-sqlite3"),{drizzle:e}=Q("drizzle-orm/better-sqlite3"),n=new t(i);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(s,r=[])=>n.prepare(s).run(...r),close:()=>n.close()}}var Dt=new Set,Kt={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function ct(i,t){return (i.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Vt(i,t){if(t>0||!ct(i,"tasks"))return;let e=i.all("PRAGMA table_info(tasks)"),n=new Set(e.map(s=>s.name));for(let[s,r]of Object.entries(Kt))n.has(s)||i.run(`ALTER TABLE tasks ADD COLUMN ${s} ${r}`);}var Qt={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function Zt(i,t,e){if(!ct(i,"__drizzle_migrations")||!ct(i,"tasks"))return;let n=i.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(Lt.readFileSync(z__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=Qt[o.tag];if(!l)continue;let u=z__namespace.default.join(t,`${o.tag}.sql`);if(!Lt.existsSync(u))continue;let p=Lt.readFileSync(u,"utf-8"),f=crypto.createHash("sha256").update(p).digest("hex");if(s.has(f))continue;let m=i.all("PRAGMA table_info(tasks)"),g=new Set(m.map(y=>y.name));for(let[y,F]of Object.entries(l))g.has(y)||(i.run(`ALTER TABLE tasks ADD COLUMN ${y} ${F}`),g.add(y));}}function te(i,t,e){let n=i.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(Lt.readFileSync(z__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=z__namespace.default.join(t,`${o.tag}.sql`);if(!Lt.existsSync(l))continue;let u=Lt.readFileSync(l,"utf-8"),p=crypto.createHash("sha256").update(u).digest("hex");if(s.has(p))continue;let f=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],g;for(;(g=f.exec(u))!==null;)m.push({table:g[1],column:g[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(M=>M.trim()).filter(Boolean).every(M=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(M)))continue;m.every(({table:M,column:dt})=>i.all(`PRAGMA table_info("${M}")`).some(lt=>lt.name===dt))&&i.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${o.when})`);}}function X(i){let{migrate:t}=Q("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Q("drizzle-orm"),n=[z__namespace.default.join(__dirname,"../migrations"),z__namespace.default.join(__dirname,"migrations"),z__namespace.default.join(__dirname,"../../../../drizzle/migrations"),z__namespace.default.join(process.cwd(),"drizzle/migrations")],s=n.find(p=>Lt.existsSync(z__namespace.default.join(p,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
1
+ 'use strict';var Ht=require('fs'),I=require('path'),Qt=require('os'),drizzleOrm=require('drizzle-orm'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ht__default=/*#__PURE__*/_interopDefault(Ht);var I__namespace=/*#__PURE__*/_interopNamespace(I);var Qt__default=/*#__PURE__*/_interopDefault(Qt);var et=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var S=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:I.join(Qt__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return Ht.existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function k(a){let t=et("better-sqlite3"),{drizzle:e}=et("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(s,r=[])=>n.prepare(s).run(...r),close:()=>n.close()}}var Ot=new Set,Zt={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function _t(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function te(a,t){if(t>0||!_t(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(s=>s.name));for(let[s,r]of Object.entries(Zt))n.has(s)||a.run(`ALTER TABLE tasks ADD COLUMN ${s} ${r}`);}var ee={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function ne(a,t,e){if(!_t(a,"__drizzle_migrations")||!_t(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(Ht.readFileSync(I__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=ee[o.tag];if(!l)continue;let u=I__namespace.default.join(t,`${o.tag}.sql`);if(!Ht.existsSync(u))continue;let c=Ht.readFileSync(u,"utf-8"),h=crypto.createHash("sha256").update(c).digest("hex");if(s.has(h))continue;let m=a.all("PRAGMA table_info(tasks)"),w=new Set(m.map(R=>R.name));for(let[R,M]of Object.entries(l))w.has(R)||(a.run(`ALTER TABLE tasks ADD COLUMN ${R} ${M}`),w.add(R));}}function se(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(Ht.readFileSync(I__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=I__namespace.default.join(t,`${o.tag}.sql`);if(!Ht.existsSync(l))continue;let u=Ht.readFileSync(l,"utf-8"),c=crypto.createHash("sha256").update(u).digest("hex");if(s.has(c))continue;let h=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],w;for(;(w=h.exec(u))!==null;)m.push({table:w[1],column:w[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(q=>q.trim()).filter(Boolean).every(q=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(q)))continue;m.every(({table:q,column:ut})=>a.all(`PRAGMA table_info("${q}")`).some(pt=>pt.name===ut))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${o.when})`);}}function J(a){let{migrate:t}=et("drizzle-orm/better-sqlite3/migrator"),{sql:e}=et("drizzle-orm"),n=[I__namespace.default.join(__dirname,"../migrations"),I__namespace.default.join(__dirname,"migrations"),I__namespace.default.join(__dirname,"../../../../drizzle/migrations"),I__namespace.default.join(process.cwd(),"drizzle/migrations")],s=n.find(c=>Ht.existsSync(I__namespace.default.join(c,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
2
2
  ${n.join(`
3
- `)}`);let r=i.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;r?.cnt&&(o=i.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Vt(i,o),r?.cnt&&(te(i,s,e),Zt(i,s,e)),t(i,{migrationsFolder:s});let u=(i.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${u} migration${u>1?"s":""} applied).`);}}function T(i,t){Dt.has(t)||(X(i),Dt.add(t));}var h=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()});var d=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),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)},i=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(i.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(i.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(i.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(i.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(i.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(i.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(i.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(i.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(i.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(i.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(i.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(i.workspace_id,i.started_at)}));var c=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>h.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)},i=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(i.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(i.workspace_id)}));var q=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>d.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>q.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")},i=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(i.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(i.parent_span_id)}));var v=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>d.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},i=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(i.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(i.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(i.timestamp)}));var N=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>c.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()},i=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(i.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(i.thread_id,i.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(i.thread_id,i.seq)}));var G=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")},i=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(i.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(i.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(i.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(i.partition_key)}));function ht(i){let t=z__namespace.resolve(i);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Pt(i){let t=ht(i);return crypto.createHash("sha256").update(t).digest("hex")}function st(i){return i.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var mt=class extends E{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?z.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=z.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{X(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=st(z.basename(n)),o=`${st(z.basename(z.dirname(n)))}-${s}`,l=[s,o];try{let u=p=>t.select({id:h.id}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.slug,p),drizzleOrm.ne(h.id,e))).limit(1).all().length>0;for(let p of l)if(!u(p))return p;for(let p=2;p<1e3;p+=1){let f=`${o}-${p}`;if(!u(f))return f}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=st(s.slug.replace(/\//g,"-"));t.db.update(h).set({slug:r,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,s.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new a("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:s,name:r,workspacePath:o}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:s,name:r,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(h).set({workspace_path:o,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(h.id,n),drizzleOrm.isNull(h.workspace_path))).run();}registerWorkspace(t){let e=ht(t),n=this.openHandle(true);try{let s=Pt(e),r=z.basename(e),o=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:o,name:r,workspacePath:e}),{id:s,slug:o}}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to register workspace",s)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?drizzleOrm.eq(h.is_active,t.isActive?1:0):void 0,s=e.db.select({count:drizzleOrm.sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(drizzleOrm.desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.count??0}}catch(n){throw new a("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(s=>s.agent_id)}catch(n){throw new a("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let s=n.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(drizzleOrm.sql`SELECT t.*,
3
+ `)}`);let r=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;r?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),te(a,o),r?.cnt&&(se(a,s,e),ne(a,s,e)),t(a,{migrationsFolder:s});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let c=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function x(a,t){Ot.has(t)||(J(a),Ot.add(t));}var _=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()});var i=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"),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)},a=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(a.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>_.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)},a=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(a.workspace_id)}));var z=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>z.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")},a=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(a.parent_span_id)}));var P=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.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()},a=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(a.timestamp)}));var C=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>p.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()},a=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(a.thread_id,a.seq)}));var V=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")},a=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(a.partition_key)}));function mt(a){let t=I__namespace.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function $t(a){let t=mt(a);return crypto.createHash("sha256").update(t).digest("hex")}function it(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var kt=class extends S{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?I.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=I.dirname(e);Ht.existsSync(s)||Ht.mkdirSync(s,{recursive:true});}else if(!Ht.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{J(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=it(I.basename(n)),o=`${it(I.basename(I.dirname(n)))}-${s}`,l=[s,o];try{let u=c=>t.select({id:_.id}).from(_).where(drizzleOrm.and(drizzleOrm.eq(_.slug,c),drizzleOrm.ne(_.id,e))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let h=`${o}-${c}`;if(!u(h))return h}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,slug:_.slug}).from(_).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=it(s.slug.replace(/\//g,"-"));t.db.update(_).set({slug:r,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(_.id,s.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:s,name:r,workspacePath:o}=e,l=new Date().toISOString();t.insert(_).values({id:n,slug:s,name:r,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(_).set({workspace_path:o,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(_.id,n),drizzleOrm.isNull(_.workspace_path))).run();}registerWorkspace(t){let e=mt(t),n=this.openHandle(true);try{let s=$t(e),r=I.basename(e),o=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:o,name:r,workspacePath:e}),{id:s,slug:o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to register workspace",s)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?drizzleOrm.eq(_.is_active,t.isActive?1:0):void 0,s=e.db.select({count:drizzleOrm.sql`count(*)`}).from(_).where(n).get();return {rows:e.db.select().from(_).where(n).orderBy(drizzleOrm.desc(_.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(s=>s.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let s=n.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(drizzleOrm.sql`SELECT t.*,
4
4
  (SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
5
5
  FROM threads t
6
6
  WHERE t.workspace_id = ${t}
7
7
  ORDER BY t.updated_at DESC
8
- LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new a("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.slug,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?drizzleOrm.and(drizzleOrm.eq(h.slug,t),drizzleOrm.ne(h.id,e)):drizzleOrm.eq(h.slug,t);return !!n.db.select({id:h.id}).from(h).where(s).limit(1).get()}catch(s){throw new a("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(h).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!l)throw new a("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof a?o:new a("DB_ERROR","Failed to insert workspace",o)}finally{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!r)throw new a("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.is_active,1),drizzleOrm.isNotNull(h.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;Lt.existsSync(z.join(r,"crewx.yaml"))||Lt.existsSync(z.join(r,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new a("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(h).where(drizzleOrm.eq(h.id,t)).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var $t=[h,d,c,q,v,N,G];function ye(){return z__namespace.default.join(Jt__default.default.homedir(),".crewx","crewx.db")}function Ee(i){if(!Lt__default.default.existsSync(i))return null;let t=Math.floor(Date.now()/1e3),e=`${i}.bak-${t}`;return Lt__default.default.copyFileSync(i,e),e}function qt(i){let t=i.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Se(i){return i==null||typeof i=="object"&&"queryChunks"in i?null:typeof i=="number"?String(i):typeof i=="boolean"?i?"1":"0":typeof i=="string"?`'${i.replace(/'/g,"''")}'`:String(i)}function De(i){let t=i.getSQLType(),e=`"${i.name}" ${t}`,n=Se(i.default);return n!==null&&(e+=` DEFAULT ${n}`),i.notNull&&(e+=" NOT NULL"),e}function xe(i,t){let e=t?.dbPath??ye(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Ee(e);if(n&&!s)try{i.run("DELETE FROM __drizzle_migrations");}catch{}let o=qt(i);if(!s)try{X(i);}catch(m){let g=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw m}let l,u;s?(l=$t.map(g=>sqliteCore.getTableConfig(g).name).filter(g=>!o.has(g)),u=o):(u=qt(i),l=[...u].filter(m=>!o.has(m)));let p=[],f=[];for(let m of $t){let g=sqliteCore.getTableConfig(m),y=g.name;if(!u.has(y))continue;let F=i.all(`PRAGMA table_info("${y}")`),M=new Set(F.map(P=>P.name)),dt=new Set(g.columns.map(P=>P.name));for(let P of g.columns)if(!M.has(P.name)){if(!s){let lt=De(P);i.run(`ALTER TABLE "${y}" ADD COLUMN ${lt}`);}p.push({table:y,column:P.name});}for(let P of F)dt.has(P.name)||f.push(`${y}.${P.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:p,warnings:f,backupPath:r}}var kt=class extends E{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=z.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(d).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
8
+ LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new d("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(drizzleOrm.eq(_.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?drizzleOrm.and(drizzleOrm.eq(_.slug,t),drizzleOrm.ne(_.id,e)):drizzleOrm.eq(_.slug,t);return !!n.db.select({id:_.id}).from(_).where(s).limit(1).get()}catch(s){throw new d("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(_).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.db.select().from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get();if(!r)throw new d("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,workspace_path:_.workspace_path}).from(_).where(drizzleOrm.and(drizzleOrm.eq(_.is_active,1),drizzleOrm.isNotNull(_.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;Ht.existsSync(I.join(r,"crewx.yaml"))||Ht.existsSync(I.join(r,"crewx.yml"))||(t.db.update(_).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(_.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(_).where(drizzleOrm.eq(_.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Ut=[_,i,p,z,P,C,V];function Te(){return I__namespace.default.join(Qt__default.default.homedir(),".crewx","crewx.db")}function De(a){if(!Ht__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Ht__default.default.copyFileSync(a,e),e}function Mt(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function xe(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function Oe(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=xe(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Ae(a,t){let e=t?.dbPath??Te(),n=t?.force??false,s=t?.dryRun??false,r=s?null:De(e);if(n&&!s)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Mt(a);if(!s)try{J(a);}catch(m){let w=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!w.includes("duplicate column"))throw m}let l,u;s?(l=Ut.map(w=>sqliteCore.getTableConfig(w).name).filter(w=>!o.has(w)),u=o):(u=Mt(a),l=[...u].filter(m=>!o.has(m)));let c=[],h=[];for(let m of Ut){let w=sqliteCore.getTableConfig(m),R=w.name;if(!u.has(R))continue;let M=a.all(`PRAGMA table_info("${R}")`),q=new Set(M.map(v=>v.name)),ut=new Set(w.columns.map(v=>v.name));for(let v of w.columns)if(!q.has(v.name)){if(!s){let pt=Oe(v);a.run(`ALTER TABLE "${R}" ADD COLUMN ${pt}`);}c.push({table:R,column:v.name});}for(let v of M)ut.has(v.name)||h.push(`${R}.${v.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:h,backupPath:r}}var G="2026-05-09",$e="0.8.9-rc.13",Y=10,X=parseInt($e.split("rc.")[1]),Rt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=I.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=I.dirname(e);Ht.existsSync(s)||Ht.mkdirSync(s,{recursive:true});}else if(!Ht.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
9
9
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
10
- model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let r=s.select({logs:d.logs}).from(d).where(drizzleOrm.eq(d.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(d).set({logs:JSON.stringify(o)}).where(drizzleOrm.eq(d.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(d).where(drizzleOrm.eq(d.status,"running")).orderBy(drizzleOrm.desc(d.started_at)).all()}catch(e){throw new a("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(d).orderBy(drizzleOrm.desc(d.started_at)).limit(100).all()}catch(e){throw new a("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(d).where(drizzleOrm.eq(d.id,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:d.id,status:d.status,pid:d.pid}).from(d).where(drizzleOrm.eq(d.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(d).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(d.id,t),drizzleOrm.eq(d.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:d.id,pid:d.pid}).from(d).where(drizzleOrm.eq(d.status,"running")).all(),n=0;for(let s of e){if(!s.pid)continue;let r=!1;try{process.kill(s.pid,0),r=!0;}catch{}r||(t.db.update(d).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(d.id,s.id),drizzleOrm.eq(d.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Lt.existsSync(s))continue;let r=k(s);try{let o=e?drizzleOrm.eq(d.workspace_id,e):void 0,l=o?drizzleOrm.and(drizzleOrm.eq(d.id,t),o):drizzleOrm.eq(d.id,t),u=r.db.select().from(d).where(l).limit(1).get()??void 0;if(!u){let p=drizzleOrm.or(drizzleOrm.eq(d.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(d.thread_id),drizzleOrm.like(d.command,`%--thread=${t}%`))),f=o?drizzleOrm.and(p,o):p;u=r.db.select().from(d).where(f).orderBy(drizzleOrm.desc(d.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new a("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=k(o);try{let u=e?drizzleOrm.and(drizzleOrm.eq(d.parent_task_id,t),drizzleOrm.eq(d.workspace_id,e)):drizzleOrm.eq(d.parent_task_id,t),p=l.db.select().from(d).where(u).orderBy(drizzleOrm.asc(d.started_at)).all();for(let f of p)s.has(f.id)||(s.add(f.id),r.push(f));}catch(u){throw new a("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
10
+ model=COALESCE(?, model)
11
+ WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let r=s.select({logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(drizzleOrm.eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(drizzleOrm.eq(i.status,"running")).orderBy(drizzleOrm.desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(drizzleOrm.desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(drizzleOrm.eq(i.status,"running")).all(),n=0;for(let s of e){if(!s.pid)continue;let r=!1;try{process.kill(s.pid,0),r=!0;}catch{}r||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,s.id),drizzleOrm.eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Ht.existsSync(s))continue;let r=k(s);try{let o=e?drizzleOrm.eq(i.workspace_id,e):void 0,l=o?drizzleOrm.and(drizzleOrm.eq(i.id,t),o):drizzleOrm.eq(i.id,t),u=r.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let c=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),h=o?drizzleOrm.and(c,o):c;u=r.db.select().from(i).where(h).orderBy(drizzleOrm.desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Ht.existsSync(o))continue;let l=k(o);try{let u=e?drizzleOrm.and(drizzleOrm.eq(i.parent_task_id,t),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.eq(i.parent_task_id,t),c=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let h of c)s.has(h.id)||(s.add(h.id),r.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
11
12
  SELECT
12
13
  COALESCE(workspace_id, 'unknown') AS workspace_id,
13
14
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -28,12 +29,24 @@ ${n.join(`
28
29
  FROM tasks
29
30
  GROUP BY workspace_id
30
31
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
31
- `)}catch(n){throw new a("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),s=new Set,r=0,o=0,l=0;for(let u of n){if(!Lt.existsSync(u))continue;let p=k(u);try{let f=drizzleOrm.or(drizzleOrm.eq(d.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(d.thread_id),drizzleOrm.like(d.command,`%--thread=${t}%`))),m=e?drizzleOrm.and(f,drizzleOrm.eq(d.workspace_id,e)):f,g=p.db.select({id:d.id,input_tokens:d.input_tokens,output_tokens:d.output_tokens,cost_usd:d.cost_usd}).from(d).where(m).all();for(let y of g)s.has(y.id)||(s.add(y.id),r+=y.input_tokens??0,o+=y.output_tokens??0,l+=y.cost_usd??0);}catch(f){throw new a("DB_ERROR","Failed to get thread token usage",f)}finally{p.close();}}return {inputTokens:r,outputTokens:o,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=k(o);try{let u=drizzleOrm.or(drizzleOrm.eq(d.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(d.thread_id),drizzleOrm.like(d.command,`%--thread=${t}%`))),p=e?drizzleOrm.and(u,drizzleOrm.eq(d.workspace_id,e)):u,f=l.db.select().from(d).where(p).orderBy(drizzleOrm.asc(d.started_at)).all();for(let m of f)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new a("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(drizzleOrm.eq(d.workspace_id,t.workspaceId));let s=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;s&&n.push(drizzleOrm.inArray(d.agent_id,s));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&n.push(drizzleOrm.inArray(d.status,r));let o=t.q??t.search;o&&n.push(drizzleOrm.like(d.prompt,`%${o}%`)),t.from&&n.push(drizzleOrm.gte(d.started_at,t.from)),t.to&&n.push(drizzleOrm.lt(d.started_at,t.to));let l=n.length>0?drizzleOrm.and(...n):void 0,u=e.db.select({count:drizzleOrm.sql`count(*)`}).from(d).where(l).get(),p=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(d.started_at):drizzleOrm.desc(d.started_at);return {rows:e.db.select().from(d).where(l).orderBy(p).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new a("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?drizzleOrm.sql`
32
+ `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),s=new Set,r=0,o=0,l=0;for(let u of n){if(!Ht.existsSync(u))continue;let c=k(u);try{let h=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),m=e?drizzleOrm.and(h,drizzleOrm.eq(i.workspace_id,e)):h,w=c.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(m).all();for(let R of w)s.has(R.id)||(s.add(R.id),r+=R.input_tokens??0,o+=R.output_tokens??0,l+=R.cost_usd??0);}catch(h){throw new d("DB_ERROR","Failed to get thread token usage",h)}finally{c.close();}}return {inputTokens:r,outputTokens:o,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Ht.existsSync(o))continue;let l=k(o);try{let u=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),c=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of h)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(drizzleOrm.eq(i.workspace_id,t.workspaceId));let s=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;s&&n.push(drizzleOrm.inArray(i.agent_id,s));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&n.push(drizzleOrm.inArray(i.status,r));let o=t.q??t.search;o&&n.push(drizzleOrm.like(i.prompt,`%${o}%`)),t.from&&n.push(drizzleOrm.gte(i.started_at,t.from)),t.to&&n.push(drizzleOrm.lt(i.started_at,t.to));let l=n.length>0?drizzleOrm.and(...n):void 0,u=e.db.select({count:drizzleOrm.sql`count(*)`}).from(i).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(i.started_at):drizzleOrm.desc(i.started_at);return {rows:e.db.select().from(i).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?drizzleOrm.sql`
32
33
  SELECT
33
34
  t.agent_id,
34
35
  t.workspace_id,
35
36
  COUNT(*) AS total_tasks,
36
- COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
37
+ COALESCE(SUM(
38
+ COALESCE(t.input_tokens, 0)
39
+ + CASE
40
+ WHEN t.started_at >= ${G}
41
+ AND (
42
+ t.crewx_version IS NULL
43
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
44
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
45
+ )
46
+ THEN COALESCE(t.cached_input_tokens, 0)
47
+ ELSE 0
48
+ END
49
+ ), 0) AS input_tokens,
37
50
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
38
51
  COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
39
52
  COALESCE(SUM(t.cost_usd), 0) AS cost_usd
@@ -43,13 +56,40 @@ ${n.join(`
43
56
  AND t.started_at < ${e}
44
57
  AND t.workspace_id = ${n}
45
58
  GROUP BY t.agent_id, t.workspace_id
46
- ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
59
+ ORDER BY (
60
+ COALESCE(SUM(
61
+ COALESCE(t.input_tokens, 0)
62
+ + CASE
63
+ WHEN t.started_at >= ${G}
64
+ AND (
65
+ t.crewx_version IS NULL
66
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
67
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
68
+ )
69
+ THEN COALESCE(t.cached_input_tokens, 0)
70
+ ELSE 0
71
+ END
72
+ ), 0)
73
+ + COALESCE(SUM(t.output_tokens), 0)
74
+ ) DESC
47
75
  `:drizzleOrm.sql`
48
76
  SELECT
49
77
  t.agent_id,
50
78
  t.workspace_id,
51
79
  COUNT(*) AS total_tasks,
52
- COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
80
+ COALESCE(SUM(
81
+ COALESCE(t.input_tokens, 0)
82
+ + CASE
83
+ WHEN t.started_at >= ${G}
84
+ AND (
85
+ t.crewx_version IS NULL
86
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
87
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
88
+ )
89
+ THEN COALESCE(t.cached_input_tokens, 0)
90
+ ELSE 0
91
+ END
92
+ ), 0) AS input_tokens,
53
93
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
54
94
  COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
55
95
  COALESCE(SUM(t.cost_usd), 0) AS cost_usd
@@ -58,12 +98,39 @@ ${n.join(`
58
98
  AND t.started_at >= ${t}
59
99
  AND t.started_at < ${e}
60
100
  GROUP BY t.agent_id, t.workspace_id
61
- ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
62
- `).map(o=>({agentId:o.agent_id,workspaceId:o.workspace_id??null,totalTasks:o.total_tasks,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd}))}catch(r){throw new a("DB_ERROR","Failed to get agent usage",r)}finally{s.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?drizzleOrm.sql`
101
+ ORDER BY (
102
+ COALESCE(SUM(
103
+ COALESCE(t.input_tokens, 0)
104
+ + CASE
105
+ WHEN t.started_at >= ${G}
106
+ AND (
107
+ t.crewx_version IS NULL
108
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
109
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
110
+ )
111
+ THEN COALESCE(t.cached_input_tokens, 0)
112
+ ELSE 0
113
+ END
114
+ ), 0)
115
+ + COALESCE(SUM(t.output_tokens), 0)
116
+ ) DESC
117
+ `).map(o=>({agentId:o.agent_id,workspaceId:o.workspace_id??null,totalTasks:o.total_tasks,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd,totalTokens:o.input_tokens+o.output_tokens}))}catch(r){throw new d("DB_ERROR","Failed to get agent usage",r)}finally{s.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?drizzleOrm.sql`
63
118
  SELECT
64
119
  date(t.started_at) AS date,
65
120
  t.agent_id,
66
- COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
121
+ COALESCE(SUM(
122
+ COALESCE(t.input_tokens, 0)
123
+ + CASE
124
+ WHEN t.started_at >= ${G}
125
+ AND (
126
+ t.crewx_version IS NULL
127
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
128
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
129
+ )
130
+ THEN COALESCE(t.cached_input_tokens, 0)
131
+ ELSE 0
132
+ END
133
+ ), 0) AS input_tokens,
67
134
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
68
135
  COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
69
136
  COALESCE(SUM(t.cost_usd), 0) AS cost_usd
@@ -78,7 +145,19 @@ ${n.join(`
78
145
  SELECT
79
146
  date(t.started_at) AS date,
80
147
  t.agent_id,
81
- COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
148
+ COALESCE(SUM(
149
+ COALESCE(t.input_tokens, 0)
150
+ + CASE
151
+ WHEN t.started_at >= ${G}
152
+ AND (
153
+ t.crewx_version IS NULL
154
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
155
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
156
+ )
157
+ THEN COALESCE(t.cached_input_tokens, 0)
158
+ ELSE 0
159
+ END
160
+ ), 0) AS input_tokens,
82
161
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
83
162
  COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
84
163
  COALESCE(SUM(t.cost_usd), 0) AS cost_usd
@@ -88,7 +167,43 @@ ${n.join(`
88
167
  AND t.started_at < ${e}
89
168
  GROUP BY date(t.started_at), t.agent_id
90
169
  ORDER BY date(t.started_at) ASC
91
- `).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd}))}catch(r){throw new a("DB_ERROR","Failed to get agent usage trend",r)}finally{s.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(d).where(drizzleOrm.and(drizzleOrm.eq(d.id,t),drizzleOrm.eq(d.workspace_id,e))).limit(1).get()??void 0}catch(s){throw new a("DB_ERROR","Failed to find task for stop",s)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString(),o=n?drizzleOrm.and(drizzleOrm.eq(d.id,t),drizzleOrm.eq(d.status,"running"),drizzleOrm.eq(d.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(d.id,t),drizzleOrm.eq(d.status,"running"));s.db.update(d).set({status:"failed",error:e,completed_at:r}).where(o).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to mark task failed",r)}finally{s.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=k(o);try{let u=e?drizzleOrm.and(drizzleOrm.like(d.prompt,`%${t}%`),drizzleOrm.eq(d.workspace_id,e)):drizzleOrm.like(d.prompt,`%${t}%`),p=l.db.select().from(d).where(u).orderBy(drizzleOrm.asc(d.started_at)).all();for(let f of p)s.has(f.id)||(s.add(f.id),r.push(f));}catch(u){throw new a("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return r}};var bt=class extends E{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=z.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:h.id}).from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return drizzleOrm.sql.raw(`(
170
+ `).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd,totalTokens:o.input_tokens+o.output_tokens}))}catch(r){throw new d("DB_ERROR","Failed to get agent usage trend",r)}finally{s.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.workspace_id,e))).limit(1).get()??void 0}catch(s){throw new d("DB_ERROR","Failed to find task for stop",s)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString(),o=n?drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"),drizzleOrm.eq(i.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"));s.db.update(i).set({status:"failed",error:e,completed_at:r}).where(o).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to mark task failed",r)}finally{s.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Ht.existsSync(o))continue;let l=k(o);try{let u=e?drizzleOrm.and(drizzleOrm.like(i.prompt,`%${t}%`),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.like(i.prompt,`%${t}%`),c=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let h of c)s.has(h.id)||(s.add(h.id),r.push(h));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return r}getProviderUsage(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{let r=drizzleOrm.sql`
171
+ CASE
172
+ WHEN ${i.model} LIKE 'claude-%' OR ${i.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
173
+ WHEN ${i.model} LIKE 'gpt-%' OR ${i.model} LIKE 'codex-%' THEN 'codex'
174
+ WHEN ${i.model} LIKE 'gemini-%' THEN 'gemini'
175
+ WHEN ${i.model} LIKE 'zai-%' OR ${i.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
176
+ WHEN ${i.model} LIKE 'minimax/%' THEN 'minimax'
177
+ WHEN ${i.model} LIKE 'qwen%' THEN 'qwen'
178
+ ELSE 'unknown'
179
+ END
180
+ `,o=drizzleOrm.sql`
181
+ COALESCE(${i.input_tokens}, 0)
182
+ + CASE
183
+ WHEN ${i.started_at} >= ${G}
184
+ AND (
185
+ ${i.crewx_version} IS NULL
186
+ OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
187
+ OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Y}) AS INTEGER) < ${X})
188
+ )
189
+ THEN COALESCE(${i.cached_input_tokens}, 0)
190
+ ELSE 0
191
+ END
192
+ `,l=n?drizzleOrm.sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${t} AND ${i.started_at} < ${e} AND ${i.workspace_id} = ${n}`:drizzleOrm.sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${t} AND ${i.started_at} < ${e}`;return s.db.all(drizzleOrm.sql`
193
+ SELECT
194
+ ${r} AS provider,
195
+ COUNT(*) AS total_tasks,
196
+ COALESCE(SUM(${o}), 0) AS input_tokens,
197
+ COALESCE(SUM(${i.output_tokens}), 0) AS output_tokens,
198
+ COALESCE(SUM(${i.cached_input_tokens}), 0) AS cached_input_tokens,
199
+ COALESCE(SUM(${i.cost_usd}), 0) AS cost_usd,
200
+ COALESCE(SUM(${i.duration_ms}), 0) AS active_duration_ms,
201
+ MAX(${i.completed_at}) AS last_active_at
202
+ FROM ${i}
203
+ ${l}
204
+ GROUP BY provider
205
+ ORDER BY (COALESCE(SUM(${o}), 0) + COALESCE(SUM(${i.output_tokens}), 0)) DESC
206
+ `).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(r){throw new d("DB_ERROR","Failed to get provider usage",r)}finally{s.close();}}};var yt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=I.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=I.dirname(e);Ht.existsSync(s)||Ht.mkdirSync(s,{recursive:true});}else if(!Ht.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:_.id}).from(_).where(drizzleOrm.eq(_.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return drizzleOrm.sql.raw(`(
92
207
  ${t}.parent_task_id IS NULL
93
208
  OR ${t}.parent_task_id = ''
94
209
  OR NOT EXISTS (
@@ -96,7 +211,7 @@ ${n.join(`
96
211
  WHERE parent.id = ${t}.parent_task_id
97
212
  AND parent.thread_id = ${t}.thread_id
98
213
  )
99
- )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let r of e){if(!Lt.existsSync(r))continue;let o=k(r);try{let l=t?drizzleOrm.eq(c.workspace_id,t):void 0,u=o.db.select().from(c).where(l).orderBy(drizzleOrm.desc(c.updated_at)).all();for(let p of u)n.has(p.id)||(n.add(p.id),s.push(p));}catch(l){throw new a("DB_ERROR","Failed to find all threads",l)}finally{o.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Lt.existsSync(s))continue;let r=k(s);try{let o=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(c.workspace_id,e)):o,u=r.db.select().from(c).where(l).limit(1).get()??void 0;if(u)return u}catch(o){throw new a("DB_ERROR","Failed to find thread by id",o)}finally{r.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Lt.existsSync(s))continue;let r=k(s);try{let o=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(c.workspace_id,e)):o;if(r.db.select({id:c.id}).from(c).where(l).limit(1).get())return !0}catch(o){throw new a("DB_ERROR","Failed to check thread existence",o)}finally{r.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,r=0,o=0,l=0,u=0,p=new Set;for(let f of n){if(!Lt.existsSync(f))continue;let m=k(f);try{let g=m.db.get(drizzleOrm.sql`
214
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let r of e){if(!Ht.existsSync(r))continue;let o=k(r);try{let l=t?drizzleOrm.eq(p.workspace_id,t):void 0,u=o.db.select().from(p).where(l).orderBy(drizzleOrm.desc(p.updated_at)).all();for(let c of u)n.has(c.id)||(n.add(c.id),s.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{o.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Ht.existsSync(s))continue;let r=k(s);try{let o=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(p.workspace_id,e)):o,u=r.db.select().from(p).where(l).limit(1).get()??void 0;if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find thread by id",o)}finally{r.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Ht.existsSync(s))continue;let r=k(s);try{let o=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(p.workspace_id,e)):o;if(r.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(o){throw new d("DB_ERROR","Failed to check thread existence",o)}finally{r.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,r=0,o=0,l=0,u=0,c=new Set;for(let h of n){if(!Ht.existsSync(h))continue;let m=k(h);try{let w=m.db.get(drizzleOrm.sql`
100
215
  SELECT
101
216
  count(*) AS cnt,
102
217
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -107,25 +222,36 @@ ${n.join(`
107
222
  WHERE child.thread_id = ${t}
108
223
  AND ${this.topLevelTaskPredicateSql()}
109
224
  ${e?drizzleOrm.sql`AND child.workspace_id = ${e}`:drizzleOrm.sql``}
110
- `);g&&(s+=g.cnt,r+=g.total_input,o+=g.total_output,l+=g.total_cached,u+=g.total_cost);let y=m.db.all(drizzleOrm.sql`
225
+ `);w&&(s+=w.cnt,r+=w.total_input,o+=w.total_output,l+=w.total_cached,u+=w.total_cost);let R=m.db.all(drizzleOrm.sql`
111
226
  SELECT DISTINCT child.agent_id FROM tasks child
112
227
  WHERE child.thread_id = ${t}
113
228
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
114
229
  AND ${this.topLevelTaskPredicateSql()}
115
230
  ${e?drizzleOrm.sql`AND child.workspace_id = ${e}`:drizzleOrm.sql``}
116
- `);for(let F of y)p.add(F.agent_id);}catch(g){throw new a("DB_ERROR","Failed to aggregate task stats",g)}finally{m.close();}}return {taskCount:s,inputTokens:r,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=k(o);try{let u=l.db.all(drizzleOrm.sql`
117
- SELECT child.* FROM tasks child
118
- WHERE child.thread_id = ${t}
119
- AND ${this.topLevelTaskPredicateSql()}
120
- ${e?drizzleOrm.sql`AND child.workspace_id = ${e}`:drizzleOrm.sql``}
121
- ORDER BY child.started_at ASC
122
- `);for(let p of u)s.has(p.id)||(s.add(p.id),r.push(p));}catch(u){throw new a("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}return r}findAllTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=k(o);try{let u=drizzleOrm.eq(d.thread_id,t),p=e?drizzleOrm.and(u,drizzleOrm.eq(d.workspace_id,e)):u,f=l.db.select().from(d).where(p).orderBy(drizzleOrm.asc(d.started_at)).all();for(let m of f)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new a("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return r}findTaskById(t,e,n){let s=this.resolveDbPaths();for(let r of s){if(!Lt.existsSync(r))continue;let o=k(r);try{let l=drizzleOrm.and(drizzleOrm.eq(d.id,e),drizzleOrm.eq(d.thread_id,t)),u=n?drizzleOrm.and(l,drizzleOrm.eq(d.workspace_id,n)):l,p=o.db.select().from(d).where(u).limit(1).get();if(!p)continue;let f=o.db.select().from(d).where(drizzleOrm.eq(d.parent_task_id,p.id)).orderBy(drizzleOrm.asc(d.started_at)).all();return {task:p,children:f}}catch(l){throw new a("DB_ERROR","Failed to find task by id",l)}finally{o.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let s=this.resolveDbPaths();for(let r of s){if(!Lt.existsSync(r))continue;let o=k(r);try{let l=o.db.all(drizzleOrm.sql`
231
+ `);for(let M of R)c.add(M.agent_id);}catch(w){throw new d("DB_ERROR","Failed to aggregate task stats",w)}finally{m.close();}}return {taskCount:s,inputTokens:r,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,n){let s=this.resolveDbPaths(),r=new Set,o=[];for(let l of s){if(!Ht.existsSync(l))continue;let u=k(l);try{let c;n!==void 0?c=u.db.all(drizzleOrm.sql`
232
+ SELECT * FROM (
233
+ SELECT child.*,
234
+ ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
235
+ FROM tasks child
236
+ WHERE child.thread_id = ${t}
237
+ AND ${this.topLevelTaskPredicateSql()}
238
+ ${e?drizzleOrm.sql`AND child.workspace_id = ${e}`:drizzleOrm.sql``}
239
+ ) ranked
240
+ WHERE rn <= ${n}
241
+ ORDER BY started_at ASC
242
+ `):c=u.db.all(drizzleOrm.sql`
243
+ SELECT child.* FROM tasks child
244
+ WHERE child.thread_id = ${t}
245
+ AND ${this.topLevelTaskPredicateSql()}
246
+ ${e?drizzleOrm.sql`AND child.workspace_id = ${e}`:drizzleOrm.sql``}
247
+ ORDER BY child.started_at ASC
248
+ `);for(let h of c)r.has(h.id)||(r.add(h.id),o.push(h));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(n!==void 0&&s.length>1){let l=new Map;for(let u of o){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}o=[];for(let u of l.values())u.sort((c,h)=>(h.started_at??"").localeCompare(c.started_at??"")),o.push(...u.slice(0,n));o.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return o}findAllTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Ht.existsSync(o))continue;let l=k(o);try{let u=drizzleOrm.eq(i.thread_id,t),c=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of h)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return r}findTaskById(t,e,n){let s=this.resolveDbPaths();for(let r of s){if(!Ht.existsSync(r))continue;let o=k(r);try{let l=drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.thread_id,t)),u=n?drizzleOrm.and(l,drizzleOrm.eq(i.workspace_id,n)):l,c=o.db.select().from(i).where(u).limit(1).get();if(!c)continue;let h=o.db.select().from(i).where(drizzleOrm.eq(i.parent_task_id,c.id)).orderBy(drizzleOrm.asc(i.started_at)).all();return {task:c,children:h}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{o.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let s=this.resolveDbPaths();for(let r of s){if(!Ht.existsSync(r))continue;let o=k(r);try{let l=o.db.all(drizzleOrm.sql`
123
249
  SELECT child.* FROM tasks child
124
250
  WHERE child.thread_id IN (${drizzleOrm.sql.join(t.map(u=>drizzleOrm.sql`${u}`),drizzleOrm.sql`, `)})
125
251
  AND ${this.topLevelTaskPredicateSql()}
126
252
  ${e?drizzleOrm.sql`AND child.workspace_id = ${e}`:drizzleOrm.sql``}
127
253
  ORDER BY child.started_at ASC
128
- `);for(let u of l){let p=u.thread_id;n.has(p)||n.set(p,[]),n.get(p).push(u);}}catch(l){throw new a("DB_ERROR","Failed to batch fetch tasks",l)}finally{o.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=drizzleOrm.eq(c.id,t),o=n?drizzleOrm.and(r,drizzleOrm.eq(c.workspace_id,n)):r;if(!s.db.select({id:c.id}).from(c).where(o).limit(1).get())return;s.db.update(c).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(c.id,t)).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to update thread title",r)}finally{s.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let s=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,r=new Date().toISOString();if(n.db.select({id:c.id,message_count:c.message_count}).from(c).where(drizzleOrm.eq(c.id,t)).limit(1).get()){let l={updated_at:r};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(c).set(l).where(drizzleOrm.eq(c.id,t)).run();}else n.db.insert(c).values({id:t,platform:e.platform,workspace_id:s,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to upsert thread",s)}finally{n.close();}}ensureThread(t,e,n){let s=this.openHandle(true);try{let r=n?this.validateWorkspaceId(s,n):null,o=s.db.select({id:c.id,platform:c.platform,workspace_id:c.workspace_id}).from(c).where(drizzleOrm.eq(c.id,t)).limit(1).get();if(o){r&&!o.workspace_id&&s.db.update(c).set({workspace_id:r}).where(drizzleOrm.eq(c.id,t)).run();return}let l=new Date().toISOString();s.db.insert(c).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:l,updated_at:l}).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to ensure thread",r)}finally{s.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let s=this.openHandle(true);try{let r=new Date().toISOString();return {firstMessage:s.db.transaction(l=>{let p=l.select({message_count:c.message_count}).from(c).where(drizzleOrm.eq(c.id,t)).limit(1).get()?.message_count===0;return l.run(drizzleOrm.sql`
254
+ `);for(let u of l){let c=u.thread_id;n.has(c)||n.set(c,[]),n.get(c).push(u);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{o.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=drizzleOrm.eq(p.id,t),o=n?drizzleOrm.and(r,drizzleOrm.eq(p.workspace_id,n)):r;if(!s.db.select({id:p.id}).from(p).where(o).limit(1).get())return;s.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread title",r)}finally{s.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let s=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,r=new Date().toISOString();if(n.db.select({id:p.id,message_count:p.message_count}).from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get()){let l={updated_at:r};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(p).set(l).where(drizzleOrm.eq(p.id,t)).run();}else n.db.insert(p).values({id:t,platform:e.platform,workspace_id:s,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to upsert thread",s)}finally{n.close();}}ensureThread(t,e,n){let s=this.openHandle(true);try{let r=n?this.validateWorkspaceId(s,n):null,o=s.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get();if(o){r&&!o.workspace_id&&s.db.update(p).set({workspace_id:r}).where(drizzleOrm.eq(p.id,t)).run();return}let l=new Date().toISOString();s.db.insert(p).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:l,updated_at:l}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to ensure thread",r)}finally{s.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let s=this.openHandle(true);try{let r=new Date().toISOString();return {firstMessage:s.db.transaction(l=>{let c=l.select({message_count:p.message_count}).from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get()?.message_count===0;return l.run(drizzleOrm.sql`
129
255
  UPDATE threads
130
256
  SET first_message = COALESCE(first_message, ${e}),
131
257
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
@@ -133,4 +259,4 @@ ${n.join(`
133
259
  message_count = message_count + 1,
134
260
  updated_at = ${r}
135
261
  WHERE id = ${t}
136
- `),p},{behavior:"immediate"})}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to save user message",r)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.update(c).set({last_message:e,updated_at:r}).where(drizzleOrm.eq(c.id,t)).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to save assistant message",r)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(c).set(s).where(drizzleOrm.eq(c.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update thread",s)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let s=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),r=n.db.select({pinned:c.pinned,metadata:c.metadata}).from(c).where(s).get();if(!r)return null;let o=r.pinned?0:1,l=r.metadata?JSON.parse(r.metadata):{};if(o){let u=e?drizzleOrm.and(drizzleOrm.eq(c.pinned,1),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.pinned,1),p=n.db.select({metadata:c.metadata}).from(c).where(u).all(),f=0;for(let m of p){let g=m.metadata?JSON.parse(m.metadata):{};typeof g.pinOrder=="number"&&g.pinOrder>f&&(f=g.pinOrder);}l.pinOrder=f+1;}else delete l.pinOrder;return n.db.update(c).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(s).run(),{pinned:!!o}}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to toggle pin",s)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let s=0;s<t.length;s++){let r=e?drizzleOrm.and(drizzleOrm.eq(c.id,t[s]),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t[s]),o=n.db.select({metadata:c.metadata}).from(c).where(r).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=s+1,n.db.update(c).set({metadata:JSON.stringify(l)}).where(r).run();}}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to reorder pins",s)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let s=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),r=n.db.select({starred:c.starred}).from(c).where(s).get();if(!r)return null;let o=r.starred?0:1;return n.db.update(c).set({starred:o}).where(s).run(),{starred:!!o}}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to toggle star",s)}finally{n.close();}}};var Rt=class extends E{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=z.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(q).values(t).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(q).where(drizzleOrm.eq(q.task_id,t)).all()}catch(n){throw new a("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(q).where(drizzleOrm.eq(q.id,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var yt=class extends E{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=z.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(v).values(t).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(v).where(drizzleOrm.eq(v.task_id,t)).all()}catch(n){throw new a("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:v.tool_name,count:drizzleOrm.sql`count(*)`}).from(v).where(drizzleOrm.eq(v.task_id,t)).groupBy(v.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new a("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var Et=class extends E{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=z.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}ensureThreadExists(t,e){if(!t.db.select({id:c.id}).from(c).where(drizzleOrm.eq(c.id,e)).limit(1).get())throw new a("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(N).where(drizzleOrm.eq(N.thread_id,t)).orderBy(drizzleOrm.asc(N.seq)).all()}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(N).where(drizzleOrm.and(drizzleOrm.eq(N.id,e),drizzleOrm.eq(N.thread_id,t))).limit(1).get()??void 0}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to find box by id",s)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(N).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(s){throw s instanceof Error&&/UNIQUE constraint failed/i.test(s.message)?new a("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,s):s}let n=e.db.select().from(N).where(drizzleOrm.eq(N.id,t.id)).limit(1).get();if(!n)throw new a("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var St=class extends E{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=z.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(s=>{for(let r of t)s.insert(G).values({id:crypto.randomUUID(),path:r.path,method:r.method,status_code:r.statusCode,duration_ms:r.durationMs,ip:r.ip??null,request_headers:r.requestHeaders??null,response_headers:r.responseHeaders??null,request_body:r.requestBody??null,response_body:r.responseBody??null,query:r.query??null,user_id:r.userId??null,project_id:r.projectId??null,partition_key:r.partitionKey??"default",timestamp:n,metadata:r.metadata??null}).run();});}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(G).orderBy(drizzleOrm.desc(G.timestamp)).limit(t).all()}catch(n){throw new a("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};exports.BaseSqliteRepository=E;exports.RepositoryError=a;exports.RequestLogRepository=St;exports.SpanRepository=Rt;exports.TaskRepository=kt;exports.ThreadBoxRepository=Et;exports.ThreadRepository=bt;exports.ToolCallRepository=yt;exports.WorkspaceRepository=mt;exports.openDrizzleDb=k;exports.pushSchema=xe;exports.runMigrations=X;exports.runMigrationsOnce=T;
262
+ `),c},{behavior:"immediate"})}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save user message",r)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.update(p).set({last_message:e,updated_at:r}).where(drizzleOrm.eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save assistant message",r)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(p).set(s).where(drizzleOrm.eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread",s)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let s=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t),r=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(s).get();if(!r)return null;let o=r.pinned?0:1,l=r.metadata?JSON.parse(r.metadata):{};if(o){let u=e?drizzleOrm.and(drizzleOrm.eq(p.pinned,1),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.pinned,1),c=n.db.select({metadata:p.metadata}).from(p).where(u).all(),h=0;for(let m of c){let w=m.metadata?JSON.parse(m.metadata):{};typeof w.pinOrder=="number"&&w.pinOrder>h&&(h=w.pinOrder);}l.pinOrder=h+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(s).run(),{pinned:!!o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to toggle pin",s)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let s=0;s<t.length;s++){let r=e?drizzleOrm.and(drizzleOrm.eq(p.id,t[s]),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t[s]),o=n.db.select({metadata:p.metadata}).from(p).where(r).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=s+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(r).run();}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to reorder pins",s)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let s=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t),r=n.db.select({starred:p.starred}).from(p).where(s).get();if(!r)return null;let o=r.starred?0:1;return n.db.update(p).set({starred:o}).where(s).run(),{starred:!!o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to toggle star",s)}finally{n.close();}}};var St=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=I.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=I.dirname(e);Ht.existsSync(s)||Ht.mkdirSync(s,{recursive:true});}else if(!Ht.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(s){throw n.close(),s}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(z).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(z).where(drizzleOrm.eq(z.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(z).where(drizzleOrm.eq(z.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var Tt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=I.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=I.dirname(e);Ht.existsSync(s)||Ht.mkdirSync(s,{recursive:true});}else if(!Ht.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(P).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(P).where(drizzleOrm.eq(P.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:P.tool_name,count:drizzleOrm.sql`count(*)`}).from(P).where(drizzleOrm.eq(P.task_id,t)).groupBy(P.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var Dt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=I.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=I.dirname(e);Ht.existsSync(s)||Ht.mkdirSync(s,{recursive:true});}else if(!Ht.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(s){throw n.close(),s}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(drizzleOrm.eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(C).where(drizzleOrm.eq(C.thread_id,t)).orderBy(drizzleOrm.asc(C.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.id,e),drizzleOrm.eq(C.thread_id,t))).limit(1).get()??void 0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to find box by id",s)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(C).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(s){throw s instanceof Error&&/UNIQUE constraint failed/i.test(s.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,s):s}let n=e.db.select().from(C).where(drizzleOrm.eq(C.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var xt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=I.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=I.dirname(e);Ht.existsSync(s)||Ht.mkdirSync(s,{recursive:true});}else if(!Ht.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(s){throw n.close(),s}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(s=>{for(let r of t)s.insert(V).values({id:crypto.randomUUID(),path:r.path,method:r.method,status_code:r.statusCode,duration_ms:r.durationMs,ip:r.ip??null,request_headers:r.requestHeaders??null,response_headers:r.responseHeaders??null,request_body:r.requestBody??null,response_body:r.responseBody??null,query:r.query??null,user_id:r.userId??null,project_id:r.projectId??null,partition_key:r.partitionKey??"default",timestamp:n,metadata:r.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(V).orderBy(drizzleOrm.desc(V.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};exports.BaseSqliteRepository=S;exports.RepositoryError=d;exports.RequestLogRepository=xt;exports.SpanRepository=St;exports.TaskRepository=Rt;exports.ThreadBoxRepository=Dt;exports.ThreadRepository=yt;exports.ToolCallRepository=Tt;exports.WorkspaceRepository=kt;exports.openDrizzleDb=k;exports.pushSchema=Ae;exports.runMigrations=J;exports.runMigrationsOnce=x;exports.tasks=i;
@@ -10,6 +10,7 @@ export interface AgentUsageRow {
10
10
  outputTokens: number;
11
11
  cachedInputTokens: number;
12
12
  costUsd: number;
13
+ totalTokens: number;
13
14
  }
14
15
  export interface TrendRow {
15
16
  date: string;
@@ -18,6 +19,18 @@ export interface TrendRow {
18
19
  outputTokens: number;
19
20
  cachedInputTokens: number;
20
21
  costUsd: number;
22
+ totalTokens: number;
23
+ }
24
+ export interface ProviderUsageRow {
25
+ provider: string;
26
+ totalTasks: number;
27
+ inputTokens: number;
28
+ outputTokens: number;
29
+ cachedInputTokens: number;
30
+ costUsd: number;
31
+ totalTokens: number;
32
+ activeDurationMs: number;
33
+ lastActiveAt: string | null;
21
34
  }
22
35
  export declare class TaskRepository extends BaseSqliteRepository {
23
36
  private readonly dbPath?;
@@ -61,6 +74,7 @@ export declare class TaskRepository extends BaseSqliteRepository {
61
74
  cachedInputTokens?: number;
62
75
  costUsd?: number;
63
76
  model?: string | null;
77
+ runEpoch?: number | null;
64
78
  }): void;
65
79
  appendLog(taskId: string, entry: {
66
80
  timestamp: string;
@@ -112,4 +126,5 @@ export declare class TaskRepository extends BaseSqliteRepository {
112
126
  findTaskForStop(taskId: string, workspaceId: string): TaskRow | undefined;
113
127
  markTaskFailed(taskId: string, error: string, workspaceId?: string): void;
114
128
  findTasksByPromptHint(hint: string, workspaceId?: string): TaskRow[];
129
+ getProviderUsage(from: string, to: string, workspace?: string): ProviderUsageRow[];
115
130
  }
@@ -24,7 +24,7 @@ export declare class ThreadRepository extends BaseSqliteRepository {
24
24
  costUsd: number;
25
25
  agentIds: string[];
26
26
  };
27
- findTopLevelTasks(threadId: string, workspaceId?: string): TaskRow[];
27
+ findTopLevelTasks(threadId: string, workspaceId?: string, limit?: number): TaskRow[];
28
28
  findAllTasks(threadId: string, workspaceId?: string): TaskRow[];
29
29
  findTaskById(threadId: string, taskId: string, workspaceId?: string): {
30
30
  task: TaskRow;