@crewx/sdk 0.8.7-rc.8 → 0.8.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/context/DailyLoader.d.ts +2 -0
- package/dist/context/GoalLoader.d.ts +2 -0
- package/dist/esm/index.js +33 -29
- package/dist/esm/plugins/index.js +11 -11
- package/dist/esm/repository/index.js +10 -10
- package/dist/index.browser.js +2 -2
- package/dist/index.js +33 -29
- package/dist/layout/types.d.ts +4 -0
- package/dist/migrations/0004_add_thread_pin_star.sql +2 -0
- package/dist/migrations/meta/_journal.json +9 -2
- package/dist/platform/BrowserFsAdapter.d.ts +1 -0
- package/dist/platform/IFsAdapter.d.ts +1 -0
- package/dist/platform/NodeFsAdapter.d.ts +1 -0
- package/dist/plugins/index.js +11 -11
- package/dist/provider/cli/adapters/antigravity.d.ts +2 -0
- package/dist/provider/cli/adapters/index.d.ts +1 -0
- package/dist/provider/cli/index.d.ts +1 -1
- package/dist/repository/index.js +10 -10
- package/dist/repository/task.repository.d.ts +1 -0
- package/dist/repository/thread.repository.d.ts +7 -0
- package/dist/schema/threads.d.ts +34 -0
- package/package.json +1 -1
- package/templates/agents/default.yaml +22 -0
package/dist/repository/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var Lt=require('fs'),U=require('path'),Kt=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 U__namespace=/*#__PURE__*/_interopNamespace(U);var Kt__default=/*#__PURE__*/_interopDefault(Kt);var Z=(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 R=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:U.join(Kt__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 d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function w(a){let t=Z("better-sqlite3"),{drizzle:e}=Z("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:(r,s=[])=>n.prepare(r).run(...s),close:()=>n.close()}}var St=new Set,Vt={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 Qt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Zt(a,t){if(t>0||!Qt(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,s]of Object.entries(Vt))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}function te(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(Lt.readFileSync(U__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=U__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(r.has(p))continue;let f=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],b;for(;(b=f.exec(u))!==null;)m.push({table:b[1],column:b[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(L=>L.trim()).filter(Boolean).every(L=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(L)))continue;m.every(({table:L,column:J})=>a.all(`PRAGMA table_info("${L}")`).some(lt=>lt.name===J))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${o.when})`);}}function X(a){let{migrate:t}=Z("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Z("drizzle-orm"),n=[U__namespace.default.join(__dirname,"../migrations"),U__namespace.default.join(__dirname,"migrations"),U__namespace.default.join(__dirname,"../../../../drizzle/migrations"),U__namespace.default.join(process.cwd(),"drizzle/migrations")],r=n.find(p=>Lt.existsSync(U__namespace.default.join(p,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
|
|
2
2
|
${n.join(`
|
|
3
|
-
`)}`);let r=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Vt(a,i),t(a,{migrationsFolder:s});let c=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${c} migration${c>1?"s":""} applied).`);}}function S(a,t){Et.has(t)||(j(a),Et.add(t));}var u=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 o=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)},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 _=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>u.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)},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 q=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.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")},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 B=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.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 P=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>_.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 X=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 lt(a){let t=G__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 Pt(a){let t=lt(a);return crypto.createHash("sha256").update(t).digest("hex")}function tt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var pt=class extends y{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?G.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=G.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=m(e);if(t)try{j(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=tt(G.basename(n)),i=`${tt(G.basename(G.dirname(n)))}-${s}`,l=[s,i];try{let c=p=>t.select({id:u.id}).from(u).where(drizzleOrm.and(drizzleOrm.eq(u.slug,p),drizzleOrm.ne(u.id,e))).limit(1).all().length>0;for(let p of l)if(!c(p))return p;for(let p=2;p<1e3;p+=1){let h=`${i}-${p}`;if(!c(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:u.id,slug:u.slug}).from(u).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=tt(s.slug.replace(/\//g,"-"));t.db.update(u).set({slug:r,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(u.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:i}=e,l=new Date().toISOString();t.insert(u).values({id:n,slug:s,name:r,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(u).set({workspace_path:i,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(u.id,n),drizzleOrm.isNull(u.workspace_path))).run();}registerWorkspace(t){let e=lt(t),n=this.openHandle(true);try{let s=Pt(e),r=G.basename(e),i=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:i,name:r,workspacePath:e}),{id:s,slug:i}}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(u.is_active,t.isActive?1:0):void 0,s=e.db.select({count:drizzleOrm.sql`count(*)`}).from(u).where(n).get();return {rows:e.db.select().from(u).where(n).orderBy(drizzleOrm.desc(u.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(u).where(drizzleOrm.eq(u.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.*,
|
|
3
|
+
`)}`);let s=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;s?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Zt(a,o),te(a,r,e),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let p=s?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${u} migration${u>1?"s":""} applied).`);}}function T(a,t){St.has(t)||(X(a),St.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 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)},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 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)},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 H=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(()=>H.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 v=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 P=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()},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 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")},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 ut(a){let t=U__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 Bt(a){let t=ut(a);return crypto.createHash("sha256").update(t).digest("hex")}function rt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var ft=class extends R{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?U.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{X(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=rt(U.basename(n)),o=`${rt(U.basename(U.dirname(n)))}-${r}`,l=[r,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 r}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 r of e)if(r.slug.includes("/")){let s=rt(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:s,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:s,workspacePath:o}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:r,name:s,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=ut(t),n=this.openHandle(true);try{let r=Bt(e),s=U.basename(e),o=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:o,name:s,workspacePath:e}),{id:r,slug:o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?drizzleOrm.eq(h.is_active,t.isActive?1:0):void 0,r=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:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.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(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(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:
|
|
8
|
+
LIMIT ${e.limit} OFFSET ${e.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?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(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.insert(h).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:o,updated_at:o}).run();let l=s.db.select().from(h).where(drizzleOrm.eq(h.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{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.is_active,1),drizzleOrm.isNotNull(h.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;Lt.existsSync(U.join(s,"crewx.yaml"))||Lt.existsSync(U.join(s,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(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 d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Ht=[h,i,c,H,v,P,G];function Re(){return U__namespace.default.join(Kt__default.default.homedir(),".crewx","crewx.db")}function Ee(a){if(!Lt__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Lt__default.default.copyFileSync(a,e),e}function Ft(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 De(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 Se(a,t){let e=t?.dbPath??Re(),n=t?.force??false,r=t?.dryRun??false,s=r?null:Ee(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Ft(a);if(!r)try{X(a);}catch(m){let b=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!b.includes("duplicate column"))throw m}let l,u;r?(l=Ht.map(b=>sqliteCore.getTableConfig(b).name).filter(b=>!o.has(b)),u=o):(u=Ft(a),l=[...u].filter(m=>!o.has(m)));let p=[],f=[];for(let m of Ht){let b=sqliteCore.getTableConfig(m),D=b.name;if(!u.has(D))continue;let B=a.all(`PRAGMA table_info("${D}")`),L=new Set(B.map(N=>N.name)),J=new Set(b.columns.map(N=>N.name));for(let N of b.columns)if(!L.has(N.name)){if(!r){let lt=De(N);a.run(`ALTER TABLE "${D}" ADD COLUMN ${lt}`);}p.push({table:D,column:N.name});}for(let N of B)J.has(N.name)||f.push(`${D}.${N.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:p,warnings:f,backupPath:s}}var gt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}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{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 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(
|
|
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 d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let s=r.select({logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get(),o=s?.logs?JSON.parse(s.logs):[];o.push(e),r.update(i).set({logs:JSON.stringify(o)}).where(drizzleOrm.eq(i.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(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 r of e){let s=!1;if(r.pid)try{process.kill(r.pid,0),s=!0;}catch{}s||(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,r.id),drizzleOrm.eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Lt.existsSync(r))continue;let s=w(r);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=s.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let p=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),f=o?drizzleOrm.and(p,o):p;u=s.db.select().from(i).where(f).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{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(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),p=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
|
|
11
11
|
SELECT
|
|
12
12
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
13
13
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -28,7 +28,7 @@ ${n.join(`
|
|
|
28
28
|
FROM tasks
|
|
29
29
|
GROUP BY workspace_id
|
|
30
30
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
31
|
-
`)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),
|
|
31
|
+
`)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,s=0,o=0,l=0;for(let u of n){if(!Lt.existsSync(u))continue;let p=w(u);try{let f=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(f,drizzleOrm.eq(i.workspace_id,e)):f,b=p.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 D of b)r.has(D.id)||(r.add(D.id),s+=D.input_tokens??0,o+=D.output_tokens??0,l+=D.cost_usd??0);}catch(f){throw new d("DB_ERROR","Failed to get thread token usage",f)}finally{p.close();}}return {inputTokens:s,outputTokens:o,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(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}%`))),p=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,f=l.db.select().from(i).where(p).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of f)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}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 r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(drizzleOrm.inArray(i.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(drizzleOrm.inArray(i.status,s));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(),p=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(i.started_at):drizzleOrm.desc(i.started_at);return {rows:e.db.select().from(i).where(l).orderBy(p).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?drizzleOrm.sql`
|
|
32
32
|
SELECT
|
|
33
33
|
t.agent_id,
|
|
34
34
|
t.workspace_id,
|
|
@@ -59,7 +59,7 @@ ${n.join(`
|
|
|
59
59
|
AND t.started_at < ${e}
|
|
60
60
|
GROUP BY t.agent_id, t.workspace_id
|
|
61
61
|
ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
|
|
62
|
-
`).map(
|
|
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(s){throw new d("DB_ERROR","Failed to get agent usage",s)}finally{r.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?drizzleOrm.sql`
|
|
63
63
|
SELECT
|
|
64
64
|
date(t.started_at) AS date,
|
|
65
65
|
t.agent_id,
|
|
@@ -88,18 +88,18 @@ ${n.join(`
|
|
|
88
88
|
AND t.started_at < ${e}
|
|
89
89
|
GROUP BY date(t.started_at), t.agent_id
|
|
90
90
|
ORDER BY date(t.started_at) ASC
|
|
91
|
-
`).map(
|
|
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(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.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(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=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"));r.db.update(i).set({status:"failed",error:e,completed_at:s}).where(o).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=e?drizzleOrm.and(drizzleOrm.like(i.prompt,`%${t}%`),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.like(i.prompt,`%${t}%`),p=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}};var bt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}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}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!Lt.existsSync(s))continue;let o=w(s);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),r.push(p));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{o.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Lt.existsSync(r))continue;let s=w(r);try{let o=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(c.workspace_id,e)):o,u=s.db.select().from(c).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{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Lt.existsSync(r))continue;let s=w(r);try{let o=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(c.workspace_id,e)):o;if(s.db.select({id:c.id}).from(c).where(l).limit(1).get())return !0}catch(o){throw new d("DB_ERROR","Failed to check thread existence",o)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,o=0,l=0,u=0,p=new Set;for(let f of n){if(!Lt.existsSync(f))continue;let m=w(f);try{let b=drizzleOrm.and(drizzleOrm.eq(i.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(i.parent_task_id),drizzleOrm.eq(i.parent_task_id,""))),D=e?drizzleOrm.and(b,drizzleOrm.eq(i.workspace_id,e)):b,B=m.db.select({cnt:drizzleOrm.sql`count(*)`,total_input:drizzleOrm.sql`COALESCE(SUM(input_tokens), 0)`,total_output:drizzleOrm.sql`COALESCE(SUM(output_tokens), 0)`,total_cached:drizzleOrm.sql`COALESCE(SUM(cached_input_tokens), 0)`,total_cost:drizzleOrm.sql`COALESCE(SUM(cost_usd), 0)`}).from(i).where(D).get();B&&(r+=B.cnt,s+=B.total_input,o+=B.total_output,l+=B.total_cached,u+=B.total_cost);let L=m.db.all(drizzleOrm.sql`
|
|
92
92
|
SELECT DISTINCT agent_id FROM tasks
|
|
93
93
|
WHERE thread_id = ${t}
|
|
94
94
|
AND agent_id IS NOT NULL AND agent_id != ''
|
|
95
95
|
AND (parent_task_id IS NULL OR parent_task_id = '')
|
|
96
96
|
${e?drizzleOrm.sql`AND workspace_id = ${e}`:drizzleOrm.sql``}
|
|
97
|
-
`);for(let
|
|
97
|
+
`);for(let J of L)p.add(J.agent_id);}catch(b){throw new d("DB_ERROR","Failed to aggregate task stats",b)}finally{m.close();}}return {taskCount:r,inputTokens:s,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=drizzleOrm.and(drizzleOrm.eq(i.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(i.parent_task_id),drizzleOrm.eq(i.parent_task_id,""))),p=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,f=l.db.select().from(i).where(p).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of f)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}return s}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=drizzleOrm.eq(i.thread_id,t),p=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,f=l.db.select().from(i).where(p).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of f)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let s of r){if(!Lt.existsSync(s))continue;let o=w(s);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,p=o.db.select().from(i).where(u).limit(1).get();if(!p)continue;let f=o.db.select().from(i).where(drizzleOrm.eq(i.parent_task_id,p.id)).orderBy(drizzleOrm.asc(i.started_at)).all();return {task:p,children:f}}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 r=this.resolveDbPaths();for(let s of r){if(!Lt.existsSync(s))continue;let o=w(s);try{let l=drizzleOrm.and(drizzleOrm.inArray(i.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(i.parent_task_id),drizzleOrm.eq(i.parent_task_id,""))),u=e?drizzleOrm.and(l,drizzleOrm.eq(i.workspace_id,e)):l,p=o.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let f of p){let m=f.thread_id;n.has(m)||n.set(m,[]),n.get(m).push(f);}}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 r=this.openHandle(true);try{let s=drizzleOrm.eq(c.id,t),o=n?drizzleOrm.and(s,drizzleOrm.eq(c.workspace_id,n)):s;if(!r.db.select({id:c.id}).from(c).where(o).limit(1).get())return;r.db.update(c).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(c.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread title",s)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,s=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:s};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:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let s=n?this.validateWorkspaceId(r,n):null,o=r.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){s&&!o.workspace_id&&r.db.update(c).set({workspace_id:s}).where(drizzleOrm.eq(c.id,t)).run();return}let l=new Date().toISOString();r.db.insert(c).values({id:t,platform:e,workspace_id:s,message_count:0,created_at:l,updated_at:l}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.run(drizzleOrm.sql`
|
|
98
98
|
UPDATE threads
|
|
99
99
|
SET first_message = COALESCE(first_message, ${e}),
|
|
100
100
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
|
|
101
101
|
last_message = ${e},
|
|
102
102
|
message_count = message_count + 1,
|
|
103
|
-
updated_at = ${
|
|
103
|
+
updated_at = ${s}
|
|
104
104
|
WHERE id = ${t}
|
|
105
|
-
`);}catch(
|
|
105
|
+
`);}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(c).set({last_message:e,updated_at:s}).where(drizzleOrm.eq(c.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(c).set(r).where(drizzleOrm.eq(c.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),s=n.db.select({pinned:c.pinned,metadata:c.metadata}).from(c).where(r).get();if(!s)return null;let o=s.pinned?0:1,l=s.metadata?JSON.parse(s.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 b=m.metadata?JSON.parse(m.metadata):{};typeof b.pinOrder=="number"&&b.pinOrder>f&&(f=b.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(r).run(),{pinned:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?drizzleOrm.and(drizzleOrm.eq(c.id,t[r]),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t[r]),o=n.db.select({metadata:c.metadata}).from(c).where(s).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=r+1,n.db.update(c).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),s=n.db.select({starred:c.starred}).from(c).where(r).get();if(!s)return null;let o=s.starred?0:1;return n.db.update(c).set({starred:o}).where(r).run(),{starred:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}};var yt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(H).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(H).where(drizzleOrm.eq(H.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(H).where(drizzleOrm.eq(H.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 Rt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(v).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(v).where(drizzleOrm.eq(v.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: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 d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var Et=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}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 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(P).where(drizzleOrm.eq(P.thread_id,t)).orderBy(drizzleOrm.asc(P.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(P).where(drizzleOrm.and(drizzleOrm.eq(P.id,e),drizzleOrm.eq(P.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(P).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(P).where(drizzleOrm.eq(P.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 R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(G).values({id:crypto.randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(G).orderBy(drizzleOrm.desc(G.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};exports.BaseSqliteRepository=R;exports.RepositoryError=d;exports.RequestLogRepository=xt;exports.SpanRepository=yt;exports.TaskRepository=gt;exports.ThreadBoxRepository=Et;exports.ThreadRepository=bt;exports.ToolCallRepository=Rt;exports.WorkspaceRepository=ft;exports.openDrizzleDb=w;exports.pushSchema=Se;exports.runMigrations=X;exports.runMigrationsOnce=T;
|
|
@@ -74,6 +74,7 @@ export declare class TaskRepository extends BaseSqliteRepository {
|
|
|
74
74
|
killed: boolean;
|
|
75
75
|
pid?: number;
|
|
76
76
|
};
|
|
77
|
+
reapOrphanedTasks(): number;
|
|
77
78
|
findTaskStatus(taskId: string, workspaceId?: string): TaskRow | undefined;
|
|
78
79
|
findChildTasks(parentTaskId: string, workspaceId?: string): TaskRow[];
|
|
79
80
|
getWorkspaceUsageSummary(workspaceId?: string): Array<{
|
|
@@ -53,4 +53,11 @@ export declare class ThreadRepository extends BaseSqliteRepository {
|
|
|
53
53
|
title?: string;
|
|
54
54
|
titleLocked?: boolean;
|
|
55
55
|
}): void;
|
|
56
|
+
togglePin(threadId: string, workspaceId?: string): {
|
|
57
|
+
pinned: boolean;
|
|
58
|
+
} | null;
|
|
59
|
+
reorderPins(threadIds: string[], workspaceId?: string): void;
|
|
60
|
+
toggleStar(threadId: string, workspaceId?: string): {
|
|
61
|
+
starred: boolean;
|
|
62
|
+
} | null;
|
|
56
63
|
}
|
package/dist/schema/threads.d.ts
CHANGED
|
@@ -207,6 +207,40 @@ export declare const threads: import("drizzle-orm/sqlite-core").SQLiteTableWithC
|
|
|
207
207
|
identity: undefined;
|
|
208
208
|
generated: undefined;
|
|
209
209
|
}, {}, {}>;
|
|
210
|
+
pinned: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
211
|
+
name: "pinned";
|
|
212
|
+
tableName: "threads";
|
|
213
|
+
dataType: "number";
|
|
214
|
+
columnType: "SQLiteInteger";
|
|
215
|
+
data: number;
|
|
216
|
+
driverParam: number;
|
|
217
|
+
notNull: true;
|
|
218
|
+
hasDefault: true;
|
|
219
|
+
isPrimaryKey: false;
|
|
220
|
+
isAutoincrement: false;
|
|
221
|
+
hasRuntimeDefault: false;
|
|
222
|
+
enumValues: undefined;
|
|
223
|
+
baseColumn: never;
|
|
224
|
+
identity: undefined;
|
|
225
|
+
generated: undefined;
|
|
226
|
+
}, {}, {}>;
|
|
227
|
+
starred: import("drizzle-orm/sqlite-core").SQLiteColumn<{
|
|
228
|
+
name: "starred";
|
|
229
|
+
tableName: "threads";
|
|
230
|
+
dataType: "number";
|
|
231
|
+
columnType: "SQLiteInteger";
|
|
232
|
+
data: number;
|
|
233
|
+
driverParam: number;
|
|
234
|
+
notNull: true;
|
|
235
|
+
hasDefault: true;
|
|
236
|
+
isPrimaryKey: false;
|
|
237
|
+
isAutoincrement: false;
|
|
238
|
+
hasRuntimeDefault: false;
|
|
239
|
+
enumValues: undefined;
|
|
240
|
+
baseColumn: never;
|
|
241
|
+
identity: undefined;
|
|
242
|
+
generated: undefined;
|
|
243
|
+
}, {}, {}>;
|
|
210
244
|
};
|
|
211
245
|
dialect: "sqlite";
|
|
212
246
|
}>;
|
package/package.json
CHANGED
|
@@ -109,6 +109,18 @@ layouts:
|
|
|
109
109
|
</agent_profile>
|
|
110
110
|
{{/if}}
|
|
111
111
|
|
|
112
|
+
{{#if documents.active_goals}}
|
|
113
|
+
<crewx_context type="goals">
|
|
114
|
+
{{{documents.active_goals.content}}}
|
|
115
|
+
</crewx_context>
|
|
116
|
+
{{/if}}
|
|
117
|
+
|
|
118
|
+
{{#if documents.today_daily}}
|
|
119
|
+
<crewx_context type="daily">
|
|
120
|
+
{{{documents.today_daily.content}}}
|
|
121
|
+
</crewx_context>
|
|
122
|
+
{{/if}}
|
|
123
|
+
|
|
112
124
|
{{#if props.showManual}}
|
|
113
125
|
{{#if documents.crewx_manual.toc}}
|
|
114
126
|
<document name="CrewX User Manual (TOC)">
|
|
@@ -189,6 +201,16 @@ layouts:
|
|
|
189
201
|
|
|
190
202
|
Types: `exec` (has entrypoint, runs script) | `doc` (no entrypoint, outputs markdown)
|
|
191
203
|
|
|
204
|
+
### Work Instruction (`$CREWX_CLI wi`)
|
|
205
|
+
Structured task delegation. Create and issue work instructions to agents.
|
|
206
|
+
|
|
207
|
+
```bash
|
|
208
|
+
{{env.CREWX_CLI}} wi usage # Show detailed guide
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Template: docs/wi/WI-TEMPLATE.md
|
|
212
|
+
→ Full usage: `{{env.CREWX_CLI}} wi usage`
|
|
213
|
+
|
|
192
214
|
### Workflow (`{{env.CREWX_CLI}} workflow`)
|
|
193
215
|
Semantic workflow — structured collaboration recipes for agents. Not auto-executed; agents follow the flow step by step.
|
|
194
216
|
|