@crewx/sdk 0.9.0-rc.55 → 0.9.0-rc.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/models.generated.d.ts +2 -2
- package/dist/config/pricing.generated.d.ts +3 -3
- package/dist/context-budget/index.d.ts +105 -0
- package/dist/esm/index.js +93 -85
- package/dist/esm/plugins/index.js +3 -3
- package/dist/esm/repository/index.js +2 -2
- package/dist/esm/testing/index.js +1 -1
- package/dist/facade/Crewx.d.ts +14 -0
- package/dist/index.browser.d.ts +1 -1
- package/dist/index.browser.js +5 -5
- package/dist/index.d.ts +4 -2
- package/dist/index.js +93 -85
- package/dist/provider/bridge.d.ts +2 -0
- package/dist/provider/cli/adapter.types.d.ts +1 -0
- package/dist/provider/cli/adapters/cli-knob.util.d.ts +2 -0
- package/dist/provider/cli/adapters/grok.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/provider/order.d.ts +1 -1
- package/dist/repository/index.js +12 -12
- package/dist/testing/index.js +1 -1
- package/dist/types/index.d.ts +303 -0
- package/package.json +2 -1
|
@@ -10,7 +10,7 @@ Message: ${n.message}
|
|
|
10
10
|
[${r}] INFO: Process closed with exit code: ${n.error?1:0}
|
|
11
11
|
`;appendFileSync(s,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(t){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};function re(d){let t=F.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(n,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function $t(d){let t=re(d);return createHash("sha256").update(t).digest("hex")}var nt=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(ae.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};function b(d){let t=dt("better-sqlite3"),{drizzle:n}=dt("drizzle-orm/better-sqlite3"),s=new t(d);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400"),s.exec("PRAGMA optimize"),{db:n(s),runRaw:(r,o=[])=>s.prepare(r).run(...o),close:()=>s.close()}}var Lt=new Set,de={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 St(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function le(d,t){if(t>0||!St(d,"tasks"))return;let n=d.all("PRAGMA table_info(tasks)"),s=new Set(n.map(r=>r.name));for(let[r,o]of Object.entries(de))s.has(r)||d.run(`ALTER TABLE tasks ADD COLUMN ${r} ${o}`);}var ce={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function ue(d,t,n){if(!St(d,"__drizzle_migrations")||!St(d,"tasks"))return;let s=d.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(s.map(i=>i.hash)),o=JSON.parse(readFileSync(F__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let a=ce[i.tag];if(!a)continue;let c=F__default.join(t,`${i.tag}.sql`);if(!existsSync(c))continue;let l=readFileSync(c,"utf-8"),u=createHash("sha256").update(l).digest("hex");if(r.has(u))continue;let h=d.all("PRAGMA table_info(tasks)"),g=new Set(h.map(y=>y.name));for(let[y,C]of Object.entries(a))g.has(y)||(d.run(`ALTER TABLE tasks ADD COLUMN ${y} ${C}`),g.add(y));}}function pe(d,t,n){let s=d.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(s.map(i=>i.hash)),o=JSON.parse(readFileSync(F__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let a=F__default.join(t,`${i.tag}.sql`);if(!existsSync(a))continue;let c=readFileSync(a,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(r.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,h=[],g;for(;(g=u.exec(c))!==null;)h.push({table:g[1],column:g[2]});if(h.length===0||!c.split(/-->\s*statement-breakpoint/).map(N=>N.trim()).filter(Boolean).every(N=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(N)))continue;h.every(({table:N,column:$})=>d.all(`PRAGMA table_info("${N}")`).some(B=>B.name===$))&&d.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${i.when})`);}}function _e(d){let{migrate:t}=dt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=dt("drizzle-orm"),s=[F__default.join(k,"../migrations"),F__default.join(k,"migrations"),F__default.join(k,"../../../../drizzle/migrations"),F__default.join(process.cwd(),"drizzle/migrations")],r=s.find(l=>existsSync(F__default.join(l,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
|
|
12
12
|
${s.join(`
|
|
13
|
-
`)}`);let o=d.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=d.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),le(d,i),o?.cnt&&(pe(d,r,n),ue(d,r,n)),t(d,{migrationsFolder:r});let c=(d.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let l=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}}function ct(d,t){Lt.has(t)||(_e(d),Lt.add(t));}var _=class extends Error{code;cause;constructor(t,n,s){super(n),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var st=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var e=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>st.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(d.workspace_id,d.updated_at),idx_threads_title:index("idx_threads_title").on(d.title)}));var Se=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>e.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Se.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>e.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},d=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},d=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(d.workspace_id,d.month)}));sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},d=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(d.workspace_id,sql`${d.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},d=>({pk:primaryKey({columns:[d.notification_id,d.user_id]})}));sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},d=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(d.workspace_id,d.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(d.workspace_id,d.created_at)}));function Wt(d){let t=d.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let n=t.lastIndexOf("/");return n>=0&&(t=t.slice(n+1)),t=t.replace(/-\d{8}$/,""),t}var G="2026-05-09",je="0.8.9-rc.13",X=10,Y=parseInt(je.split("rc.")[1]),Ke=new Set(["workflow","mcp"]),jt=600*1e3,ft=class extends nt{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new _("NOT_FOUND","Database not found");let s=b(n);if(t)try{ct(s.db,n);}catch(r){throw s.close(),r}return s}startTask(t){let n=this.openHandle(true);try{n.db.insert(e).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}).onConflictDoUpdate({target:e.id,set:{pid:sql`COALESCE(excluded.pid, ${e.pid})`},setWhere:eq(e.status,"running")}).run();}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to start task",s)}finally{n.close();}}finishTask(t){let n=this.openHandle(true);try{let s=t.runEpoch??null;n.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
13
|
+
`)}`);let o=d.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=d.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),le(d,i),o?.cnt&&(pe(d,r,n),ue(d,r,n)),t(d,{migrationsFolder:r});let c=(d.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let l=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}}function ct(d,t){Lt.has(t)||(_e(d),Lt.add(t));}var _=class extends Error{code;cause;constructor(t,n,s){super(n),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var st=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var e=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>st.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(d.workspace_id,d.updated_at),idx_threads_title:index("idx_threads_title").on(d.title)}));var Se=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>e.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Se.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>e.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},d=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},d=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(d.workspace_id,d.month)}));sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},d=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(d.workspace_id,sql`${d.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},d=>({pk:primaryKey({columns:[d.notification_id,d.user_id]})}));sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},d=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(d.workspace_id,d.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(d.workspace_id,d.created_at)}));function Wt(d){let t=d.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let n=t.lastIndexOf("/");return n>=0&&(t=t.slice(n+1)),t=t.replace(/-\d{8}$/,""),t}var G="2026-05-09",je="0.8.9-rc.13",X=10,Y=parseInt(je.split("rc.")[1]),Ke=new Set(["workflow","mcp"]),jt=600*1e3,mt=class extends nt{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new _("NOT_FOUND","Database not found");let s=b(n);if(t)try{ct(s.db,n);}catch(r){throw s.close(),r}return s}startTask(t){let n=this.openHandle(true);try{n.db.insert(e).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}).onConflictDoUpdate({target:e.id,set:{pid:sql`COALESCE(excluded.pid, ${e.pid})`},setWhere:eq(e.status,"running")}).run();}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to start task",s)}finally{n.close();}}finishTask(t){let n=this.openHandle(true);try{let s=t.runEpoch??null;n.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
14
14
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
15
15
|
model=COALESCE(?, model)
|
|
16
16
|
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,s]);}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to finish task",s)}finally{n.close();}}appendLog(t,n){let s=this.openHandle(true);try{s.db.transaction(r=>{let o=r.select({logs:e.logs}).from(e).where(eq(e.id,t)).limit(1).get(),i=o?.logs?JSON.parse(o.logs):[];i.push(n),r.update(e).set({logs:JSON.stringify(i)}).where(eq(e.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to append log",r)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(e).where(eq(e.status,"running")).orderBy(desc(e.started_at)).all()}catch(n){throw new _("DB_ERROR","Failed to get running tasks",n)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(e).orderBy(desc(e.started_at)).limit(100).all()}catch(n){throw new _("DB_ERROR","Failed to get all tasks",n)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(e).where(eq(e.id,t)).limit(1).get()??void 0}catch(s){throw new _("DB_ERROR","Failed to get task",s)}finally{n.close();}}killTask(t){if(!this.dbExists())return {killed:false};let n=this.openHandle(true);try{let s=n.db.select({id:e.id,status:e.status,pid:e.pid}).from(e).where(eq(e.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return n.db.update(e).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(e.id,t),eq(e.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to kill task",s)}finally{n.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let n=t.db.select({id:e.id,pid:e.pid,platform:e.platform,run_epoch:e.run_epoch}).from(e).where(eq(e.status,"running")).all(),s=Date.now(),r=new Set,o=0;for(let i of n){if(i.pid){let l=!1;try{process.kill(i.pid,0),l=!0;}catch{}l||(t.db.update(e).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(e.id,i.id),eq(e.status,"running"))).run(),o++);continue}if(Ke.has(i.platform??"cli"))continue;let a=`${i.id}:${i.run_epoch??0}`;r.add(a);let c=this.pidNullObservedSince.get(a);if(c===void 0){this.pidNullObservedSince.set(a,s);continue}s-c>=jt&&(t.db.update(e).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(e.id,i.id),eq(e.status,"running"))).run(),o++,this.pidNullObservedSince.delete(a));}for(let i of Array.from(this.pidNullObservedSince.keys()))r.has(i)||this.pidNullObservedSince.delete(i);return o}finally{t.close();}}reapRunningWorkflowTasks(t=jt){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let s=new Date(Date.now()-t).toISOString();return n.db.update(e).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(e.status,"running"),eq(e.platform,"workflow"),isNull(e.pid),lt(e.started_at,s),or(isNull(e.metadata),notLike(e.metadata,'%"kind":"workflow_card"%')))).run().changes??0}finally{n.close();}}findTaskStatus(t,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let o=b(r);try{let i=n?eq(e.workspace_id,n):void 0,a=i?and(eq(e.id,t),i):eq(e.id,t),c=o.db.select().from(e).where(a).limit(1).get()??void 0;if(!c){let l=or(eq(e.thread_id,t),and(isNull(e.thread_id),like(e.command,`%--thread=${t}%`))),u=i?and(l,i):l;c=o.db.select().from(e).where(u).orderBy(desc(e.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new _("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(t,n){let s=this.resolveDbPaths(),r=new Set,o=[];for(let i of s){if(!existsSync(i))continue;let a=b(i);try{let c=n?and(eq(e.parent_task_id,t),eq(e.workspace_id,n)):eq(e.parent_task_id,t),l=a.db.select().from(e).where(c).orderBy(asc(e.started_at)).all();for(let u of l)r.has(u.id)||(r.add(u.id),o.push(u));}catch(c){throw new _("DB_ERROR","Failed to find child tasks",c)}finally{a.close();}}return o}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(t?sql`
|
|
@@ -255,7 +255,7 @@ ${s.join(`
|
|
|
255
255
|
FROM ${e}
|
|
256
256
|
${o}
|
|
257
257
|
ORDER BY ${e.started_at} ASC
|
|
258
|
-
`).map(a=>({threadId:a.thread_id,agentId:a.agent_id,startedAt:a.started_at,status:a.status,error:a.error,exitCode:a.exit_code}))}catch(o){throw new _("DB_ERROR","Failed to get tasks for report",o)}finally{r.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(e.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&s.push(inArray(e.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&s.push(inArray(e.status,t.statuses)),t.from&&s.push(gte(e.started_at,t.from)),t.to&&s.push(lt(e.started_at,t.to));let r=s.length>0?and(...s):void 0,o=(t.order??"DESC")==="ASC"?asc(e.started_at):desc(e.started_at),i={id:e.id,agent_id:e.agent_id,status:e.status,prompt:e.prompt,started_at:e.started_at,completed_at:e.completed_at,thread_id:e.thread_id};return t.limit?n.db.select(i).from(e).where(r).orderBy(o).limit(t.limit).all():n.db.select(i).from(e).where(r).orderBy(o).all()}catch(s){throw new _("DB_ERROR","Failed to find task evidence",s)}finally{n.close();}}findThreadChains(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let s=t.maxThreads??8,r=t.maxTurnsPerThread??4,o=[isNotNull(e.thread_id),isNull(e.parent_task_id),isNull(e.caller_agent_id),or(isNull(e.platform),ne(e.platform,"workflow")),or(isNull(e.metadata),notLike(e.metadata,'%"kind":"workflow_card"%')),or(isNull(e.metadata),notLike(e.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&o.push(eq(e.workspace_id,t.workspaceId)),t.from&&o.push(gte(e.started_at,t.from)),t.to&&o.push(lt(e.started_at,t.to));let i=n.db.select({id:e.id,agent_id:e.agent_id,status:e.status,prompt:e.prompt,started_at:e.started_at,completed_at:e.completed_at,thread_id:e.thread_id}).from(e).where(and(...o)).orderBy(asc(e.started_at),asc(e.id)).all(),a=new Map;for(let l of i){if(!l.thread_id)continue;let u={id:l.id,agentId:l.agent_id,status:l.status,prompt:l.prompt,startedAt:l.started_at,completedAt:l.completed_at},h=a.get(l.thread_id);h?h.push(u):a.set(l.thread_id,[u]);}let c=[];for(let[l,u]of a){let h=u.filter(g=>g.agentId===t.targetAgentId).length;h<2||c.push({threadId:l,targetAgentTurnCount:h,turns:u});}return c.sort((l,u)=>{let h=l.turns[l.turns.length-1].startedAt,g=u.turns[u.turns.length-1].startedAt;return h<g?1:h>g?-1:0}),c.slice(0,s).map(l=>({threadId:l.threadId,targetAgentTurnCount:l.targetAgentTurnCount,turns:l.turns.slice(-r)}))}catch(s){throw new _("DB_ERROR","Failed to find thread chains",s)}finally{n.close();}}};var At=class extends j{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=join(t?.dbRoot??homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let n=new
|
|
258
|
+
`).map(a=>({threadId:a.thread_id,agentId:a.agent_id,startedAt:a.started_at,status:a.status,error:a.error,exitCode:a.exit_code}))}catch(o){throw new _("DB_ERROR","Failed to get tasks for report",o)}finally{r.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(e.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&s.push(inArray(e.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&s.push(inArray(e.status,t.statuses)),t.from&&s.push(gte(e.started_at,t.from)),t.to&&s.push(lt(e.started_at,t.to));let r=s.length>0?and(...s):void 0,o=(t.order??"DESC")==="ASC"?asc(e.started_at):desc(e.started_at),i={id:e.id,agent_id:e.agent_id,status:e.status,prompt:e.prompt,started_at:e.started_at,completed_at:e.completed_at,thread_id:e.thread_id};return t.limit?n.db.select(i).from(e).where(r).orderBy(o).limit(t.limit).all():n.db.select(i).from(e).where(r).orderBy(o).all()}catch(s){throw new _("DB_ERROR","Failed to find task evidence",s)}finally{n.close();}}findThreadChains(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let s=t.maxThreads??8,r=t.maxTurnsPerThread??4,o=[isNotNull(e.thread_id),isNull(e.parent_task_id),isNull(e.caller_agent_id),or(isNull(e.platform),ne(e.platform,"workflow")),or(isNull(e.metadata),notLike(e.metadata,'%"kind":"workflow_card"%')),or(isNull(e.metadata),notLike(e.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&o.push(eq(e.workspace_id,t.workspaceId)),t.from&&o.push(gte(e.started_at,t.from)),t.to&&o.push(lt(e.started_at,t.to));let i=n.db.select({id:e.id,agent_id:e.agent_id,status:e.status,prompt:e.prompt,started_at:e.started_at,completed_at:e.completed_at,thread_id:e.thread_id}).from(e).where(and(...o)).orderBy(asc(e.started_at),asc(e.id)).all(),a=new Map;for(let l of i){if(!l.thread_id)continue;let u={id:l.id,agentId:l.agent_id,status:l.status,prompt:l.prompt,startedAt:l.started_at,completedAt:l.completed_at},h=a.get(l.thread_id);h?h.push(u):a.set(l.thread_id,[u]);}let c=[];for(let[l,u]of a){let h=u.filter(g=>g.agentId===t.targetAgentId).length;h<2||c.push({threadId:l,targetAgentTurnCount:h,turns:u});}return c.sort((l,u)=>{let h=l.turns[l.turns.length-1].startedAt,g=u.turns[u.turns.length-1].startedAt;return h<g?1:h>g?-1:0}),c.slice(0,s).map(l=>({threadId:l.threadId,targetAgentTurnCount:l.targetAgentTurnCount,turns:l.turns.slice(-r)}))}catch(s){throw new _("DB_ERROR","Failed to find thread chains",s)}finally{n.close();}}};var At=class extends j{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=join(t?.dbRoot??homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let n=new mt({dbPath:this.dbPath}),s=process.cwd(),o=existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))?$t(s):null,i=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let c=a.callerAgentId??null,l=a.parentTaskId??null,u=a.rootTraceId??a.traceId,h=a.metadata?JSON.stringify(a.metadata):JSON.stringify({provider:a.provider??"cli/claude"});n.startTask({id:a.traceId,agentId:a.agentRef.replace(/^@/,""),prompt:a.message,mode:a.mode,status:"running",pid:a.pid??null,startedAt:a.timestamp.toISOString(),crewxVersion:this.version,platform:a.platform??"cli",model:a.model??null,renderedPrompt:a.renderedPrompt??null,command:i,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??o,callerAgentId:c,parentTaskId:l,traceId:u,metadata:h,threadId:a.threadId??null});}catch{}}),t.on("task:output",a=>{try{n.appendLog(a.traceId,{timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output});}catch{}}),t.on("task:end",a=>{try{let c=typeof a.metadata?.runEpoch=="number"?a.metadata.runEpoch:null,l=a.error?JSON.stringify({code:a.error.code,message:a.error.message,...a.error.providerCode?{providerCode:a.error.providerCode}:{}}):null;n.finishTask({id:a.traceId,status:a.error?"failed":"success",result:a.result??null,error:l,completedAt:a.timestamp.toISOString(),durationMs:a.durationMs,exitCode:a.exitCode??null,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cachedInputTokens:a.cachedInputTokens??0,costUsd:a.costUsd??0,model:a.model??null,runEpoch:c});}catch{}}));}detach(t){this.unsubs.forEach(n=>n()),this.unsubs=[];}};var ft=class extends nt{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new _("NOT_FOUND","Database not found");let s=b(n);if(t)try{ct(s.db,n);}catch(r){throw s.close(),r}return s}validateWorkspaceId(t,n){return t.db.select({id:st.id}).from(st).where(eq(st.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
|
|
259
259
|
SELECT 1 FROM tasks parent
|
|
260
260
|
WHERE parent.id = ${t}.parent_task_id
|
|
261
261
|
AND parent.thread_id = ${t}.thread_id
|
|
@@ -314,5 +314,5 @@ ${s.join(`
|
|
|
314
314
|
`),l},{behavior:"immediate"})}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save user message",o)}finally{r.close();}}saveAssistantMessage(t,n,s){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.update(p).set({last_message:n,updated_at:o}).where(eq(p.id,t)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save assistant message",o)}finally{r.close();}}updateThread(t,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};n.title!==void 0&&(r.title=n.title,r.title_locked=1),n.titleLocked!==void 0&&(r.title_locked=n.titleLocked?1:0),s.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to update thread",r)}finally{s.close();}}togglePin(t,n){let s=this.openHandle(true);try{let r=n?and(eq(p.id,t),eq(p.workspace_id,n)):eq(p.id,t),o=s.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!o)return null;let i=o.pinned?0:1,a=o.metadata?JSON.parse(o.metadata):{};if(i){let c=n?and(eq(p.pinned,1),eq(p.workspace_id,n)):eq(p.pinned,1),l=s.db.select({metadata:p.metadata}).from(p).where(c).all(),u=null;for(let h of l){let g=h.metadata?JSON.parse(h.metadata):{};typeof g.pinOrder=="number"&&(u===null||g.pinOrder<u)&&(u=g.pinOrder);}a.pinOrder=u===null?0:u-1;}else delete a.pinOrder;return s.db.update(p).set({pinned:i,metadata:Object.keys(a).length>0?JSON.stringify(a):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to toggle pin",r)}finally{s.close();}}reorderPins(t,n){let s=this.openHandle(true);try{for(let r=0;r<t.length;r++){let o=n?and(eq(p.id,t[r]),eq(p.workspace_id,n)):eq(p.id,t[r]),i=s.db.select({metadata:p.metadata}).from(p).where(o).get();if(!i)continue;let a=i.metadata?JSON.parse(i.metadata):{};a.pinOrder=r+1,s.db.update(p).set({metadata:JSON.stringify(a)}).where(o).run();}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to reorder pins",r)}finally{s.close();}}toggleStar(t,n){let s=this.openHandle(true);try{let r=n?and(eq(p.id,t),eq(p.workspace_id,n)):eq(p.id,t),o=s.db.select({starred:p.starred}).from(p).where(r).get();if(!o)return null;let i=o.starred?0:1;return s.db.update(p).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to toggle star",r)}finally{s.close();}}resolveOverdriveForRequest(t,n,s,r){let i=this.openHandle(true);try{let a=n?and(eq(p.id,t),eq(p.workspace_id,n)):eq(p.id,t);return i.db.transaction(l=>{let u=l.select({metadata:p.metadata}).from(p).where(a).get();if(!u)return null;let h=u.metadata?JSON.parse(u.metadata):{},g=h.overdrive??{},y=r?.defaultTurns??g.defaultTurns??3,C=r?.updatedBy??"ui",N=new Date().toISOString(),$,M,B,rt;switch(s){case "enable-count":{let ot=r?.turns??y,it=r?.consumeCurrent?Math.max(ot-1,0):ot;$=it>0?"count":"off",M=it,B=!0,rt="count";break}case "enable-latch":{$="latch",M=0,B=!0,rt="latch";break}case "disable":{$="off",M=0,B=!1;break}default:{let ot=g.state??"off",it=typeof g.remaining=="number"?g.remaining:0;if(ot==="count"&&it>0){let Nt=it-1;Nt<=0?($="off",M=0):($="count",M=Nt),B=!0,rt="count";}else ot==="latch"?($="latch",M=0,B=!0,rt="latch"):($="off",M=0,B=!1);break}}return h.overdrive={state:$,remaining:M,defaultTurns:y,updatedAt:N,updatedBy:C},l.update(p).set({metadata:JSON.stringify(h),updated_at:N}).where(a).run(),{applied:B,appliedMode:rt,state:$,remaining:M}},{behavior:"immediate"})}catch(a){throw a instanceof _?a:new _("DB_ERROR","Failed to resolve overdrive",a)}finally{i.close();}}};function tn(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
315
315
|
`).filter(r=>!(r.startsWith("Loaded ")&&r.includes("layouts from")||r.includes("[dotenv@")||r.includes("[Nest]")&&r.includes("DEBUG")||r.startsWith("Registered custom layout:")||r.startsWith("Updated custom layout:"))).join(`
|
|
316
316
|
`).trim()}function en(d){if(!d)return "";let t=d;try{let n=JSON.parse(t);Array.isArray(n)?t=n.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
|
|
317
|
-
`):n&&typeof n=="object"&&n.result!==void 0&&(t=n.result||"");}catch{t=tn(t);}return t}var kt=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new
|
|
317
|
+
`):n&&typeof n=="object"&&n.result!==void 0&&(t=n.result||"");}catch{t=tn(t);}return t}var kt=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new ft({dbPath:this.dbPath})}updateThread(t,n){this.getThreadRepo().updateThread(t,{title:n.title});}async ensureThread(t,n,s){let r=this.getThreadRepo(),o=r.findThreadById(t);if(o){if(o.platform!==n)throw new Error(`Thread '${t}' already exists with platform '${o.platform}' \u2014 cannot change to '${n}' (platform is immutable)`);return {created:false}}return r.ensureThread(t,n,s),{created:true}}async fetchHistory(t,n){let s=n?.limit??100,r=this.getThreadRepo(),o=r.findThreadById(t),i=r.findTopLevelTasks(t,void 0,s),a=new Set(["queued","cancelled"]);i=i.filter(u=>(!u.status||!a.has(u.status))&&(!n?.currentTraceId||u.trace_id!==n.currentTraceId));let c=o?.platform??"cli",l=this.rowsToMessages(i);return {threadId:t,platform:c,messages:l,metadata:{title:o?.title??void 0,firstMessage:o?.first_message??void 0,lastMessage:o?.last_message??void 0,messageCount:o?.message_count??0,updatedAt:o?.updated_at?new Date(o.updated_at).getTime():void 0}}}async saveUserMessage(t,n,s,r){let{firstMessage:o}=this.getThreadRepo().saveUserMessage(t,n);return {id:t,firstMessage:o}}async saveAssistantMessage(t,n,s,r){return this.getThreadRepo().saveAssistantMessage(t,n),{id:t}}close(){}normalizeStatus(t){if(t&&!["success","completed","done"].includes(t)){if(["failed","error"].includes(t))return "failed";if(t==="running")return "running"}}rowsToMessages(t){let n=[];for(let s of t){s.prompt&&n.push({id:`${s.id}-user`,text:s.prompt,isAssistant:false,timestamp:new Date(s.started_at).getTime(),metadata:{caller_agent_id:s.caller_agent_id}});let r=en(s.result),o=this.normalizeStatus(s.status);if(r||o==="running"||o==="failed"){let i={agent_id:s.agent_id,task_id:s.id};o&&(i.status=o),o==="failed"&&s.error&&(i.reason=s.error.split(`
|
|
318
318
|
`)[0].slice(0,200)),n.push({id:`${s.id}-assistant`,text:r,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:i});}}return n}};var Ct=class extends j{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new kt(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,n,s,r){}async afterAssistantMessage(t,n,s){}attach(t){this.unsubStart=t.on("task:start",async n=>{if(!n.threadId)return;let s=n.platform??"cli";try{let r=await this._provider.ensureThread(n.threadId,s,n.workspaceId),o=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,o.id,r.created||o.firstMessage,n);}catch{}}),this.unsubEnd=t.on("task:end",async n=>{if(!n.result)return;let s=n.metadata?.threadId;if(!s)return;let r=n.agentRef?.replace(/^@/,"")??"";try{let{id:o}=await this._provider.saveAssistantMessage(s,n.result,r);await this.afterAssistantMessage(s,o,n);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{Ct as ConversationPlugin,Et as FileLoggerPlugin,At as SqliteTracingPlugin};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import*as Z from'path';import Z__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import ge,{existsSync,mkdirSync,readFileSync}from'fs';import Ze from'os';import {sql,and,eq,ne as ne$1,isNull,desc,isNotNull,lt,or,notLike,like,asc,inArray,gte,lte}from'drizzle-orm';import {randomUUID,createHash,randomBytes}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var Tt=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var Xe=()=>fileURLToPath(import.meta.url),Je=()=>Z__default.dirname(Xe()),R=Je();var T=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Ze.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,n,e){super(n),this.name="RepositoryError",this.code=t,this.cause=e,Object.setPrototypeOf(this,new.target.prototype);}};function w(a){let t=Tt("better-sqlite3"),{drizzle:n}=Tt("drizzle-orm/better-sqlite3"),e=new t(a);return e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA busy_timeout = 5000"),e.exec("PRAGMA foreign_keys = ON"),e.exec("PRAGMA analysis_limit = 400"),e.exec("PRAGMA optimize"),{db:n(e),runRaw:(r,s=[])=>e.prepare(r).run(...s),close:()=>e.close()}}var oe=new Set,tn={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 Bt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function en(a,t){if(t>0||!Bt(a,"tasks"))return;let n=a.all("PRAGMA table_info(tasks)"),e=new Set(n.map(r=>r.name));for(let[r,s]of Object.entries(tn))e.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var nn={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function rn(a,t,n){if(!Bt(a,"__drizzle_migrations")||!Bt(a,"tasks"))return;let e=a.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(e.map(i=>i.hash)),s=JSON.parse(readFileSync(Z__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=nn[i.tag];if(!l)continue;let u=Z__default.join(t,`${i.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),p=createHash("sha256").update(c).digest("hex");if(r.has(p))continue;let f=a.all("PRAGMA table_info(tasks)"),h=new Set(f.map(x=>x.name));for(let[x,L]of Object.entries(l))h.has(x)||(a.run(`ALTER TABLE tasks ADD COLUMN ${x} ${L}`),h.add(x));}}function on(a,t,n){let e=a.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(e.map(i=>i.hash)),s=JSON.parse(readFileSync(Z__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=Z__default.join(t,`${i.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,f=[],h;for(;(h=p.exec(u))!==null;)f.push({table:h[1],column:h[2]});if(f.length===0||!u.split(/-->\s*statement-breakpoint/).map(B=>B.trim()).filter(Boolean).every(B=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(B)))continue;f.every(({table:B,column:H})=>a.all(`PRAGMA table_info("${B}")`).some(Y=>Y.name===H))&&a.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function ht(a){let{migrate:t}=Tt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=Tt("drizzle-orm"),e=[Z__default.join(R,"../migrations"),Z__default.join(R,"migrations"),Z__default.join(R,"../../../../drizzle/migrations"),Z__default.join(process.cwd(),"drizzle/migrations")],r=e.find(c=>existsSync(Z__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
|
|
2
2
|
${e.join(`
|
|
3
|
-
`)}`);let s=a.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=a.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),en(a,i),s?.cnt&&(on(a,r,n),rn(a,r,n)),t(a,{migrationsFolder:r});let u=(a.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function O(a,t){oe.has(t)||(ht(a),oe.add(t));}var m=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var _=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>m.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at),idx_threads_title:index("idx_threads_title").on(a.title)}));var et=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>et.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},a=>({idx_spans_task_id:index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(a.parent_span_id)}));var V=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var W=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:unique().on(a.thread_id,a.seq)}));var mt=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));var v=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));var F=sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},a=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));var k=sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},a=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(a.workspace_id,sql`${a.created_at} DESC`)})),C=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},a=>({pk:primaryKey({columns:[a.notification_id,a.user_id]})}));var E=sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},a=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(a.workspace_id,a.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(a.workspace_id,a.created_at)}));function Ht(a){let t=Z.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(n,e)=>`${e.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function fe(a){let t=Ht(a);return createHash("sha256").update(t).digest("hex")}function Ct(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var qt=class extends T{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{ht(e.db);}catch(r){throw e.close(),r}return e}resolveSlug(t,n,e){let r=Ct(basename(e)),i=`${Ct(basename(dirname(e)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:m.id}).from(m).where(and(eq(m.slug,c),ne$1(m.id,n))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let p=`${i}-${c}`;if(!u(p))return p}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let n=t.db.select({id:m.id,slug:m.slug}).from(m).all(),e=0;for(let r of n)if(r.slug.includes("/")){let s=Ct(r.slug.replace(/\//g,"-"));t.db.update(m).set({slug:s,updated_at:new Date().toISOString()}).where(eq(m.id,r.id)).run(),e+=1;}return {updated:e,checked:n.length}}catch(n){throw new d("DB_ERROR","Failed to normalize legacy slugs",n)}finally{t.close();}}ensureRow(t,n){let{id:e,slug:r,name:s,workspacePath:i}=n,l=new Date().toISOString();t.insert(m).values({id:e,slug:r,name:s,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(m).set({workspace_path:i,updated_at:l}).where(and(eq(m.id,e),isNull(m.workspace_path))).run();}registerWorkspace(t){let n=Ht(t),e=this.openHandle(true);try{let r=fe(n),s=basename(n),i=this.resolveSlug(e.db,r,n);return this.ensureRow(e.db,{id:r,slug:i,name:s,workspacePath:n}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{e.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let e=t.isActive!==void 0?eq(m.is_active,t.isActive?1:0):void 0,r=n.db.select({count:sql`count(*)`}).from(m).where(e).get();return {rows:n.db.select().from(m).where(e).orderBy(desc(m.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(e){throw new d("DB_ERROR","Failed to list projects",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(m).where(eq(m.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find workspace",e)}finally{n.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(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(e){throw new d("DB_ERROR","Failed to find agents by project",e)}finally{n.close();}}findThreadsByProject(t,n){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let r=e.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:e.db.all(sql`SELECT t.*,
|
|
3
|
+
`)}`);let s=a.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=a.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),en(a,i),s?.cnt&&(on(a,r,n),rn(a,r,n)),t(a,{migrationsFolder:r});let u=(a.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function O(a,t){oe.has(t)||(ht(a),oe.add(t));}var m=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var _=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>m.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at),idx_threads_title:index("idx_threads_title").on(a.title)}));var et=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>et.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},a=>({idx_spans_task_id:index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(a.parent_span_id)}));var V=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var W=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:unique().on(a.thread_id,a.seq)}));var mt=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));var v=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));var F=sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},a=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));var k=sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},a=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(a.workspace_id,sql`${a.created_at} DESC`)})),P=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},a=>({pk:primaryKey({columns:[a.notification_id,a.user_id]})}));var E=sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},a=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(a.workspace_id,a.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(a.workspace_id,a.created_at)}));function Ht(a){let t=Z.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(n,e)=>`${e.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function fe(a){let t=Ht(a);return createHash("sha256").update(t).digest("hex")}function Pt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var qt=class extends T{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{ht(e.db);}catch(r){throw e.close(),r}return e}resolveSlug(t,n,e){let r=Pt(basename(e)),i=`${Pt(basename(dirname(e)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:m.id}).from(m).where(and(eq(m.slug,c),ne$1(m.id,n))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let p=`${i}-${c}`;if(!u(p))return p}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let n=t.db.select({id:m.id,slug:m.slug}).from(m).all(),e=0;for(let r of n)if(r.slug.includes("/")){let s=Pt(r.slug.replace(/\//g,"-"));t.db.update(m).set({slug:s,updated_at:new Date().toISOString()}).where(eq(m.id,r.id)).run(),e+=1;}return {updated:e,checked:n.length}}catch(n){throw new d("DB_ERROR","Failed to normalize legacy slugs",n)}finally{t.close();}}ensureRow(t,n){let{id:e,slug:r,name:s,workspacePath:i}=n,l=new Date().toISOString();t.insert(m).values({id:e,slug:r,name:s,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(m).set({workspace_path:i,updated_at:l}).where(and(eq(m.id,e),isNull(m.workspace_path))).run();}registerWorkspace(t){let n=Ht(t),e=this.openHandle(true);try{let r=fe(n),s=basename(n),i=this.resolveSlug(e.db,r,n);return this.ensureRow(e.db,{id:r,slug:i,name:s,workspacePath:n}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{e.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let e=t.isActive!==void 0?eq(m.is_active,t.isActive?1:0):void 0,r=n.db.select({count:sql`count(*)`}).from(m).where(e).get();return {rows:n.db.select().from(m).where(e).orderBy(desc(m.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(e){throw new d("DB_ERROR","Failed to list projects",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(m).where(eq(m.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find workspace",e)}finally{n.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(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(e){throw new d("DB_ERROR","Failed to find agents by project",e)}finally{n.close();}}findThreadsByProject(t,n){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let r=e.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:e.db.all(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}
|
|
@@ -306,4 +306,4 @@ ${e.join(`
|
|
|
306
306
|
message_count = message_count + 1,
|
|
307
307
|
updated_at = ${s}
|
|
308
308
|
WHERE id = ${t}
|
|
309
|
-
`),c},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(_).set({last_message:n,updated_at:s}).where(eq(_.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,n){if(!this.dbExists())return;let e=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};n.title!==void 0&&(r.title=n.title,r.title_locked=1),n.titleLocked!==void 0&&(r.title_locked=n.titleLocked?1:0),e.db.update(_).set(r).where(eq(_.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{e.close();}}togglePin(t,n){let e=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),s=e.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!s)return null;let i=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(i){let u=n?and(eq(_.pinned,1),eq(_.workspace_id,n)):eq(_.pinned,1),c=e.db.select({metadata:_.metadata}).from(_).where(u).all(),p=null;for(let f of c){let h=f.metadata?JSON.parse(f.metadata):{};typeof h.pinOrder=="number"&&(p===null||h.pinOrder<p)&&(p=h.pinOrder);}l.pinOrder=p===null?0:p-1;}else delete l.pinOrder;return e.db.update(_).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{e.close();}}reorderPins(t,n){let e=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=n?and(eq(_.id,t[r]),eq(_.workspace_id,n)):eq(_.id,t[r]),i=e.db.select({metadata:_.metadata}).from(_).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,e.db.update(_).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{e.close();}}toggleStar(t,n){let e=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),s=e.db.select({starred:_.starred}).from(_).where(r).get();if(!s)return null;let i=s.starred?0:1;return e.db.update(_).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{e.close();}}resolveOverdriveForRequest(t,n,e,r){let i=this.openHandle(true);try{let l=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t);return i.db.transaction(c=>{let p=c.select({metadata:_.metadata}).from(_).where(l).get();if(!p)return null;let f=p.metadata?JSON.parse(p.metadata):{},h=f.overdrive??{},x=r?.defaultTurns??h.defaultTurns??3,L=r?.updatedBy??"ui",B=new Date().toISOString(),H,N,Y,kt;switch(e){case "enable-count":{let bt=r?.turns??x,Rt=r?.consumeCurrent?Math.max(bt-1,0):bt;H=Rt>0?"count":"off",N=Rt,Y=!0,kt="count";break}case "enable-latch":{H="latch",N=0,Y=!0,kt="latch";break}case "disable":{H="off",N=0,Y=!1;break}default:{let bt=h.state??"off",Rt=typeof h.remaining=="number"?h.remaining:0;if(bt==="count"&&Rt>0){let re=Rt-1;re<=0?(H="off",N=0):(H="count",N=re),Y=!0,kt="count";}else bt==="latch"?(H="latch",N=0,Y=!0,kt="latch"):(H="off",N=0,Y=!1);break}}return f.overdrive={state:H,remaining:N,defaultTurns:x,updatedAt:B,updatedBy:L},c.update(_).set({metadata:JSON.stringify(f),updated_at:B}).where(l).run(),{applied:Y,appliedMode:kt,state:H,remaining:N}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Yt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}insertSpan(t){let n=this.openHandle(true);try{n.db.insert(et).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert span",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(et).where(eq(et.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find spans by task id",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(et).where(eq(et.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find span by id",e)}finally{n.close();}}};var Xt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}insertToolCall(t){let n=this.openHandle(true);try{n.db.insert(V).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert tool call",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(V).where(eq(V.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find tool calls by task id",e)}finally{n.close();}}aggregateByName(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select({toolName:V.tool_name,count:sql`count(*)`}).from(V).where(eq(V.task_id,t)).groupBy(V.tool_name).all().map(e=>({toolName:e.toolName,count:e.count}))}catch(e){throw new d("DB_ERROR","Failed to aggregate tool calls by name",e)}finally{n.close();}}};var Jt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}ensureThreadExists(t,n){if(!t.db.select({id:_.id}).from(_).where(eq(_.id,n)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${n}`)}findByThreadId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return this.ensureThreadExists(n,t),n.db.select().from(W).where(eq(W.thread_id,t)).orderBy(asc(W.seq)).all()}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to find boxes by thread id",e)}finally{n.close();}}findById(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(W).where(and(eq(W.id,n),eq(W.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{e.close();}}insert(t){let n=this.openHandle(true);try{this.ensureThreadExists(n,t.threadId);try{n.db.insert(W).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 e=n.db.select().from(W).where(eq(W.id,t.id)).limit(1).get();if(!e)throw new d("DB_ERROR","Insert did not return a row");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert thread box",e)}finally{n.close();}}};var Vt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}bulkInsert(t){if(t.length===0)return;let n=this.openHandle(true);try{let e=new Date().toISOString();n.db.transaction(r=>{for(let s of t)r.insert(mt).values({id:randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:e,metadata:s.metadata??null}).run();});}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to bulk insert request logs",e)}finally{n.close();}}findRecent(t=100){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(mt).orderBy(desc(mt.timestamp)).limit(t).all()}catch(e){throw new d("DB_ERROR","Failed to find recent request logs",e)}finally{n.close();}}};function Pe(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Qt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}upsert(t){let n=this.openHandle(true);try{let e=Pe(t.bucketStartMs),r=t.accountRef??"default";n.db.insert(v).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:e,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[v.provider,v.account_ref,v.limit_window,v.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to upsert usage limit snapshot",e)}finally{n.close();}}getTrends(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=n.db.select({provider:v.provider,bucket_start:v.bucket_start,used_percent:v.used_percent,remaining_percent:v.remaining_percent,resets_at:v.resets_at}).from(v).where(and(eq(v.limit_window,t.window),gte(v.bucket_start,t.fromIso),lte(v.bucket_start,t.toIso))).orderBy(asc(v.bucket_start)).all(),r=new Map;for(let s of e)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,i])=>({provider:s,points:i}))}catch(e){throw new d("DB_ERROR","Failed to get usage limit trends",e)}finally{n.close();}}};var Zt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}publish(t){let n=this.openHandle(true);try{n.db.insert(F).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[F.workspace_id,F.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let e=n.db.select().from(F).where(and(eq(F.workspace_id,t.workspaceId),eq(F.month,t.month))).limit(1).get();if(!e)throw new d("DB_ERROR","Failed to read back published usage report");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to publish usage report",e)}finally{n.close();}}findByMonth(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(F).where(and(eq(F.workspace_id,t),eq(F.month,n))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{e.close();}}listByWorkspace(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(F).where(eq(F.workspace_id,t)).orderBy(desc(F.month)).all()}catch(e){throw new d("DB_ERROR","Failed to list usage reports",e)}finally{n.close();}}};var Be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Or(a){let t=randomBytes(a*2),n="";for(let e=0;e<t.length&&n.length<a;e++){let r=t[e];r<248&&(n+=Be[r%62]);}for(;n.length<a;)n+=Be[randomBytes(1)[0]%62];return n}function $t(a){return `${a}_${Or(8)}`}var ze=500,qe=50,te=class extends T{dbPath;cap;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db")),this.cap=t.cap??ze;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=$t("ntf"),r=new Date().toISOString();return n.db.insert(k).values({id:e,workspace_id:t.workspaceId,agent_id:t.agentId??null,task_id:t.taskId??null,thread_id:t.threadId??null,source:t.source??"agent",level:t.level??"info",title:t.title,body:t.body??null,target_user_id:t.targetUserId??null,created_at:r,metadata:t.metadata??null}).run(),this.enforceCap(n,t.workspaceId),{id:e}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create notification",e)}finally{n.close();}}enforceCap(t,n){let s=(t.db.select({count:sql`count(*)`}).from(k).where(eq(k.workspace_id,n)).get()?.count??0)-this.cap;if(s<=0)return;let l=t.db.select({id:k.id}).from(k).innerJoin(C,eq(C.notification_id,k.id)).where(eq(k.workspace_id,n)).groupBy(k.id).orderBy(asc(k.created_at)).limit(s).all().map(u=>u.id);l.length!==0&&(t.db.delete(C).where(inArray(C.notification_id,l)).run(),t.db.delete(k).where(inArray(k.id,l)).run());}list(t){if(!this.dbExists())return [];let n=t.limit??qe,e=this.openHandle(false);try{return e.db.select({id:k.id,workspace_id:k.workspace_id,agent_id:k.agent_id,task_id:k.task_id,thread_id:k.thread_id,source:k.source,level:k.level,title:k.title,body:k.body,target_user_id:k.target_user_id,created_at:k.created_at,metadata:k.metadata,read_at:C.read_at}).from(k).leftJoin(C,and(eq(C.notification_id,k.id),eq(C.user_id,t.userId))).where(eq(k.workspace_id,t.workspaceId)).orderBy(desc(k.created_at)).limit(n).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(r){throw new d("DB_ERROR","Failed to list notifications",r)}finally{e.close();}}unreadCount(t){if(!this.dbExists())return 0;let n=this.openHandle(false);try{return n.db.select({count:sql`count(*)`}).from(k).leftJoin(C,and(eq(C.notification_id,k.id),eq(C.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(C.notification_id))).get()?.count??0}catch(e){throw new d("DB_ERROR","Failed to count unread notifications",e)}finally{n.close();}}markRead(t){let n=this.openHandle(true);try{if(!n.db.select({id:k.id}).from(k).where(and(eq(k.id,t.notificationId),eq(k.workspace_id,t.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return n.db.insert(C).values({notification_id:t.notificationId,user_id:t.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark notification read",e)}finally{n.close();}}markAllRead(t){let n=this.openHandle(true);try{let e=n.db.select({id:k.id}).from(k).leftJoin(C,and(eq(C.notification_id,k.id),eq(C.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(C.notification_id))).all();if(e.length===0)return 0;let r=new Date().toISOString();return n.db.transaction(s=>{for(let i of e)s.insert(C).values({notification_id:i.id,user_id:t.userId,read_at:r}).onConflictDoNothing().run();}),e.length}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark all notifications read",e)}finally{n.close();}}};var Ke=50,ne=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=new Date().toISOString(),r=[],s=t.map(i=>{let l=$t("sug");return r.push(l),{id:l,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:e,updated_at:e}});return s.length>0&&n.db.insert(E).values(s).run(),{ids:r}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create agent suggestions",e)}finally{n.close();}}findLatestSet(t,n){if(!this.dbExists())return [];let e=this.openHandle(false);try{let r=e.db.select({task_id:E.task_id}).from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n))).orderBy(desc(E.created_at)).limit(1).get();if(!r)return [];let s=r.task_id===null?isNull(E.task_id):eq(E.task_id,r.task_id);return e.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),s)).orderBy(asc(E.created_at)).all()}catch(r){throw new d("DB_ERROR","Failed to find latest agent suggestion set",r)}finally{e.close();}}findSetByTaskId(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),eq(E.task_id,e))).orderBy(asc(E.created_at)).all()}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{r.close();}}findById(t,n,e){if(!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),eq(E.id,e))).get()??null}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion by id",s)}finally{r.close();}}updateStatus(t,n,e){let r=this.openHandle(true);try{let s={status:n,updated_at:new Date().toISOString()};return e!==void 0&&(s.applied_commit_sha=e),r.db.update(E).set(s).where(eq(E.id,t)).run().changes>0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update agent suggestion status",s)}finally{r.close();}}listByAgent(t,n,e=Ke){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n))).orderBy(desc(E.created_at)).limit(e).all()}catch(s){throw new d("DB_ERROR","Failed to list agent suggestions",s)}finally{r.close();}}findDismissed(t,n,e=20){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),eq(E.status,"dismissed"))).orderBy(desc(E.updated_at)).limit(e).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{r.close();}}};export{ne as AgentSuggestionRepository,T as BaseSqliteRepository,Ke as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,ze as DEFAULT_NOTIFICATION_CAP,qe as DEFAULT_NOTIFICATION_LIST_LIMIT,te as NotificationRepository,d as RepositoryError,Vt as RequestLogRepository,Yt as SpanRepository,Kt as TaskRepository,Jt as ThreadBoxRepository,Gt as ThreadRepository,Xt as ToolCallRepository,Qt as UsageLimitSnapshotRepository,Zt as UsageReportRepository,qt as WorkspaceRepository,Pe as calcBucketStart,w as openDrizzleDb,Fn as pushSchema,ht as runMigrations,O as runMigrationsOnce,o as tasks};
|
|
309
|
+
`),c},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(_).set({last_message:n,updated_at:s}).where(eq(_.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,n){if(!this.dbExists())return;let e=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};n.title!==void 0&&(r.title=n.title,r.title_locked=1),n.titleLocked!==void 0&&(r.title_locked=n.titleLocked?1:0),e.db.update(_).set(r).where(eq(_.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{e.close();}}togglePin(t,n){let e=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),s=e.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!s)return null;let i=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(i){let u=n?and(eq(_.pinned,1),eq(_.workspace_id,n)):eq(_.pinned,1),c=e.db.select({metadata:_.metadata}).from(_).where(u).all(),p=null;for(let f of c){let h=f.metadata?JSON.parse(f.metadata):{};typeof h.pinOrder=="number"&&(p===null||h.pinOrder<p)&&(p=h.pinOrder);}l.pinOrder=p===null?0:p-1;}else delete l.pinOrder;return e.db.update(_).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{e.close();}}reorderPins(t,n){let e=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=n?and(eq(_.id,t[r]),eq(_.workspace_id,n)):eq(_.id,t[r]),i=e.db.select({metadata:_.metadata}).from(_).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,e.db.update(_).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{e.close();}}toggleStar(t,n){let e=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),s=e.db.select({starred:_.starred}).from(_).where(r).get();if(!s)return null;let i=s.starred?0:1;return e.db.update(_).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{e.close();}}resolveOverdriveForRequest(t,n,e,r){let i=this.openHandle(true);try{let l=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t);return i.db.transaction(c=>{let p=c.select({metadata:_.metadata}).from(_).where(l).get();if(!p)return null;let f=p.metadata?JSON.parse(p.metadata):{},h=f.overdrive??{},x=r?.defaultTurns??h.defaultTurns??3,L=r?.updatedBy??"ui",B=new Date().toISOString(),H,N,Y,kt;switch(e){case "enable-count":{let bt=r?.turns??x,Rt=r?.consumeCurrent?Math.max(bt-1,0):bt;H=Rt>0?"count":"off",N=Rt,Y=!0,kt="count";break}case "enable-latch":{H="latch",N=0,Y=!0,kt="latch";break}case "disable":{H="off",N=0,Y=!1;break}default:{let bt=h.state??"off",Rt=typeof h.remaining=="number"?h.remaining:0;if(bt==="count"&&Rt>0){let re=Rt-1;re<=0?(H="off",N=0):(H="count",N=re),Y=!0,kt="count";}else bt==="latch"?(H="latch",N=0,Y=!0,kt="latch"):(H="off",N=0,Y=!1);break}}return f.overdrive={state:H,remaining:N,defaultTurns:x,updatedAt:B,updatedBy:L},c.update(_).set({metadata:JSON.stringify(f),updated_at:B}).where(l).run(),{applied:Y,appliedMode:kt,state:H,remaining:N}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Yt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}insertSpan(t){let n=this.openHandle(true);try{n.db.insert(et).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert span",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(et).where(eq(et.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find spans by task id",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(et).where(eq(et.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find span by id",e)}finally{n.close();}}};var Xt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}insertToolCall(t){let n=this.openHandle(true);try{n.db.insert(V).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert tool call",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(V).where(eq(V.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find tool calls by task id",e)}finally{n.close();}}aggregateByName(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select({toolName:V.tool_name,count:sql`count(*)`}).from(V).where(eq(V.task_id,t)).groupBy(V.tool_name).all().map(e=>({toolName:e.toolName,count:e.count}))}catch(e){throw new d("DB_ERROR","Failed to aggregate tool calls by name",e)}finally{n.close();}}};var Jt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}ensureThreadExists(t,n){if(!t.db.select({id:_.id}).from(_).where(eq(_.id,n)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${n}`)}findByThreadId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return this.ensureThreadExists(n,t),n.db.select().from(W).where(eq(W.thread_id,t)).orderBy(asc(W.seq)).all()}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to find boxes by thread id",e)}finally{n.close();}}findById(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(W).where(and(eq(W.id,n),eq(W.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{e.close();}}insert(t){let n=this.openHandle(true);try{this.ensureThreadExists(n,t.threadId);try{n.db.insert(W).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 e=n.db.select().from(W).where(eq(W.id,t.id)).limit(1).get();if(!e)throw new d("DB_ERROR","Insert did not return a row");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert thread box",e)}finally{n.close();}}};var Vt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}bulkInsert(t){if(t.length===0)return;let n=this.openHandle(true);try{let e=new Date().toISOString();n.db.transaction(r=>{for(let s of t)r.insert(mt).values({id:randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:e,metadata:s.metadata??null}).run();});}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to bulk insert request logs",e)}finally{n.close();}}findRecent(t=100){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(mt).orderBy(desc(mt.timestamp)).limit(t).all()}catch(e){throw new d("DB_ERROR","Failed to find recent request logs",e)}finally{n.close();}}};function Ce(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Qt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}upsert(t){let n=this.openHandle(true);try{let e=Ce(t.bucketStartMs),r=t.accountRef??"default";n.db.insert(v).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:e,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[v.provider,v.account_ref,v.limit_window,v.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to upsert usage limit snapshot",e)}finally{n.close();}}getTrends(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=n.db.select({provider:v.provider,bucket_start:v.bucket_start,used_percent:v.used_percent,remaining_percent:v.remaining_percent,resets_at:v.resets_at}).from(v).where(and(eq(v.limit_window,t.window),gte(v.bucket_start,t.fromIso),lte(v.bucket_start,t.toIso))).orderBy(asc(v.bucket_start)).all(),r=new Map;for(let s of e)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,i])=>({provider:s,points:i}))}catch(e){throw new d("DB_ERROR","Failed to get usage limit trends",e)}finally{n.close();}}};var Zt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}publish(t){let n=this.openHandle(true);try{n.db.insert(F).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[F.workspace_id,F.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let e=n.db.select().from(F).where(and(eq(F.workspace_id,t.workspaceId),eq(F.month,t.month))).limit(1).get();if(!e)throw new d("DB_ERROR","Failed to read back published usage report");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to publish usage report",e)}finally{n.close();}}findByMonth(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(F).where(and(eq(F.workspace_id,t),eq(F.month,n))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{e.close();}}listByWorkspace(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(F).where(eq(F.workspace_id,t)).orderBy(desc(F.month)).all()}catch(e){throw new d("DB_ERROR","Failed to list usage reports",e)}finally{n.close();}}};var Be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Or(a){let t=randomBytes(a*2),n="";for(let e=0;e<t.length&&n.length<a;e++){let r=t[e];r<248&&(n+=Be[r%62]);}for(;n.length<a;)n+=Be[randomBytes(1)[0]%62];return n}function $t(a){return `${a}_${Or(8)}`}var ze=500,qe=50,te=class extends T{dbPath;cap;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db")),this.cap=t.cap??ze;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=$t("ntf"),r=new Date().toISOString();return n.db.insert(k).values({id:e,workspace_id:t.workspaceId,agent_id:t.agentId??null,task_id:t.taskId??null,thread_id:t.threadId??null,source:t.source??"agent",level:t.level??"info",title:t.title,body:t.body??null,target_user_id:t.targetUserId??null,created_at:r,metadata:t.metadata??null}).run(),this.enforceCap(n,t.workspaceId),{id:e}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create notification",e)}finally{n.close();}}enforceCap(t,n){let s=(t.db.select({count:sql`count(*)`}).from(k).where(eq(k.workspace_id,n)).get()?.count??0)-this.cap;if(s<=0)return;let l=t.db.select({id:k.id}).from(k).innerJoin(P,eq(P.notification_id,k.id)).where(eq(k.workspace_id,n)).groupBy(k.id).orderBy(asc(k.created_at)).limit(s).all().map(u=>u.id);l.length!==0&&(t.db.delete(P).where(inArray(P.notification_id,l)).run(),t.db.delete(k).where(inArray(k.id,l)).run());}list(t){if(!this.dbExists())return [];let n=t.limit??qe,e=this.openHandle(false);try{return e.db.select({id:k.id,workspace_id:k.workspace_id,agent_id:k.agent_id,task_id:k.task_id,thread_id:k.thread_id,source:k.source,level:k.level,title:k.title,body:k.body,target_user_id:k.target_user_id,created_at:k.created_at,metadata:k.metadata,read_at:P.read_at}).from(k).leftJoin(P,and(eq(P.notification_id,k.id),eq(P.user_id,t.userId))).where(eq(k.workspace_id,t.workspaceId)).orderBy(desc(k.created_at)).limit(n).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(r){throw new d("DB_ERROR","Failed to list notifications",r)}finally{e.close();}}unreadCount(t){if(!this.dbExists())return 0;let n=this.openHandle(false);try{return n.db.select({count:sql`count(*)`}).from(k).leftJoin(P,and(eq(P.notification_id,k.id),eq(P.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(P.notification_id))).get()?.count??0}catch(e){throw new d("DB_ERROR","Failed to count unread notifications",e)}finally{n.close();}}markRead(t){let n=this.openHandle(true);try{if(!n.db.select({id:k.id}).from(k).where(and(eq(k.id,t.notificationId),eq(k.workspace_id,t.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return n.db.insert(P).values({notification_id:t.notificationId,user_id:t.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark notification read",e)}finally{n.close();}}markAllRead(t){let n=this.openHandle(true);try{let e=n.db.select({id:k.id}).from(k).leftJoin(P,and(eq(P.notification_id,k.id),eq(P.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(P.notification_id))).all();if(e.length===0)return 0;let r=new Date().toISOString();return n.db.transaction(s=>{for(let i of e)s.insert(P).values({notification_id:i.id,user_id:t.userId,read_at:r}).onConflictDoNothing().run();}),e.length}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark all notifications read",e)}finally{n.close();}}};var Ke=50,ne=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=new Date().toISOString(),r=[],s=t.map(i=>{let l=$t("sug");return r.push(l),{id:l,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:e,updated_at:e}});return s.length>0&&n.db.insert(E).values(s).run(),{ids:r}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create agent suggestions",e)}finally{n.close();}}findLatestSet(t,n){if(!this.dbExists())return [];let e=this.openHandle(false);try{let r=e.db.select({task_id:E.task_id}).from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n))).orderBy(desc(E.created_at)).limit(1).get();if(!r)return [];let s=r.task_id===null?isNull(E.task_id):eq(E.task_id,r.task_id);return e.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),s)).orderBy(asc(E.created_at)).all()}catch(r){throw new d("DB_ERROR","Failed to find latest agent suggestion set",r)}finally{e.close();}}findSetByTaskId(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),eq(E.task_id,e))).orderBy(asc(E.created_at)).all()}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{r.close();}}findById(t,n,e){if(!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),eq(E.id,e))).get()??null}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion by id",s)}finally{r.close();}}updateStatus(t,n,e){let r=this.openHandle(true);try{let s={status:n,updated_at:new Date().toISOString()};return e!==void 0&&(s.applied_commit_sha=e),r.db.update(E).set(s).where(eq(E.id,t)).run().changes>0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update agent suggestion status",s)}finally{r.close();}}listByAgent(t,n,e=Ke){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n))).orderBy(desc(E.created_at)).limit(e).all()}catch(s){throw new d("DB_ERROR","Failed to list agent suggestions",s)}finally{r.close();}}findDismissed(t,n,e=20){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),eq(E.status,"dismissed"))).orderBy(desc(E.updated_at)).limit(e).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{r.close();}}};export{ne as AgentSuggestionRepository,T as BaseSqliteRepository,Ke as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,ze as DEFAULT_NOTIFICATION_CAP,qe as DEFAULT_NOTIFICATION_LIST_LIMIT,te as NotificationRepository,d as RepositoryError,Vt as RequestLogRepository,Yt as SpanRepository,Kt as TaskRepository,Jt as ThreadBoxRepository,Gt as ThreadRepository,Xt as ToolCallRepository,Qt as UsageLimitSnapshotRepository,Zt as UsageReportRepository,qt as WorkspaceRepository,Ce as calcBucketStart,w as openDrizzleDb,Fn as pushSchema,ht as runMigrations,O as runMigrationsOnce,o as tasks};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function f(){let e=[];return {events:e,async log(t,o){e.push({event:t,payload:o});}}}function h(){let e={debug:[],info:[],warn:[],error:[]};return {entries:e,debug(t,o){e.debug.push({msg:t,meta:o});},info(t,o){e.info.push({msg:t,meta:o});},warn(t,o){e.warn.push({msg:t,meta:o});},error(t,o){e.error.push({msg:t,meta:o});}}}function T(){let e=200,t,o,n={},r={status(i){return e=i,r},set(i,a){return n[i]=a,r},send(i){return o=i,r},json(i){return t=i,r},end(){return r},getStatusCode:()=>e,getJsonBody:()=>t,getSentBody:()=>o,getHeaders:()=>({...n})};return r}function x(){let e=[];return {routes:e,registerRoute(o,n,r){e.push({path:o,handler:n,opts:r});},async simulate(o,n,r=Buffer.alloc(0),i={},a={},l={}){let p=e.find(m=>m.path===n);if(!p)return {status:404,body:{error:"Not found"},headers:{}};let g={method:o,url:n,headers:i,body:r,params:a,query:l},u=T();return await p.handler(g,u),{status:u.getStatusCode(),body:u.getJsonBody()??u.getSentBody(),headers:u.getHeaders()}}}}function y(e){let t=new Map,o=n=>n.startsWith(`${e}::`)?n:`${e}::${n}`;return {async get(n){let r=t.get(o(n));return r?r.value:void 0},async set(n,r){t.set(o(n),{value:r});},async delete(n){return t.delete(o(n))},async list(n){let r=n?o(n):`${e}::`,i=[];for(let a of t.keys())a.startsWith(r)&&i.push(a.slice(e.length+2));return i}}}function M(e){return y(e)}function P(){let e=new Map;return {blobs:e,async put(t,o,n){return e.set(t,{data:o,contentType:n}),t},async get(t){let o=e.get(t);return o?o.data:void 0},async delete(t){return e.delete(t)}}}function A(e){let t=e.instanceId??"mock-instance",o=f(),n=h(),r=x(),i=M(t),a=P(),l=[],p=[],g=[],u={run:async()=>({output:""}),...e.agentRunner},m=new AbortController,v=async c=>(l.push(c),{accepted:true}),w=async c=>(p.push(c),{accepted:true}),E=async(c,O)=>{g.push({messageId:c,patch:O});},R=async c=>({userId:c,displayName:c}),b=async()=>{},C=async()=>({messageId:"mock-proactive",sentAt:Date.now()});return {instanceId:t,installationId:e.installationId,config:e.config,capabilities:new Set(e.capabilities??[]),log:n,agentRunner:u,db:i,storage:a,audit:o,abortSignal:e.abortSignal??m.signal,httpRouter:r,router:r,inbound:v,emitEvent:w,updateMessage:E,resolveUser:R,respondSync:b,proactive:C,inboundCalls:l,emittedEvents:p,sentMessages:g}}function L(){}var k={claude:{models:[{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-4-5":{effort:[]}}},codex:{models:[{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship",recommended:true},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindowTokens:4e5,tier:"speed"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",contextWindowTokens:4e5,tier:"flagship"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",contextWindowTokens:128e3,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-5.6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["minimal","low","medium","high","xhigh"],defaultEffort:"high"}}},opencode:{models:[],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{}},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{}},antigravity:{models:[{id:"gemini-3.6-flash-high",name:"Gemini 3.6 Flash (High)",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash-medium",name:"Gemini 3.6 Flash (Medium)",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash-low",name:"Gemini 3.6 Flash (Low)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.5 Flash (Medium)",name:"Gemini 3.5 Flash (Medium)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.5 Flash (High)",name:"Gemini 3.5 Flash (High)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.5 Flash (Low)",name:"Gemini 3.5 Flash (Low)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.1 Pro (Low)",name:"Gemini 3.1 Pro (Low)",contextWindowTokens:1048576,tier:"flagship"},{id:"Gemini 3.1 Pro (High)",name:"Gemini 3.1 Pro (High)",contextWindowTokens:1048576,tier:"flagship"},{id:"Claude Sonnet 4.6 (Thinking)",name:"Claude Sonnet 4.6 (Thinking)",contextWindowTokens:1e6,tier:"balanced"},{id:"Claude Opus 4.6 (Thinking)",name:"Claude Opus 4.6 (Thinking)",contextWindowTokens:1e6,tier:"flagship"},{id:"GPT-OSS 120B (Medium)",name:"GPT-OSS 120B (Medium)",contextWindowTokens:128e3,tier:"balanced"}],modes:[],effort:[],modelOverrides:{}}};Object.fromEntries(Object.entries(k).map(([e,t])=>[e,t.models]));var _=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}];new Map(_.map(({baseModelId:e,catalogModelId:t})=>[e,t]));function W(){}export{f as createMockAudit,A as createMockContext,h as createMockLogger,x as createMockRouter,P as createMockStorage,M as createMockStore,W as resetModelsOverride,L as resetPricingOverride};
|
|
1
|
+
function f(){let e=[];return {events:e,async log(t,o){e.push({event:t,payload:o});}}}function h(){let e={debug:[],info:[],warn:[],error:[]};return {entries:e,debug(t,o){e.debug.push({msg:t,meta:o});},info(t,o){e.info.push({msg:t,meta:o});},warn(t,o){e.warn.push({msg:t,meta:o});},error(t,o){e.error.push({msg:t,meta:o});}}}function A(){let e=200,t,o,n={},r={status(i){return e=i,r},set(i,a){return n[i]=a,r},send(i){return o=i,r},json(i){return t=i,r},end(){return r},getStatusCode:()=>e,getJsonBody:()=>t,getSentBody:()=>o,getHeaders:()=>({...n})};return r}function x(){let e=[];return {routes:e,registerRoute(o,n,r){e.push({path:o,handler:n,opts:r});},async simulate(o,n,r=Buffer.alloc(0),i={},a={},p={}){let l=e.find(m=>m.path===n);if(!l)return {status:404,body:{error:"Not found"},headers:{}};let g={method:o,url:n,headers:i,body:r,params:a,query:p},u=A();return await l.handler(g,u),{status:u.getStatusCode(),body:u.getJsonBody()??u.getSentBody(),headers:u.getHeaders()}}}}function P(e){let t=new Map,o=n=>n.startsWith(`${e}::`)?n:`${e}::${n}`;return {async get(n){let r=t.get(o(n));return r?r.value:void 0},async set(n,r){t.set(o(n),{value:r});},async delete(n){return t.delete(o(n))},async list(n){let r=n?o(n):`${e}::`,i=[];for(let a of t.keys())a.startsWith(r)&&i.push(a.slice(e.length+2));return i}}}function M(e){return P(e)}function y(){let e=new Map;return {blobs:e,async put(t,o,n){return e.set(t,{data:o,contentType:n}),t},async get(t){let o=e.get(t);return o?o.data:void 0},async delete(t){return e.delete(t)}}}function T(e){let t=e.instanceId??"mock-instance",o=f(),n=h(),r=x(),i=M(t),a=y(),p=[],l=[],g=[],u={run:async()=>({output:""}),...e.agentRunner},m=new AbortController,w=async c=>(p.push(c),{accepted:true}),v=async c=>(l.push(c),{accepted:true}),E=async(c,C)=>{g.push({messageId:c,patch:C});},b=async c=>({userId:c,displayName:c}),R=async()=>{},O=async()=>({messageId:"mock-proactive",sentAt:Date.now()});return {instanceId:t,installationId:e.installationId,config:e.config,capabilities:new Set(e.capabilities??[]),log:n,agentRunner:u,db:i,storage:a,audit:o,abortSignal:e.abortSignal??m.signal,httpRouter:r,router:r,inbound:w,emitEvent:v,updateMessage:E,resolveUser:b,respondSync:R,proactive:O,inboundCalls:p,emittedEvents:l,sentMessages:g}}function D(){}var k={claude:{models:[{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-4-5":{effort:[]}}},codex:{models:[{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship",recommended:true},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindowTokens:4e5,tier:"speed"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",contextWindowTokens:4e5,tier:"flagship"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",contextWindowTokens:128e3,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-5.6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["minimal","low","medium","high","xhigh"],defaultEffort:"high"}}},opencode:{models:[],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{}},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{}},antigravity:{models:[{id:"gemini-3.6-flash-high",name:"Gemini 3.6 Flash (High)",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash-medium",name:"Gemini 3.6 Flash (Medium)",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash-low",name:"Gemini 3.6 Flash (Low)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.5 Flash (Medium)",name:"Gemini 3.5 Flash (Medium)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.5 Flash (High)",name:"Gemini 3.5 Flash (High)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.5 Flash (Low)",name:"Gemini 3.5 Flash (Low)",contextWindowTokens:1048576,tier:"balanced"},{id:"Gemini 3.1 Pro (Low)",name:"Gemini 3.1 Pro (Low)",contextWindowTokens:1048576,tier:"flagship"},{id:"Gemini 3.1 Pro (High)",name:"Gemini 3.1 Pro (High)",contextWindowTokens:1048576,tier:"flagship"},{id:"Claude Sonnet 4.6 (Thinking)",name:"Claude Sonnet 4.6 (Thinking)",contextWindowTokens:1e6,tier:"balanced"},{id:"Claude Opus 4.6 (Thinking)",name:"Claude Opus 4.6 (Thinking)",contextWindowTokens:1e6,tier:"flagship"},{id:"GPT-OSS 120B (Medium)",name:"GPT-OSS 120B (Medium)",contextWindowTokens:128e3,tier:"balanced"}],modes:[],effort:[],modelOverrides:{}},grok:{models:[{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.5",name:"Grok 4.5",contextWindowTokens:5e5,tier:"flagship"}],modes:[{id:"agent",name:"Agent",description:"Automatically approves tool calls inside the workspace sandbox; it cannot access the rest of the machine."},{id:"read-only",name:"Read Only",description:"Uses a read-only sandbox and plan permission mode; it can inspect files but cannot modify the workspace."},{id:"plan",name:"Plan",description:"Uses plan permission mode with a read-only sandbox; it can inspect and propose work but cannot modify files."},{id:"agent-full-access",name:"Agent Full Access",description:"Automatically approves tool calls with the sandbox disabled; it can access and modify files across the machine."},{id:"yolo",name:"YOLO",description:"Automatically approves tool calls with the sandbox disabled; it can access and modify files across the machine."}],effort:["low","medium","high"],modelOverrides:{"grok-4.6":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.5":{effort:["low","medium","high"],defaultEffort:"high"}}}};Object.fromEntries(Object.entries(k).map(([e,t])=>[e,t.models]));var _=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}];new Map(_.map(({baseModelId:e,catalogModelId:t})=>[e,t]));function W(){}export{f as createMockAudit,T as createMockContext,h as createMockLogger,x as createMockRouter,y as createMockStorage,M as createMockStore,W as resetModelsOverride,D as resetPricingOverride};
|
package/dist/facade/Crewx.d.ts
CHANGED
|
@@ -102,6 +102,20 @@ export declare class Crewx extends TypedEventEmitter {
|
|
|
102
102
|
private _extractLayoutProps;
|
|
103
103
|
private _getConversationProvider;
|
|
104
104
|
private _fetchHistoryMessages;
|
|
105
|
+
private _resolveFreshProvider;
|
|
106
|
+
private _readInputBudgetPercent;
|
|
107
|
+
private _resolveBudgetModel;
|
|
108
|
+
private _resolveContextMode;
|
|
109
|
+
private _hasUsableResumeSessionId;
|
|
110
|
+
private _buildInstructionOnlyResumeManifest;
|
|
111
|
+
private _prepareInstructionOnlyResumeWithBudget;
|
|
112
|
+
private _activityLogEntryCounts;
|
|
113
|
+
private _buildUnresolvedContextBudgetManifest;
|
|
114
|
+
private _buildResolvedContextBudgetManifest;
|
|
115
|
+
private _renderFreshPromptVariant;
|
|
116
|
+
private _prepareFreshPromptWithBudget;
|
|
117
|
+
private _recountFreshProviderInitialInput;
|
|
118
|
+
private _validateFreshProviderInitialInputBudget;
|
|
105
119
|
private _resolveTimeout;
|
|
106
120
|
private _resolveIdleTimeout;
|
|
107
121
|
private _lookupCliAdapter;
|
package/dist/index.browser.d.ts
CHANGED
|
@@ -11,4 +11,4 @@ export { BrowserFsAdapter } from './platform/BrowserFsAdapter.js';
|
|
|
11
11
|
export type { IFsAdapter } from './platform/IFsAdapter.js';
|
|
12
12
|
export { PROVIDER_ORDER, providerRank, compareProviders, normalizeProviderId } from './provider/order.js';
|
|
13
13
|
export { CLAUDE_MODEL_COMPATIBILITY_PAIRS, CLAUDE_OPUS_4_8_BASE_MODEL_ID, CLAUDE_OPUS_4_8_LEGACY_MODEL_ID, resolveCatalogModelId, } from './config/model-compat.js';
|
|
14
|
-
export type { AgentConfig, CrewxProjectConfig, CrewxOptions, QueryOptions, QueryResult, ExecuteOptions, ExecuteResult, } from './types/index.js';
|
|
14
|
+
export type { AgentConfig, CrewxProjectConfig, CrewxOptions, QueryOptions, QueryResult, ExecuteOptions, ExecuteResult, ContextMode, } from './types/index.js';
|