@crewx/sdk 0.9.0-rc.75 → 0.9.0-rc.76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -67,7 +67,7 @@ ${t??""}
67
67
  ---
68
68
  `)}u();function eh(){let t=new Date,e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return `${e}-${n}-${r}`}async function kl(t,e=Un){let n=e.resolvePath(t,`${eh()}.md`);return await e.exists(n)?e.readFile(n):""}u();or();pn();function ka(t){if(t.startsWith("cli/"))return Ot[t.slice(4)]}function nh(t,e={}){if(!t.startsWith("cli/"))return true;let r=(e.lookupAdapter??ka)(t);if(!r?.command)return false;let o=jr(r.command,{env:e.env});return ge__default.isAbsolute(o)}function vl(t,e={}){if(!Array.isArray(t))return t;if(t.length===0)return "cli/claude";for(let n of t)if(nh(n,e))return n;return t[0]}u();var to=new AsyncLocalStorage;function va(t){if(t)return {parentTaskId:t.parentTaskId??null,rootTraceId:t.rootTraceId,callerAgentId:t.callerAgentId??null}}u();u();var Ii="<crewx_card";function no(t){return t===" "||t===" "||t===`
69
69
  `||t==="\r"||t==="\f"}function oh(t){if(!t)return false;let e=t.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||t==="_"||t===":"||t==="-"}function ih(t){return t===void 0||no(t)||t==="/"||t===">"}function Tl(t,e){let n=t[e],r=e+1;for(;r<t.length;){if(t[r]===n)return {end:r+1,value:t.slice(e+1,r)};r++;}return {end:t.length,value:t.slice(e+1)}}function sh(t,e){if(t[e]==='"'||t[e]==="'")return Tl(t,e);let n=e;for(;n<t.length&&!no(t[n])&&t[n]!==">";)n++;return {end:n,value:t.slice(e,n)}}function ah(t,e){let n=Object.create(null),r=e+Ii.length,o=false;for(;r<t.length;){let i=t[r];if(i===">")return {end:r+1,closed:true,attrs:n,privileged:o};if(no(i)||i==="/"){r++;continue}if(i==='"'||i==="'"){r=Tl(t,r).end;continue}let s=r;for(;r<t.length&&oh(t[r]);)r++;if(r===s){r++;continue}let a=t.slice(s,r);for(a==="proof"&&(o=true);r<t.length&&no(t[r]);)r++;if(t[r]!=="="){n[a]="";continue}for(r++;r<t.length&&no(t[r]);)r++;let d=sh(t,r);n[a]=d.value,r=d.end;}return {end:t.length,closed:false,attrs:n,privileged:o}}function Ta(t,e){let n=ah(t,e);return {start:e,end:n.end,raw:t.slice(e,n.end),closed:n.closed,attrs:n.attrs,privileged:n.privileged}}function ro(t){let e=[],n=0;for(;n<t.length;){let r=t.indexOf(Ii,n);if(r<0)break;if(!ih(t[r+Ii.length])){n=r+Ii.length;continue}let o=Ta(t,r);if(e.push(o),!o.closed)break;n=o.end;}return e}function El(t){return t&&ro(t).find(r=>!!r.attrs.run_id?.trim())?.attrs.run_id?.trim()||void 0}u();u();var S=class extends Error{constructor(n,r=n,o){super(r);this.code=n;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"},Ke=class extends Error{constructor(n){super("UI instance database operation will be retried");this.cause=n;}cause;name="UiRetryableDatabaseError"},ct=class extends Error{constructor(n){super("UI instance revision reservation conflict");this.currentRevision=n;}currentRevision;name="UiReservationConflictError"};var dh=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,ch=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|directory|dir|folder)$/i,lh=/<\/?[A-Za-z][^>]*>/,uh=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ph=/^(?:https?|file|ftp|ws|wss):\/\//i;function Nt(){throw new S("INPUT_INVALID","JSON value is not projection-safe")}function gh(t){let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Ea(t,e,n,r){if(e>8&&Nt(),t===null||typeof t=="string"||typeof t=="boolean")return typeof t=="string"&&(lh.test(t)||ph.test(t)||uh.test(t))&&Nt(),t;if(typeof t=="number")return Number.isFinite(t)||Nt(),t;(typeof t!="object"||t===void 0||typeof t=="function"||typeof t=="bigint")&&Nt();let o=t;n.has(o)&&Nt(),n.add(o);try{if(Array.isArray(t))return t.map(s=>Ea(s,e+1,n));gh(o)||Nt();let i={};for(let[s,a]of Object.entries(t))(dh.test(s)||ch.test(s))&&Nt(),i[s]=Ea(a,e+1,n,s);return i}finally{n.delete(o);}}function Se(t){let e=Ea(t,0,new Set);return (e===null||Array.isArray(e)||typeof e!="object")&&Nt(),e}function Fe(t){try{let e=JSON.stringify(t);return e===void 0&&Nt(),e}catch{Nt();}}function ba(t){return Array.isArray(t)?t.map(ba):t!==null&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(e=>[e,ba(t[e])])):t}function bl(t){return Fe(ba(t))}function oo(t){return Buffer.byteLength(t,"utf8")}var Rl="[workflow card omitted from AI context]",fh="[workflow UI instance omitted from AI context]",mh=/\{\s*"instanceId"\s*:\s*"uic_[A-Za-z0-9_-]+"\s*\}/g;function xi(t){return typeof t=="string"?t.replace(mh,fh):""}function Ci(t){if(typeof t!="string"||t.length===0)return "";let e="",n=0;for(let r of ro(t))if(e+=t.slice(n,r.start),e+=r.privileged?Rl:r.raw,n=r.end,!r.closed)break;return e+=t.slice(n),e}function hh(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function yh(t,e){if(typeof t!="string")return "";let n=e?Ci(t):t,r=e?xi(n):n;return hh(r)}function Ra(t){return t.map(e=>({...e,text:yh(e.text,e.isAssistant)}))}function lr(t,e){let n=Ra(t);if(!e||e.length===0)return n;let r=[];for(let o of e)try{if(Object.keys(o).sort().join(",")!=="availableActions,definition,facts,instanceId,pendingDecision,recentChanges,revision"||!/^uic_[A-Za-z0-9_-]+$/.test(o.instanceId))continue;let s=Se(o),a=JSON.stringify(s);if(typeof a!="string"||oo(a)>64*1024)continue;r.push(s);}catch{}return r.length===0?n:[...n,{text:`CrewX workflow context:
70
- ${JSON.stringify(r)}`,isAssistant:true}]}function Ia(t){return Ra(t.messages.map(e=>({id:e.id,text:e.text,isAssistant:e.isAssistant,taskId:e.taskId,timestamp:e.timestamp,metadata:e.metadata,files:void 0})))}u();pn();gn();u();u();var ye=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Ja__default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};u();var Il=32*1024*1024;function B(t){let e=He("better-sqlite3"),{drizzle:n}=He("drizzle-orm/better-sqlite3"),r=new e(t);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${Il}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),r.exec("PRAGMA optimize"),{db:n(r),runRaw:(o,i=[])=>r.prepare(o).run(...i),close:()=>r.close()}}u();var xl=new Set,Eh={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT"};function Ca(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function bh(t,e){if(e>0||!Ca(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,i]of Object.entries(Eh))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${i}`);}var Rh={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"}};function Ih(t,e,n){if(!Ca(t,"__drizzle_migrations")||!Ca(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(s=>s.hash)),i=JSON.parse(readFileSync(ge__default.join(e,"meta/_journal.json"),"utf-8"));for(let s of i.entries){let a=Rh[s.tag];if(!a)continue;let d=ge__default.join(e,`${s.tag}.sql`);if(!existsSync(d))continue;let c=readFileSync(d,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(o.has(l))continue;let p=t.all("PRAGMA table_info(tasks)"),f=new Set(p.map(m=>m.name));for(let[m,E]of Object.entries(a))f.has(m)||(t.run(`ALTER TABLE tasks ADD COLUMN ${m} ${E}`),f.add(m));}}function xh(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(s=>s.hash)),i=JSON.parse(readFileSync(ge__default.join(e,"meta/_journal.json"),"utf-8"));for(let s of i.entries){let a=ge__default.join(e,`${s.tag}.sql`);if(!existsSync(a))continue;let d=readFileSync(a,"utf-8"),c=createHash("sha256").update(d).digest("hex");if(o.has(c))continue;let l=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,p=[],f;for(;(f=l.exec(d))!==null;)p.push({table:f[1],column:f[2]});if(p.length===0||!d.split(/-->\s*statement-breakpoint/).map(h=>h.trim()).filter(Boolean).every(h=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(h)))continue;p.every(({table:h,column:v})=>t.all(`PRAGMA table_info("${h}")`).some(T=>T.name===v))&&t.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${s.when})`);}}function Si(t){let{migrate:e}=He("drizzle-orm/better-sqlite3/migrator"),{sql:n}=He("drizzle-orm"),r=[ge__default.join(_,"../migrations"),ge__default.join(_,"migrations"),ge__default.join(_,"../../../../drizzle/migrations"),ge__default.join(process.cwd(),"drizzle/migrations")],o=r.find(c=>existsSync(ge__default.join(c,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
70
+ ${JSON.stringify(r)}`,isAssistant:true}]}function Ia(t){return Ra(t.messages.map(e=>({id:e.id,text:e.text,isAssistant:e.isAssistant,taskId:e.taskId,timestamp:e.timestamp,metadata:e.metadata,files:void 0})))}u();pn();gn();u();u();var ye=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Ja__default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};u();var Il=32*1024*1024;function B(t){let e=He("better-sqlite3"),{drizzle:n}=He("drizzle-orm/better-sqlite3"),r=new e(t);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${Il}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),{db:n(r),runRaw:(o,i=[])=>r.prepare(o).run(...i),close:()=>r.close()}}u();var xl=new Set,Eh={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT"};function Ca(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function bh(t,e){if(e>0||!Ca(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,i]of Object.entries(Eh))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${i}`);}var Rh={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"}};function Ih(t,e,n){if(!Ca(t,"__drizzle_migrations")||!Ca(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(s=>s.hash)),i=JSON.parse(readFileSync(ge__default.join(e,"meta/_journal.json"),"utf-8"));for(let s of i.entries){let a=Rh[s.tag];if(!a)continue;let d=ge__default.join(e,`${s.tag}.sql`);if(!existsSync(d))continue;let c=readFileSync(d,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(o.has(l))continue;let p=t.all("PRAGMA table_info(tasks)"),f=new Set(p.map(m=>m.name));for(let[m,E]of Object.entries(a))f.has(m)||(t.run(`ALTER TABLE tasks ADD COLUMN ${m} ${E}`),f.add(m));}}function xh(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(s=>s.hash)),i=JSON.parse(readFileSync(ge__default.join(e,"meta/_journal.json"),"utf-8"));for(let s of i.entries){let a=ge__default.join(e,`${s.tag}.sql`);if(!existsSync(a))continue;let d=readFileSync(a,"utf-8"),c=createHash("sha256").update(d).digest("hex");if(o.has(c))continue;let l=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,p=[],f;for(;(f=l.exec(d))!==null;)p.push({table:f[1],column:f[2]});if(p.length===0||!d.split(/-->\s*statement-breakpoint/).map(h=>h.trim()).filter(Boolean).every(h=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(h)))continue;p.every(({table:h,column:v})=>t.all(`PRAGMA table_info("${h}")`).some(T=>T.name===v))&&t.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${s.when})`);}}function Si(t){let{migrate:e}=He("drizzle-orm/better-sqlite3/migrator"),{sql:n}=He("drizzle-orm"),r=[ge__default.join(_,"../migrations"),ge__default.join(_,"migrations"),ge__default.join(_,"../../../../drizzle/migrations"),ge__default.join(process.cwd(),"drizzle/migrations")],o=r.find(c=>existsSync(ge__default.join(c,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
71
71
  ${r.join(`
72
72
  `)}`);let i=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),s=0;i?.cnt&&(s=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),bh(t,s),i?.cnt&&(xh(t,o,n),Ih(t,o,n)),e(t,{migrationsFolder:o});let d=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-s;if(d>0){let c=i?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${d} migration${d>1?"s":""} applied).`);}}function fe(t,e){xl.has(e)||(Si(t),xl.add(e));}u();var k=class extends Error{code;cause;constructor(e,n,r){super(n),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};u();u();var fn=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()});u();var g=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},t=>({log_storage_check:check("tasks_log_storage_ck",sql`${t.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:index("idx_tasks_status").on(t.status),idx_tasks_started_at:index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(t.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(t.workspace_id,t.started_at)}));u();var Lt=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>g.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},t=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq)}));u();var Uh="json_extract(metadata, '$.threadTitle.state')",jh="json_extract(metadata, '$.threadTitle.priority')",b=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>fn.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)},t=>({idx_threads_updated_at:index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_title:index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(t.workspace_id,sql.raw(Uh)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(jh))}));u();var mn=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>g.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>mn.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")},t=>({idx_spans_task_id:index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(t.parent_span_id)}));u();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>g.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()},t=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(t.timestamp)}));u();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>b.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()},t=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:unique().on(t.thread_id,t.seq)}));u();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")},t=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(t.partition_key)}));u();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")},t=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));u();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")},t=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));u();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")},t=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(t.workspace_id,sql`${t.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},t=>({pk:primaryKey({columns:[t.notification_id,t.user_id]})}));u();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()},t=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));u();sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({idCheck:check("ui_instances_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${t.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${t.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${t.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${t.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id)}));u();sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},t=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${t.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${t.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${t.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${t.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
73
73
  (${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)