@crewx/sdk 0.9.0-rc.176 → 0.9.0-rc.178

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/index.js CHANGED
@@ -69,7 +69,7 @@ ${r.join(`
69
69
  OR
70
70
  (${e.status} IN ('deferred', 'failed') AND ${e.code} IS NOT NULL
71
71
  AND ${e.to_revision} IS NULL)
72
- )`)}));});var cO=M(()=>{h();sqliteCore.sqliteTable("ui_definition_archive",{definition_hash:sqliteCore.text("definition_hash").primaryKey().notNull(),definition_json:sqliteCore.text("definition_json").notNull(),created_at:sqliteCore.integer("created_at").notNull()},e=>({definitionHashCheck:sqliteCore.check("ui_definition_archive_definition_hash_ck",drizzleOrm.sql`length(${e.definition_hash}) = 64 AND ${e.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:sqliteCore.check("ui_definition_archive_definition_json_ck",drizzleOrm.sql`json_valid(${e.definition_json}) AND json_type(${e.definition_json}) = 'object'`),createdAtCheck:sqliteCore.check("ui_definition_archive_created_at_ck",drizzleOrm.sql`${e.created_at} >= 0`)}));});var eT,uO=M(()=>{h();eT=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},e=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${e.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${e.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${e.stages_json}) AND json_type(${e.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${e.stage_index} >= 1`)})),sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>eT.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},e=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${e.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${e.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${e.evidence_json}) AND json_type(${e.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(e.project_id,e.position)})),sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>eT.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},e=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${e.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${e.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${e.payload_json}) AND json_type(${e.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(e.project_id,e.seq)}));});exports.COMMON_CODE_GROUPS=void 0;exports.COMMON_CODE_COLORS=void 0;var ee,oT=M(()=>{h();exports.COMMON_CODE_GROUPS=["THREAD_STATE","THREAD_PRIORITY"],exports.COMMON_CODE_COLORS=["gray","blue","violet","green","amber","orange","red","pink"],ee=sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},e=>({pk:sqliteCore.primaryKey({columns:[e.code_group,e.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${e.metadata} IS NULL OR (json_valid(${e.metadata}) AND json_type(${e.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${e.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${e.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(e.code_group,e.is_archived,e.sort_order)}));});exports.THREAD_EVENT_TYPES=void 0;exports.THREAD_ACTOR_TYPES=void 0;exports.THREAD_HIGHLIGHT_SOURCES=void 0;exports.THREAD_HIGHLIGHT_KINDS=void 0;exports.THREAD_HIGHLIGHT_STATUSES=void 0;exports.THREAD_HIGHLIGHT_RUN_STATUSES=void 0;var $e,Se,ye,Sm=M(()=>{h();Nu();exports.THREAD_EVENT_TYPES=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],exports.THREAD_ACTOR_TYPES=["user","agent","system"],exports.THREAD_HIGHLIGHT_SOURCES=["auto","manual"],exports.THREAD_HIGHLIGHT_KINDS=["decision","judgment","issue","result","pivot"],exports.THREAD_HIGHLIGHT_STATUSES=["active","dismissed"],exports.THREAD_HIGHLIGHT_RUN_STATUSES=["queued","running","completed","failed"],$e=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),type:sqliteCore.text("type").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),payload_json:sqliteCore.text("payload_json").notNull(),created_at:sqliteCore.text("created_at").notNull(),actor_id:sqliteCore.text("actor_id"),task_id:sqliteCore.text("task_id"),highlight_id:sqliteCore.text("highlight_id")},e=>({typeCheck:sqliteCore.check("thread_events_type_ck",drizzleOrm.sql`${e.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:sqliteCore.check("thread_events_actor_type_ck",drizzleOrm.sql`${e.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:sqliteCore.check("thread_events_payload_json_ck",drizzleOrm.sql`json_valid(${e.payload_json}) AND json_type(${e.payload_json}) = 'object'`),threadSeqIndex:sqliteCore.index("idx_thread_events_thread_seq").on(e.thread_id,e.seq),threadCreatedIndex:sqliteCore.index("idx_thread_events_thread_created").on(e.thread_id,e.created_at),threadSeqUnique:sqliteCore.uniqueIndex("thread_events_thread_seq_uq").on(e.thread_id,e.seq)})),Se=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),request_id:sqliteCore.text("request_id").notNull(),status:sqliteCore.text("status").notNull(),detector_version:sqliteCore.text("detector_version").notNull(),requested_at:sqliteCore.text("requested_at").notNull(),started_at:sqliteCore.text("started_at"),completed_at:sqliteCore.text("completed_at"),error_code:sqliteCore.text("error_code"),previous_auto_count:sqliteCore.integer("previous_auto_count"),new_auto_count:sqliteCore.integer("new_auto_count")},e=>({statusCheck:sqliteCore.check("thread_highlight_runs_status_ck",drizzleOrm.sql`${e.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:sqliteCore.check("thread_highlight_runs_counts_ck",drizzleOrm.sql`(${e.previous_auto_count} IS NULL OR ${e.previous_auto_count} >= 0) AND (${e.new_auto_count} IS NULL OR ${e.new_auto_count} >= 0)`),threadRequestUnique:sqliteCore.uniqueIndex("thread_highlight_runs_thread_request_uq").on(e.thread_id,e.request_id),inProgressThreadUnique:sqliteCore.uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(e.thread_id).where(drizzleOrm.sql`${e.status} IN ('queued', 'running')`),threadStatusRequestedIndex:sqliteCore.index("idx_thread_highlight_runs_thread_status_requested").on(e.thread_id,e.status,e.requested_at)})),ye=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),source:sqliteCore.text("source").notNull(),kind:sqliteCore.text("kind").notNull(),status:sqliteCore.text("status").notNull().default("active"),text:sqliteCore.text("text"),covers_from_task_id:sqliteCore.text("covers_from_task_id").notNull(),covers_to_task_id:sqliteCore.text("covers_to_task_id").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),agent_id:sqliteCore.text("agent_id"),source_task_id:sqliteCore.text("source_task_id"),detector_version:sqliteCore.text("detector_version"),content_fingerprint:sqliteCore.text("content_fingerprint"),dismissed_at:sqliteCore.text("dismissed_at")},e=>({sourceCheck:sqliteCore.check("thread_highlights_source_ck",drizzleOrm.sql`${e.source} IN ('auto', 'manual')`),kindCheck:sqliteCore.check("thread_highlights_kind_ck",drizzleOrm.sql`${e.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:sqliteCore.check("thread_highlights_status_ck",drizzleOrm.sql`${e.status} IN ('active', 'dismissed')`),activeTextCheck:sqliteCore.check("thread_highlights_active_text_ck",drizzleOrm.sql`${e.status} = 'dismissed' OR (${e.text} IS NOT NULL AND length(${e.text}) > 0)`),coversCheck:sqliteCore.check("thread_highlights_covers_ck",drizzleOrm.sql`length(${e.covers_from_task_id}) > 0 AND length(${e.covers_to_task_id}) > 0`),autoKeyCheck:sqliteCore.check("thread_highlights_auto_key_ck",drizzleOrm.sql`${e.source} = 'manual' OR (${e.source} = 'auto' AND ${e.source_task_id} IS NOT NULL AND ${e.detector_version} IS NOT NULL AND ${e.content_fingerprint} IS NOT NULL AND length(${e.source_task_id}) > 0 AND length(${e.detector_version}) > 0 AND length(${e.content_fingerprint}) > 0)`),threadStatusCreatedIndex:sqliteCore.index("idx_thread_highlights_thread_status_created").on(e.thread_id,e.status,e.created_at),threadCoversIndex:sqliteCore.index("idx_thread_highlights_thread_covers").on(e.thread_id,e.covers_from_task_id,e.covers_to_task_id),autoIdempotencyUnique:sqliteCore.uniqueIndex("thread_highlights_auto_idempotency_uq").on(e.thread_id,e.source_task_id,e.detector_version,e.content_fingerprint).where(drizzleOrm.sql`${e.source} = 'auto'`)}));});var fO=M(()=>{h();sqliteCore.sqliteTable("storage_metadata",{source_kind:sqliteCore.text("source_kind").notNull(),source_id:sqliteCore.text("source_id").notNull(),utc_ts:sqliteCore.text("utc_ts"),bytes:sqliteCore.integer("bytes").notNull()},e=>({pk:sqliteCore.primaryKey({columns:[e.source_kind,e.source_id]}),kindTimestampBytesIndex:sqliteCore.index("idx_storage_metadata_kind_ts_bytes").on(e.source_kind,e.utc_ts,e.bytes)})),sqliteCore.sqliteTable("storage_metadata_state",{unit:sqliteCore.text("unit").primaryKey().notNull(),cursor_rowid:sqliteCore.integer("cursor_rowid").notNull().default(0),end_rowid:sqliteCore.integer("end_rowid"),complete:sqliteCore.integer("complete").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()});});var Yn,gO=M(()=>{h();Yn=sqliteCore.sqliteTable("agent_send_history",{workspace_id:sqliteCore.text("workspace_id").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),last_accepted_at:sqliteCore.text("last_accepted_at").notNull()},e=>({pk:sqliteCore.primaryKey({columns:[e.workspace_id,e.actor_id,e.agent_id]}),recentIndex:sqliteCore.index("idx_agent_send_history_recent").on(e.workspace_id,e.actor_id,e.last_accepted_at,e.agent_id)}));});exports.SIDEBAR_GROUP_COLORS=void 0;var gr,Ye,ve,St,xr,fT=M(()=>{h();Nu();_m();exports.SIDEBAR_GROUP_COLORS=["cyan","orange","purple","blue"],gr=sqliteCore.sqliteTable("sidebar_states",{workspace_id:sqliteCore.text("workspace_id").primaryKey().references(()=>xt.id,{onDelete:"cascade"}),revision:sqliteCore.integer("revision").notNull().default(0),rail_collapsed:sqliteCore.integer("rail_collapsed").notNull().default(0),seeded_at:sqliteCore.text("seeded_at").notNull()},e=>({railCollapsedCheck:sqliteCore.check("sidebar_states_rail_collapsed_ck",drizzleOrm.sql`${e.rail_collapsed} IN (0, 1)`)})),Ye=sqliteCore.sqliteTable("sidebar_groups",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>xt.id,{onDelete:"cascade"}),name:sqliteCore.text("name").notNull(),color:sqliteCore.text("color").notNull(),collapsed:sqliteCore.integer("collapsed").notNull().default(0),position:sqliteCore.integer("position").notNull()},e=>({colorCheck:sqliteCore.check("sidebar_groups_color_ck",drizzleOrm.sql`${e.color} IN ('cyan', 'orange', 'purple', 'blue')`),collapsedCheck:sqliteCore.check("sidebar_groups_collapsed_ck",drizzleOrm.sql`${e.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:sqliteCore.index("idx_sidebar_groups_workspace_position").on(e.workspace_id,e.position)})),ve=sqliteCore.sqliteTable("sidebar_tabs",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>xt.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Ye.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull()},e=>({pk:sqliteCore.primaryKey({columns:[e.workspace_id,e.thread_id]})})),St=sqliteCore.sqliteTable("sidebar_closed_tabs",{id:sqliteCore.integer("id").primaryKey({autoIncrement:true}),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>xt.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Ye.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull(),closed_at:sqliteCore.text("closed_at").notNull()},e=>({idxSidebarClosedTabsWorkspaceId:sqliteCore.index("idx_sidebar_closed_tabs_workspace_id").on(e.workspace_id,e.id)})),xr=sqliteCore.sqliteTable("thread_reads",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>xt.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),read_through_at:sqliteCore.text("read_through_at").notNull()},e=>({pk:sqliteCore.primaryKey({columns:[e.workspace_id,e.thread_id]})}));});var Qe,yO=M(()=>{h();Qe=sqliteCore.sqliteTable("schedule_runs",{id:sqliteCore.text("id").primaryKey(),schedule_id:sqliteCore.text("schedule_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),mode:sqliteCore.text("mode").notNull(),trigger:sqliteCore.text("trigger").notNull(),occurrence_key:sqliteCore.text("occurrence_key"),task_id:sqliteCore.text("task_id"),app_id:sqliteCore.text("app_id"),schedule_name:sqliteCore.text("schedule_name"),builtin_id:sqliteCore.text("builtin_id"),command:sqliteCore.text("command"),high_frequency:sqliteCore.integer("high_frequency").notNull().default(0),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),exit_code:sqliteCore.integer("exit_code"),signal:sqliteCore.text("signal"),started_at:sqliteCore.text("started_at").notNull(),finished_at:sqliteCore.text("finished_at"),duration_ms:sqliteCore.integer("duration_ms"),pid:sqliteCore.integer("pid"),host_pid:sqliteCore.integer("host_pid"),output_tail:sqliteCore.text("output_tail"),output_bytes:sqliteCore.integer("output_bytes"),output_truncated:sqliteCore.integer("output_truncated").notNull().default(0)},e=>({idx_schedule_runs_workspace_started:sqliteCore.index("idx_schedule_runs_workspace_started").on(e.workspace_id,drizzleOrm.sql`${e.started_at} DESC`),idx_schedule_runs_schedule_started:sqliteCore.index("idx_schedule_runs_schedule_started").on(e.schedule_id,drizzleOrm.sql`${e.started_at} DESC`),idx_schedule_runs_task_id:sqliteCore.index("idx_schedule_runs_task_id").on(e.task_id),idx_schedule_runs_running:sqliteCore.index("idx_schedule_runs_running").on(e.workspace_id,e.started_at).where(drizzleOrm.sql`${e.status} = 'running'`)}));});var _O=M(()=>{h();sqliteCore.sqliteTable("run_column_backfill",{name:sqliteCore.text("name").primaryKey(),cursor:sqliteCore.integer("cursor"),anchor_id:sqliteCore.text("anchor_id"),completed_at:sqliteCore.text("completed_at")});});var Ct=M(()=>{h();_m();gc();DP();MP();Nu();FP();jP();VP();JP();zP();KP();QP();ZP();tO();rO();oO();sO();aO();cO();uO();oT();Sm();fO();gO();fT();yO();_O();});function Ja(e){return typeof e=="string"&&exports.WORKFLOW_ANCHOR_TASK_KINDS.includes(e)}function Hu(e){if(!e||!e.includes("workflow"))return null;let t;try{t=JSON.parse(e);}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r=n.workflowRunId;if(typeof r=="string"&&r!=="")return r;let o=n.workflow;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=o.exec_id;if(typeof i=="string"&&i!=="")return i}return null}exports.WORKFLOW_ANCHOR_TASK_KINDS=void 0;var Ga=M(()=>{h();exports.WORKFLOW_ANCHOR_TASK_KINDS=["workflow_card","workflow_ui_instance","workflow_run"];});function Om(e){if(!e||!e.includes("schedule_id"))return null;let t;try{t=JSON.parse(e);}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r=n.trigger;if(typeof r!="string"||!YJ.includes(r))return null;let o=n.schedule_id;return typeof o=="string"&&o!==""?o:null}var Pm,AO,IO,TO,hT,YJ,yT=M(()=>{h();Pm="tasks_run_columns",AO="idx_tasks_workflow_run_id",IO="idx_tasks_ws_schedule_started",TO="idx_tasks_ws_human_started",hT=[{name:AO,sql:`CREATE INDEX IF NOT EXISTS ${AO} ON tasks (workflow_run_id) WHERE workflow_run_id IS NOT NULL`},{name:IO,sql:`CREATE INDEX IF NOT EXISTS ${IO} ON tasks (workspace_id, started_at) WHERE schedule_id IS NOT NULL`},{name:TO,sql:`CREATE INDEX IF NOT EXISTS ${TO} ON tasks (workspace_id, started_at) WHERE actor_kind = 'human'`}],YJ=["cron","cron_manual"];});function SO(e,t){let n=t===void 0?"":` at index ${t}`;if(!e||typeof e!="object")throw new w("VALIDATION",`Task log entry${n} must be an object`);if(typeof e.timestamp!="string"||typeof e.level!="string"||typeof e.message!="string")throw new w("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:e.timestamp,level:e.level,message:e.message}}function wO(e,t){if(t===null||t.trim()==="")return [];let n;try{n=JSON.parse(t);}catch(r){throw new w("DB_ERROR",`Malformed legacy task logs: ${e}`,r)}if(!Array.isArray(n))throw new w("DB_ERROR",`Malformed legacy task logs: ${e} (expected an array)`);try{return n.map((r,o)=>SO(r,o))}catch(r){throw r instanceof w?new w("DB_ERROR",`Malformed legacy task logs: ${e}`,r):r}}function bO(e){if(e.log_storage!=="blob"&&e.log_storage!=="events")throw new w("DB_ERROR",`Invalid task log storage for task: ${e.id}`);if(!Number.isInteger(e.last_log_seq)||e.last_log_seq<0)throw new w("DB_ERROR",`Invalid task log sequence for task: ${e.id}`);if(!Number.isInteger(e.log_revision)||e.log_revision<0)throw new w("DB_ERROR",`Invalid task log revision for task: ${e.id}`);return e.log_storage}function RO(e){return {taskId:e.id,source:bO(e),revision:e.log_revision,lastSeq:e.last_log_seq}}function rG(e){if(!Number.isInteger(e)||e<0)throw new w("VALIDATION","Task log tail limit must be a non-negative integer")}var hc,Nm=M(()=>{h();st();It();Rt();Tt();Ct();hc=class extends be{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=at.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?bi(this.dbPath):super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let o=at.dirname(n);pn.existsSync(o)||pn.mkdirSync(o,{recursive:true});}else if(!pn.existsSync(n))throw new w("NOT_FOUND","Database not found");let r=K(n);if(t)try{je(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(t,n){return t.db.select({id:m.id,log_storage:m.log_storage,last_log_seq:m.last_log_seq,log_revision:m.log_revision,logs:m.logs}).from(m).where(drizzleOrm.eq(m.id,n)).limit(1).get()}findStateRowInTransaction(t,n){return t.select({id:m.id,log_storage:m.log_storage,last_log_seq:m.last_log_seq,log_revision:m.log_revision,logs:m.logs}).from(m).where(drizzleOrm.eq(m.id,n)).limit(1).get()}requireStateRowInTransaction(t,n){let r=this.findStateRowInTransaction(t,n);if(!r)throw new w("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(t,n){return this.appendLogs(t,[n])}appendLogs(t,n){let r=n.map((i,s)=>SO(i,s));if(r.length===0){let i=this.getLogState(t);if(!i)throw new w("NOT_FOUND",`Task not found: ${t}`);return i}let o=this.openHandle(true);try{return o.db.transaction(s=>{let a=this.requireStateRowInTransaction(s,t),d=bO(a);if(d==="blob"){let p=wO(t,a.logs);if(s.update(m).set({logs:JSON.stringify([...p,...r]),log_revision:drizzleOrm.sql`${m.log_revision} + 1`}).where(drizzleOrm.eq(m.id,t)).run().changes!==1)throw new w("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:d,revision:a.log_revision+1,lastSeq:a.last_log_seq}}let c=a.last_log_seq+1,l=a.last_log_seq+r.length;if(s.insert(Fo).values(r.map((p,f)=>({task_id:t,seq:c+f,timestamp:p.timestamp,level:p.level,message:p.message}))).run(),s.update(m).set({last_log_seq:l,log_revision:drizzleOrm.sql`${m.log_revision} + 1`}).where(drizzleOrm.eq(m.id,t)).run().changes!==1)throw new w("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:d,revision:a.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(i){throw i instanceof w?i:new w("DB_ERROR","Failed to append task log",i)}finally{o.close();}}getLogState(t){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,t);return r?RO(r):void 0}catch(r){throw r instanceof w?r:new w("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(t){return this.readLogsInternal(t)}readLogsTail(t,n){return rG(n),this.readLogsInternal(t,n)}readTail(t,n){return this.readLogsTail(t,n)}readLogsInternal(t,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let i=this.findStateRowInTransaction(o,t);if(!i)return;let s=RO(i);if(s.source==="blob"){let l=wO(t,i.logs);return {...s,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let a=o.select({seq:Fo.seq,timestamp:Fo.timestamp,level:Fo.level,message:Fo.message}).from(Fo).where(drizzleOrm.eq(Fo.task_id,t)).orderBy(n===void 0?drizzleOrm.asc(Fo.seq):drizzleOrm.desc(Fo.seq)),c=(n===void 0?a.all():a.limit(n).all()).map(({timestamp:l,level:u,message:p})=>({timestamp:l,level:u,message:p}));return n!==void 0&&c.reverse(),{...s,entries:c}},{behavior:"deferred"})}catch(o){throw o instanceof w?o:new w("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var dG;exports.AgentSendHistoryRepository=void 0;var xm=M(()=>{h();st();It();Rt();Tt();Ct();dG=50,exports.AgentSendHistoryRepository=class extends be{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=`${t.dbRoot}/.crewx/crewx.db`);}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(){let t=this.resolveDbPath(),n=K(t);try{return je(n.db,t),n}catch(r){throw n.close(),r}}recordAccepted(t){if(t.actorKind!=="human"||!t.workspaceId||!t.actorId||!t.agentId)return false;let n;try{n=this.openHandle();let r=t.acceptedAt??new Date().toISOString();return n.db.insert(Yn).values({workspace_id:t.workspaceId,actor_id:t.actorId,agent_id:t.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[Yn.workspace_id,Yn.actor_id,Yn.agent_id],set:{last_accepted_at:drizzleOrm.sql`MAX(${Yn.last_accepted_at}, excluded.last_accepted_at)`}}).run(),!0}catch(r){return console.error("[AgentSendHistoryRepository] Failed to record accepted agent send",r),false}finally{n?.close();}}findRecentAgents(t,n){let r;try{return r=this.openHandle(),r.db.select({agentId:Yn.agent_id,lastAcceptedAt:Yn.last_accepted_at}).from(Yn).where(drizzleOrm.and(drizzleOrm.eq(Yn.workspace_id,t),drizzleOrm.eq(Yn.actor_id,n))).orderBy(drizzleOrm.desc(Yn.last_accepted_at),drizzleOrm.asc(Yn.agent_id)).limit(dG).all()}catch(o){throw o instanceof w?o:new w("DB_ERROR","Failed to find recent agent sends",o)}finally{r?.close();}}};});function Dm(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function cG(e,t){return typeof e=="string"&&e.length>0?e:typeof t=="string"&&t.length>0?t:null}function _T(e){if(typeof e.provider!="string"||e.provider.length===0)return;let n=e.taskLogRepository.readLogs(e.taskId)?.entries.filter(p=>p.level==="stdout").map(p=>p.message).join(`
72
+ )`)}));});var cO=M(()=>{h();sqliteCore.sqliteTable("ui_definition_archive",{definition_hash:sqliteCore.text("definition_hash").primaryKey().notNull(),definition_json:sqliteCore.text("definition_json").notNull(),created_at:sqliteCore.integer("created_at").notNull()},e=>({definitionHashCheck:sqliteCore.check("ui_definition_archive_definition_hash_ck",drizzleOrm.sql`length(${e.definition_hash}) = 64 AND ${e.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:sqliteCore.check("ui_definition_archive_definition_json_ck",drizzleOrm.sql`json_valid(${e.definition_json}) AND json_type(${e.definition_json}) = 'object'`),createdAtCheck:sqliteCore.check("ui_definition_archive_created_at_ck",drizzleOrm.sql`${e.created_at} >= 0`)}));});var eT,uO=M(()=>{h();eT=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},e=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${e.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${e.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${e.stages_json}) AND json_type(${e.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${e.stage_index} >= 1`)})),sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>eT.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},e=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${e.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${e.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${e.evidence_json}) AND json_type(${e.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(e.project_id,e.position)})),sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>eT.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},e=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${e.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${e.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${e.payload_json}) AND json_type(${e.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(e.project_id,e.seq)}));});exports.COMMON_CODE_GROUPS=void 0;exports.COMMON_CODE_COLORS=void 0;var ee,oT=M(()=>{h();exports.COMMON_CODE_GROUPS=["THREAD_STATE","THREAD_PRIORITY"],exports.COMMON_CODE_COLORS=["gray","blue","violet","green","amber","orange","red","pink"],ee=sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},e=>({pk:sqliteCore.primaryKey({columns:[e.code_group,e.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${e.metadata} IS NULL OR (json_valid(${e.metadata}) AND json_type(${e.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${e.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${e.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(e.code_group,e.is_archived,e.sort_order)}));});exports.THREAD_EVENT_TYPES=void 0;exports.THREAD_ACTOR_TYPES=void 0;exports.THREAD_HIGHLIGHT_SOURCES=void 0;exports.THREAD_HIGHLIGHT_KINDS=void 0;exports.THREAD_HIGHLIGHT_STATUSES=void 0;exports.THREAD_HIGHLIGHT_RUN_STATUSES=void 0;var $e,Se,ye,Sm=M(()=>{h();Nu();exports.THREAD_EVENT_TYPES=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],exports.THREAD_ACTOR_TYPES=["user","agent","system"],exports.THREAD_HIGHLIGHT_SOURCES=["auto","manual"],exports.THREAD_HIGHLIGHT_KINDS=["decision","judgment","issue","result","pivot"],exports.THREAD_HIGHLIGHT_STATUSES=["active","dismissed"],exports.THREAD_HIGHLIGHT_RUN_STATUSES=["queued","running","completed","failed"],$e=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),type:sqliteCore.text("type").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),payload_json:sqliteCore.text("payload_json").notNull(),created_at:sqliteCore.text("created_at").notNull(),actor_id:sqliteCore.text("actor_id"),task_id:sqliteCore.text("task_id"),highlight_id:sqliteCore.text("highlight_id")},e=>({typeCheck:sqliteCore.check("thread_events_type_ck",drizzleOrm.sql`${e.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:sqliteCore.check("thread_events_actor_type_ck",drizzleOrm.sql`${e.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:sqliteCore.check("thread_events_payload_json_ck",drizzleOrm.sql`json_valid(${e.payload_json}) AND json_type(${e.payload_json}) = 'object'`),threadSeqIndex:sqliteCore.index("idx_thread_events_thread_seq").on(e.thread_id,e.seq),threadCreatedIndex:sqliteCore.index("idx_thread_events_thread_created").on(e.thread_id,e.created_at),threadSeqUnique:sqliteCore.uniqueIndex("thread_events_thread_seq_uq").on(e.thread_id,e.seq)})),Se=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),request_id:sqliteCore.text("request_id").notNull(),status:sqliteCore.text("status").notNull(),detector_version:sqliteCore.text("detector_version").notNull(),requested_at:sqliteCore.text("requested_at").notNull(),started_at:sqliteCore.text("started_at"),completed_at:sqliteCore.text("completed_at"),error_code:sqliteCore.text("error_code"),previous_auto_count:sqliteCore.integer("previous_auto_count"),new_auto_count:sqliteCore.integer("new_auto_count")},e=>({statusCheck:sqliteCore.check("thread_highlight_runs_status_ck",drizzleOrm.sql`${e.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:sqliteCore.check("thread_highlight_runs_counts_ck",drizzleOrm.sql`(${e.previous_auto_count} IS NULL OR ${e.previous_auto_count} >= 0) AND (${e.new_auto_count} IS NULL OR ${e.new_auto_count} >= 0)`),threadRequestUnique:sqliteCore.uniqueIndex("thread_highlight_runs_thread_request_uq").on(e.thread_id,e.request_id),inProgressThreadUnique:sqliteCore.uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(e.thread_id).where(drizzleOrm.sql`${e.status} IN ('queued', 'running')`),threadStatusRequestedIndex:sqliteCore.index("idx_thread_highlight_runs_thread_status_requested").on(e.thread_id,e.status,e.requested_at)})),ye=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),source:sqliteCore.text("source").notNull(),kind:sqliteCore.text("kind").notNull(),status:sqliteCore.text("status").notNull().default("active"),text:sqliteCore.text("text"),covers_from_task_id:sqliteCore.text("covers_from_task_id").notNull(),covers_to_task_id:sqliteCore.text("covers_to_task_id").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),agent_id:sqliteCore.text("agent_id"),source_task_id:sqliteCore.text("source_task_id"),detector_version:sqliteCore.text("detector_version"),content_fingerprint:sqliteCore.text("content_fingerprint"),dismissed_at:sqliteCore.text("dismissed_at")},e=>({sourceCheck:sqliteCore.check("thread_highlights_source_ck",drizzleOrm.sql`${e.source} IN ('auto', 'manual')`),kindCheck:sqliteCore.check("thread_highlights_kind_ck",drizzleOrm.sql`${e.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:sqliteCore.check("thread_highlights_status_ck",drizzleOrm.sql`${e.status} IN ('active', 'dismissed')`),activeTextCheck:sqliteCore.check("thread_highlights_active_text_ck",drizzleOrm.sql`${e.status} = 'dismissed' OR (${e.text} IS NOT NULL AND length(${e.text}) > 0)`),coversCheck:sqliteCore.check("thread_highlights_covers_ck",drizzleOrm.sql`length(${e.covers_from_task_id}) > 0 AND length(${e.covers_to_task_id}) > 0`),autoKeyCheck:sqliteCore.check("thread_highlights_auto_key_ck",drizzleOrm.sql`${e.source} = 'manual' OR (${e.source} = 'auto' AND ${e.source_task_id} IS NOT NULL AND ${e.detector_version} IS NOT NULL AND ${e.content_fingerprint} IS NOT NULL AND length(${e.source_task_id}) > 0 AND length(${e.detector_version}) > 0 AND length(${e.content_fingerprint}) > 0)`),threadStatusCreatedIndex:sqliteCore.index("idx_thread_highlights_thread_status_created").on(e.thread_id,e.status,e.created_at),threadCoversIndex:sqliteCore.index("idx_thread_highlights_thread_covers").on(e.thread_id,e.covers_from_task_id,e.covers_to_task_id),autoIdempotencyUnique:sqliteCore.uniqueIndex("thread_highlights_auto_idempotency_uq").on(e.thread_id,e.source_task_id,e.detector_version,e.content_fingerprint).where(drizzleOrm.sql`${e.source} = 'auto'`)}));});var fO=M(()=>{h();sqliteCore.sqliteTable("storage_metadata",{source_kind:sqliteCore.text("source_kind").notNull(),source_id:sqliteCore.text("source_id").notNull(),utc_ts:sqliteCore.text("utc_ts"),bytes:sqliteCore.integer("bytes").notNull()},e=>({pk:sqliteCore.primaryKey({columns:[e.source_kind,e.source_id]}),kindTimestampBytesIndex:sqliteCore.index("idx_storage_metadata_kind_ts_bytes").on(e.source_kind,e.utc_ts,e.bytes)})),sqliteCore.sqliteTable("storage_metadata_state",{unit:sqliteCore.text("unit").primaryKey().notNull(),cursor_rowid:sqliteCore.integer("cursor_rowid").notNull().default(0),end_rowid:sqliteCore.integer("end_rowid"),complete:sqliteCore.integer("complete").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()});});var Yn,gO=M(()=>{h();Yn=sqliteCore.sqliteTable("agent_send_history",{workspace_id:sqliteCore.text("workspace_id").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),last_accepted_at:sqliteCore.text("last_accepted_at").notNull()},e=>({pk:sqliteCore.primaryKey({columns:[e.workspace_id,e.actor_id,e.agent_id]}),recentIndex:sqliteCore.index("idx_agent_send_history_recent").on(e.workspace_id,e.actor_id,e.last_accepted_at,e.agent_id)}));});exports.SIDEBAR_GROUP_COLORS=void 0;var gr,Ye,ve,St,xr,fT=M(()=>{h();Nu();_m();exports.SIDEBAR_GROUP_COLORS=["cyan","orange","purple","blue"],gr=sqliteCore.sqliteTable("sidebar_states",{workspace_id:sqliteCore.text("workspace_id").primaryKey().references(()=>xt.id,{onDelete:"cascade"}),revision:sqliteCore.integer("revision").notNull().default(0),rail_collapsed:sqliteCore.integer("rail_collapsed").notNull().default(0),seeded_at:sqliteCore.text("seeded_at").notNull()},e=>({railCollapsedCheck:sqliteCore.check("sidebar_states_rail_collapsed_ck",drizzleOrm.sql`${e.rail_collapsed} IN (0, 1)`)})),Ye=sqliteCore.sqliteTable("sidebar_groups",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>xt.id,{onDelete:"cascade"}),name:sqliteCore.text("name").notNull(),color:sqliteCore.text("color").notNull(),collapsed:sqliteCore.integer("collapsed").notNull().default(0),position:sqliteCore.integer("position").notNull()},e=>({colorCheck:sqliteCore.check("sidebar_groups_color_ck",drizzleOrm.sql`${e.color} IN ('cyan', 'orange', 'purple', 'blue')`),collapsedCheck:sqliteCore.check("sidebar_groups_collapsed_ck",drizzleOrm.sql`${e.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:sqliteCore.index("idx_sidebar_groups_workspace_position").on(e.workspace_id,e.position)})),ve=sqliteCore.sqliteTable("sidebar_tabs",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>xt.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Ye.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull()},e=>({pk:sqliteCore.primaryKey({columns:[e.workspace_id,e.thread_id]})})),St=sqliteCore.sqliteTable("sidebar_closed_tabs",{id:sqliteCore.integer("id").primaryKey({autoIncrement:true}),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>xt.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Ye.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull(),closed_at:sqliteCore.text("closed_at").notNull()},e=>({idxSidebarClosedTabsWorkspaceId:sqliteCore.index("idx_sidebar_closed_tabs_workspace_id").on(e.workspace_id,e.id)})),xr=sqliteCore.sqliteTable("thread_reads",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>xt.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>D.id,{onDelete:"cascade"}),read_through_at:sqliteCore.text("read_through_at").notNull()},e=>({pk:sqliteCore.primaryKey({columns:[e.workspace_id,e.thread_id]})}));});var Qe,yO=M(()=>{h();Qe=sqliteCore.sqliteTable("schedule_runs",{id:sqliteCore.text("id").primaryKey(),schedule_id:sqliteCore.text("schedule_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),mode:sqliteCore.text("mode").notNull(),trigger:sqliteCore.text("trigger").notNull(),occurrence_key:sqliteCore.text("occurrence_key"),task_id:sqliteCore.text("task_id"),app_id:sqliteCore.text("app_id"),schedule_name:sqliteCore.text("schedule_name"),builtin_id:sqliteCore.text("builtin_id"),command:sqliteCore.text("command"),high_frequency:sqliteCore.integer("high_frequency").notNull().default(0),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),exit_code:sqliteCore.integer("exit_code"),signal:sqliteCore.text("signal"),started_at:sqliteCore.text("started_at").notNull(),finished_at:sqliteCore.text("finished_at"),duration_ms:sqliteCore.integer("duration_ms"),pid:sqliteCore.integer("pid"),host_pid:sqliteCore.integer("host_pid"),output_tail:sqliteCore.text("output_tail"),output_bytes:sqliteCore.integer("output_bytes"),output_truncated:sqliteCore.integer("output_truncated").notNull().default(0)},e=>({idx_schedule_runs_workspace_started:sqliteCore.index("idx_schedule_runs_workspace_started").on(e.workspace_id,drizzleOrm.sql`${e.started_at} DESC`),idx_schedule_runs_schedule_started:sqliteCore.index("idx_schedule_runs_schedule_started").on(e.schedule_id,drizzleOrm.sql`${e.started_at} DESC`),idx_schedule_runs_task_id:sqliteCore.index("idx_schedule_runs_task_id").on(e.task_id),idx_schedule_runs_running:sqliteCore.index("idx_schedule_runs_running").on(e.workspace_id,e.started_at).where(drizzleOrm.sql`${e.status} = 'running'`)}));});var _O=M(()=>{h();sqliteCore.sqliteTable("run_column_backfill",{name:sqliteCore.text("name").primaryKey(),cursor:sqliteCore.integer("cursor"),anchor_id:sqliteCore.text("anchor_id"),completed_at:sqliteCore.text("completed_at")});});var Ct=M(()=>{h();_m();gc();DP();MP();Nu();FP();jP();VP();JP();zP();KP();QP();ZP();tO();rO();oO();sO();aO();cO();uO();oT();Sm();fO();gO();fT();yO();_O();});function Ja(e){return typeof e=="string"&&exports.WORKFLOW_ANCHOR_TASK_KINDS.includes(e)}function Hu(e){if(!e||!e.includes("workflow"))return null;let t;try{t=JSON.parse(e);}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r=n.workflowRunId;if(typeof r=="string"&&r!=="")return r;let o=n.workflow;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=o.exec_id;if(typeof i=="string"&&i!=="")return i}return null}exports.WORKFLOW_ANCHOR_TASK_KINDS=void 0;var Ga=M(()=>{h();exports.WORKFLOW_ANCHOR_TASK_KINDS=["workflow_card","workflow_ui_instance","workflow_run"];});function Om(e){if(!e||!e.includes("schedule_id"))return null;let t;try{t=JSON.parse(e);}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r=n.trigger;if(typeof r!="string"||!YJ.includes(r))return null;let o=n.schedule_id;return typeof o=="string"&&o!==""?o:null}var Pm,AO,IO,TO,hT,YJ,yT=M(()=>{h();Pm="tasks_run_columns",AO="idx_tasks_workflow_run_id",IO="idx_tasks_ws_schedule_started",TO="idx_tasks_ws_human_started",hT=[{name:AO,sql:`CREATE INDEX IF NOT EXISTS ${AO} ON tasks (workflow_run_id) WHERE workflow_run_id IS NOT NULL`},{name:IO,sql:`CREATE INDEX IF NOT EXISTS ${IO} ON tasks (workspace_id, started_at) WHERE schedule_id IS NOT NULL`},{name:TO,sql:`CREATE INDEX IF NOT EXISTS ${TO} ON tasks (workspace_id, started_at) WHERE actor_kind = 'human'`}],YJ=["cron","cron_manual"];});function SO(e,t){let n=t===void 0?"":` at index ${t}`;if(!e||typeof e!="object")throw new w("VALIDATION",`Task log entry${n} must be an object`);if(typeof e.timestamp!="string"||typeof e.level!="string"||typeof e.message!="string")throw new w("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:e.timestamp,level:e.level,message:e.message}}function wO(e,t){if(t===null||t.trim()==="")return [];let n;try{n=JSON.parse(t);}catch(r){throw new w("DB_ERROR",`Malformed legacy task logs: ${e}`,r)}if(!Array.isArray(n))throw new w("DB_ERROR",`Malformed legacy task logs: ${e} (expected an array)`);try{return n.map((r,o)=>SO(r,o))}catch(r){throw r instanceof w?new w("DB_ERROR",`Malformed legacy task logs: ${e}`,r):r}}function bO(e){if(e.log_storage!=="blob"&&e.log_storage!=="events")throw new w("DB_ERROR",`Invalid task log storage for task: ${e.id}`);if(!Number.isInteger(e.last_log_seq)||e.last_log_seq<0)throw new w("DB_ERROR",`Invalid task log sequence for task: ${e.id}`);if(!Number.isInteger(e.log_revision)||e.log_revision<0)throw new w("DB_ERROR",`Invalid task log revision for task: ${e.id}`);return e.log_storage}function RO(e){return {taskId:e.id,source:bO(e),revision:e.log_revision,lastSeq:e.last_log_seq}}function rG(e){if(!Number.isInteger(e)||e<0)throw new w("VALIDATION","Task log tail limit must be a non-negative integer")}var hc,Nm=M(()=>{h();st();It();Rt();Tt();Ct();hc=class extends be{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=at.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?bi(this.dbPath):super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let o=at.dirname(n);pn.existsSync(o)||pn.mkdirSync(o,{recursive:true});}else if(!pn.existsSync(n))throw new w("NOT_FOUND","Database not found");let r=K(n);if(t)try{je(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(t,n){return t.db.select({id:m.id,log_storage:m.log_storage,last_log_seq:m.last_log_seq,log_revision:m.log_revision,logs:m.logs}).from(m).where(drizzleOrm.eq(m.id,n)).limit(1).get()}findStateRowInTransaction(t,n){return t.select({id:m.id,log_storage:m.log_storage,last_log_seq:m.last_log_seq,log_revision:m.log_revision,logs:m.logs}).from(m).where(drizzleOrm.eq(m.id,n)).limit(1).get()}requireStateRowInTransaction(t,n){let r=this.findStateRowInTransaction(t,n);if(!r)throw new w("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(t,n){return this.appendLogs(t,[n])}appendLogs(t,n){let r=n.map((i,s)=>SO(i,s));if(r.length===0){let i=this.getLogState(t);if(!i)throw new w("NOT_FOUND",`Task not found: ${t}`);return i}let o=this.openHandle(true);try{return o.db.transaction(s=>{let a=this.requireStateRowInTransaction(s,t),d=bO(a);if(d==="blob"){let p=wO(t,a.logs);if(s.update(m).set({logs:JSON.stringify([...p,...r]),log_revision:drizzleOrm.sql`${m.log_revision} + 1`}).where(drizzleOrm.eq(m.id,t)).run().changes!==1)throw new w("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:d,revision:a.log_revision+1,lastSeq:a.last_log_seq}}let c=a.last_log_seq+1,l=a.last_log_seq+r.length;if(s.insert(Fo).values(r.map((p,f)=>({task_id:t,seq:c+f,timestamp:p.timestamp,level:p.level,message:p.message}))).run(),s.update(m).set({last_log_seq:l,log_revision:drizzleOrm.sql`${m.log_revision} + 1`}).where(drizzleOrm.eq(m.id,t)).run().changes!==1)throw new w("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:d,revision:a.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(i){throw i instanceof w?i:new w("DB_ERROR","Failed to append task log",i)}finally{o.close();}}getLogState(t){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,t);return r?RO(r):void 0}catch(r){throw r instanceof w?r:new w("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(t){return this.readLogsInternal(t)}readLogsTail(t,n){return rG(n),this.readLogsInternal(t,n)}readTail(t,n){return this.readLogsTail(t,n)}readLogsInternal(t,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let i=this.findStateRowInTransaction(o,t);if(!i)return;let s=RO(i);if(s.source==="blob"){let l=wO(t,i.logs).map((u,p)=>({...u,seq:p+1}));return {...s,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let a=o.select({seq:Fo.seq,timestamp:Fo.timestamp,level:Fo.level,message:Fo.message}).from(Fo).where(drizzleOrm.eq(Fo.task_id,t)).orderBy(n===void 0?drizzleOrm.asc(Fo.seq):drizzleOrm.desc(Fo.seq)),c=(n===void 0?a.all():a.limit(n).all()).map(({seq:l,timestamp:u,level:p,message:f})=>({seq:l,timestamp:u,level:p,message:f}));return n!==void 0&&c.reverse(),{...s,entries:c}},{behavior:"deferred"})}catch(o){throw o instanceof w?o:new w("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var dG;exports.AgentSendHistoryRepository=void 0;var xm=M(()=>{h();st();It();Rt();Tt();Ct();dG=50,exports.AgentSendHistoryRepository=class extends be{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=`${t.dbRoot}/.crewx/crewx.db`);}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(){let t=this.resolveDbPath(),n=K(t);try{return je(n.db,t),n}catch(r){throw n.close(),r}}recordAccepted(t){if(t.actorKind!=="human"||!t.workspaceId||!t.actorId||!t.agentId)return false;let n;try{n=this.openHandle();let r=t.acceptedAt??new Date().toISOString();return n.db.insert(Yn).values({workspace_id:t.workspaceId,actor_id:t.actorId,agent_id:t.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[Yn.workspace_id,Yn.actor_id,Yn.agent_id],set:{last_accepted_at:drizzleOrm.sql`MAX(${Yn.last_accepted_at}, excluded.last_accepted_at)`}}).run(),!0}catch(r){return console.error("[AgentSendHistoryRepository] Failed to record accepted agent send",r),false}finally{n?.close();}}findRecentAgents(t,n){let r;try{return r=this.openHandle(),r.db.select({agentId:Yn.agent_id,lastAcceptedAt:Yn.last_accepted_at}).from(Yn).where(drizzleOrm.and(drizzleOrm.eq(Yn.workspace_id,t),drizzleOrm.eq(Yn.actor_id,n))).orderBy(drizzleOrm.desc(Yn.last_accepted_at),drizzleOrm.asc(Yn.agent_id)).limit(dG).all()}catch(o){throw o instanceof w?o:new w("DB_ERROR","Failed to find recent agent sends",o)}finally{r?.close();}}};});function Dm(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function cG(e,t){return typeof e=="string"&&e.length>0?e:typeof t=="string"&&t.length>0?t:null}function _T(e){if(typeof e.provider!="string"||e.provider.length===0)return;let n=e.taskLogRepository.readLogs(e.taskId)?.entries.filter(p=>p.level==="stdout").map(p=>p.message).join(`
73
73
  `)??"";if(!n.trim())return;let r=tc(e.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let i=cG(o?.model,e.model),s=o?.usage;if(!s)return {stdout:n,adapter:r};let a=Dm(s.inputTokens),d=Dm(s.outputTokens),c=Dm(s.cachedInputTokens),l=Of(Dm(s.costUsd),a,d,c,i);return a!==0||d!==0||c!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:a,outputTokens:d,cachedInputTokens:c,costUsd:l,model:i}}:{stdout:n,adapter:r}}var AT=M(()=>{h();Ng();Zs();});function za(e){let t=new Set;for(let n of e)for(let r of lG.get(n)??[n])t.add(r);return [...t]}function IT(e){if(e)try{let t=JSON.parse(e);if(typeof t!="object"||t===null||Array.isArray(t))return;let n=t.terminalReason;return typeof n=="string"&&uG.has(n)?n:void 0}catch{return}}function Qn(e){let t=IT(e.metadata);if(t)return t;if(e.status==="runner_lost")return "runner_lost";if(e.status==="stopped")return "user_stop";if(e.status==="failed"&&typeof e.error=="string"){if(exports.LEGACY_TASK_TERMINAL_ERROR_PATTERNS.stopped.test(e.error))return "user_stop";if(exports.LEGACY_TASK_TERMINAL_ERROR_PATTERNS.runnerLost.test(e.error))return "runner_lost"}}function Dt(e){switch(e.status){case "stopped":case "pending":case "running":case "paused":case "success":return e.status;case "completed":case "done":return "success";case "error":case "runner_lost":return "failed";case "failed":{let t=IT(e.metadata);return t==="user_stop"?"stopped":t?"failed":typeof e.error=="string"&&exports.LEGACY_TASK_TERMINAL_ERROR_PATTERNS.stopped.test(e.error)?"stopped":"failed"}default:return e.status}}function pG(e){if(!e)return {};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}catch{return {}}}function Ka(e){let t=Dt(e);return e.status==="runner_lost"&&IT(e.metadata)===void 0?{...e,status:t,metadata:JSON.stringify({...pG(e.metadata),terminalReason:"runner_lost"})}:{...e,status:t}}function PO(e){return Dt(e)==="failed"&&Qn(e)!=="runner_lost"}exports.TASK_TERMINAL_STATUSES=void 0;exports.TASK_TERMINAL_STORED_STATUSES=void 0;var lG;exports.LEGACY_TASK_TERMINAL_ERROR_PATTERNS=void 0;var uG,ws=M(()=>{h();exports.TASK_TERMINAL_STATUSES=["success","failed","stopped"],exports.TASK_TERMINAL_STORED_STATUSES=["success","completed","done","failed","error","stopped","runner_lost"],lG=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);exports.LEGACY_TASK_TERMINAL_ERROR_PATTERNS={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},uG=new Set(["user_stop","runner_lost","launch_failed"]);});function TT(e,t,n=1){let r=process.env[e];if(r===void 0||r==="")return t;let o=Number(r);return !Number.isFinite(o)||o<=0?t:Math.max(n,Math.trunc(o))}function Ya(){return TT("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Rs(){return TT("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function Ac(){return TT("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function _c(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):0}function Lm(e){let t=typeof e=="object"&&e!==null&&"code"in e?String(e.code):e instanceof Error?e.name:typeof e;console.warn(`[crewx] task heartbeat write failed (${t}); execution continues`);}function fG(e){return e?{id:e.id,status:e.status,run_epoch:e.run_epoch,stop_requested_at:e.stop_requested_at,stop_requested_epoch:e.stop_requested_epoch,pid:e.pid,metadata:e.metadata,started_at:e.started_at,duration_ms:e.duration_ms}:null}function OO(e,t){return !!e.stop_requested_at&&_c(e.stop_requested_epoch)===_c(t)}function Mm(e,t){let n=_c(t.runEpoch);if(!(t.writeHeartbeat===false?true:e.heartbeatTask({id:t.taskId,runEpoch:n})))return {accepted:false,row:null};let o=fG(e.getTask(t.taskId));return !o||o.status!=="running"||_c(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function xO(e,t){let n=exports.taskHeartbeatRegistry.get(e);return !n||t&&n!==t?false:(clearInterval(n.timer),exports.taskHeartbeatRegistry.delete(e),true)}function ET(e,t){let n=exports.taskHeartbeatRegistry.get(e);return !n||t!==void 0&&n.runEpoch!==_c(t)?false:xO(e,n)}function DO(e,t){let n=_c(t.runEpoch);ET(t.taskId);let r=true,o=null;try{let c=Mm(e,{...t,runEpoch:n});r=c.accepted,o=c.row;}catch(c){Lm(c);}if(!r)return false;let i=Ya(),s=Math.min(i,1e3),a=setInterval(()=>{let c=exports.taskHeartbeatRegistry.get(t.taskId);if(!(!c||c.timer!==a))try{c.heartbeatElapsedMs+=s;let l=c.heartbeatElapsedMs>=i,u=Mm(e,{taskId:t.taskId,runEpoch:n,writeHeartbeat:l});if(!u.accepted){xO(t.taskId,c);return}l&&(c.heartbeatElapsedMs%=i,c.lastHeartbeatAt=Date.now()),u.row&&OO(u.row,n)&&!c.stopRequested&&(c.stopRequested=!0,t.onStopRequested&&Promise.resolve(t.onStopRequested(u.row)).catch(Lm));}catch(l){Lm(l);}},s),d={timer:a,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return exports.taskHeartbeatRegistry.set(t.taskId,d),typeof a=="object"&&a!==null&&"unref"in a&&a.unref(),o&&OO(o,n)&&t.onStopRequested&&(d.stopRequested=true,Promise.resolve(t.onStopRequested(o)).catch(Lm)),true}exports.TASK_HEARTBEAT_INTERVAL_MS=void 0;exports.TASK_HEARTBEAT_STALE_MS=void 0;exports.TASK_HEARTBEAT_HARD_STALE_MS=void 0;exports.TASK_STOP_POLL_INTERVAL_MS=void 0;exports.taskHeartbeatRegistry=void 0;var Ic=M(()=>{h();exports.TASK_HEARTBEAT_INTERVAL_MS=1e4,exports.TASK_HEARTBEAT_STALE_MS=3e4,exports.TASK_HEARTBEAT_HARD_STALE_MS=18e5,exports.TASK_STOP_POLL_INTERVAL_MS=1e3;exports.taskHeartbeatRegistry=new Map;});function $m(e,t=Date.now(),n=exports.TASK_STOP_DEFAULT_GRACE_MS){let r=e?Date.parse(e):Number.NaN,o=typeof t=="number"?t:Date.parse(t),i=RT(n,exports.TASK_STOP_DEFAULT_GRACE_MS,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>i?"forced":"cooperative"}function vT(e){let t=[],n=typeof e.pid=="number"&&e.pid>0?e.pid:void 0;n!==void 0&&t.push({pid:n,startedAt:e.pid_started_at});let r=FO(e.metadata),o=r.ownership==="runner"&&typeof r.providerPid=="number"&&Number.isSafeInteger(r.providerPid)&&r.providerPid>0?r.providerPid:void 0;if(o!==void 0&&o!==n){let i=r.providerPidStartedAt;t.push({pid:o,startedAt:typeof i=="string"?i:null});}return t}async function CT(e,t={}){if(e.pid===process.pid||e.pid===process.ppid)return {verdict:"unproven",ownership:"not_owned",reason:"pid is this process or its parent"};let n=typeof e.startedAt=="string"?Date.parse(e.startedAt):Number.NaN,r=Number.isFinite(n),o=t.legacyStartBoundaryMs;if(!r&&o===void 0)return {verdict:"unproven",ownership:"unknown",reason:"no start time recorded"};let i=t.processControlOptions??{},s=t.processControl?.checkProcessOwnershipAsync??XA,a=t.processControl?.readProcessIdentityAsync??vv,d;try{d=await s(e.pid,t.ownershipMarkers??exports.TASK_STOP_OWNED_PROCESS_MARKERS,i);}catch{d="unknown";}let c;try{c=await a(e.pid,i);}catch{c={status:"unknown"};}if(c.status==="not_found")return {verdict:"unproven",ownership:"not_found",reason:"process is no longer running"};if(c.status!=="found")return {verdict:"unproven",ownership:"unknown",reason:"start time could not be read"};let l=new Date(c.startedAtMs).toISOString();if(r){if(Math.abs(c.startedAtMs-n)>Ag)return {verdict:"reused",reason:`started ${l}, not the recorded ${e.startedAt}`}}else return o!==void 0&&c.startedAtMs>o?{verdict:"reused",reason:`started ${l}, after the row's last heartbeat`}:{verdict:"unproven",ownership:"unknown",reason:"no start time recorded and it started before the row's last heartbeat"};return d!=="owned"?{verdict:"unproven",ownership:d,reason:"command line has no owned marker"}:c.groupId!==null&&c.groupId!==e.pid?{verdict:"unproven",ownership:"not_owned",reason:"pid does not lead its process group"}:{verdict:"owned"}}async function BO(e,t={}){let n=await CT(e,t);return n.verdict==="owned"?"owned":n.verdict==="reused"?"not_owned":n.ownership}function RT(e,t,n){return e===void 0||!Number.isFinite(e)?t:Math.max(n,Math.trunc(e))}function FO(e){if(!e)return {};try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}catch{}return {}}function gG(e){if(!e)return;let t=FO(e.metadata).stopMethod;return t==="cooperative"||t==="forced"?t:void 0}function Vo(e,t){if(!e)return {status:"not_running",finalStatus:"not_running",...t?{pid:t}:{}};let n=typeof e.pid=="number"&&e.pid>0?e.pid:t;if(e.status==="stopped"){let r=gG(e);return {status:"stopped",finalStatus:e.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:e.status,...n?{pid:n}:{}}}function HO(e,t,n="Process owner could not be verified"){let r=t??(e.pid&&e.pid>0?e.pid:void 0);return {status:"ownership_unverified",finalStatus:e.status,...r?{pid:r}:{},error:n}}function wn(e,t,n){let r=n??(e?.pid&&e.pid>0?e.pid:void 0);return {status:"failed",finalStatus:e?.status??null,...r?{pid:r}:{},error:t}}function kT(e,t){return wn(e,exports.INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED,t)}function mG(e,t){if(!e.heartbeat_at)return false;let n=Date.parse(e.heartbeat_at);return Number.isFinite(n)?t-n<=Rs():false}function hG(e){return {...e.processControlOptions,...e.platform?{platform:e.platform}:{}}}function yG(e,t,n){let r=e.getTask(t);if(!r||r.status!=="running")return Vo(r,n)}async function _G(e,t,n,r){let o=Date.now()+n;for(;;){let i=yG(e,t);if(i)return i;let s=o-Date.now();if(s<=0)return;await new Promise(a=>{setTimeout(a,Math.min(r,s));});}}async function LO(e,t,n){let r=new Date().toISOString(),o={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},i=e.requestTaskStop({id:t,requestedAt:r,...o}),s=e.getTask(t);if(!i.accepted){if(i.status==="pending"){let k=e.stopPendingTask(t,void 0,void 0,{...o,at:r}),T=e.getTask(t);if(k||!T||T.status!=="running")return Vo(T);if(i=e.requestTaskStop({id:t,requestedAt:r,...o}),!i.accepted&&i.status!=="running"||!i.accepted&&!i.alreadyRequestedAt)return Vo(e.getTask(t))}else if(!(i.status==="running"&&i.alreadyRequestedAt))return Vo(s)}let a=i.runEpoch,d=RT(n.graceMs,exports.TASK_STOP_DEFAULT_GRACE_MS,0),c=RT(n.pollMs,exports.TASK_STOP_DEFAULT_POLL_MS,1),l=await _G(e,t,d,c);if(l)return l;let u=e.getTask(t);if(!u||u.status!=="running")return Vo(u);let p=vT(u),f=p.map(k=>k.pid),g=f[0];if(!g){let k=e.finalizeTaskStop({id:t,runEpoch:a,method:"forced"}),T=e.getTask(t);return k||T?.status!=="running"?Vo(T):wn(T,"Failed to finalize task stop")}let y=hG(n);if(!mG(u,Date.now())){for(let k of p)if(await BO(k,{ownershipMarkers:n.ownershipMarkers,processControl:n.processControl,processControlOptions:y})!=="owned")return HO(u)}let _=n.processControl?.terminateProcessTree??an;for(let k of f){let T;try{T=await _(k,{...y,signal:cs});}catch(R){T={status:"failed",pid:k,method:y.platform==="win32"?"taskkill":"process-group",error:R instanceof Error?R.message:String(R)};}if(T.status==="failed")return wn(e.getTask(t),T.error??"Failed to terminate process tree")}let A=e.finalizeTaskStop({id:t,runEpoch:a,method:"forced"}),I=e.getTask(t);return A||I?.status!=="running"?Vo(I,g):wn(I,"Task changed before stop was finalized")}function MO(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function UO(e){return Number.isSafeInteger(e)&&e>=0}function wT(e){return typeof e=="number"&&Number.isFinite(e)?Math.trunc(e):0}function AG(e){return {...e.processControlOptions,...e.platform?{platform:e.platform}:{}}}async function jO(e,t){let n=e.getTask(t.taskId);if(!n||n.status!=="running")return kT(n,MO(t.targetPid)?t.targetPid:void 0);if(!UO(t.sourceRunEpoch)||!UO(t.settleRunEpoch)||wT(n.run_epoch)!==t.settleRunEpoch)return wn(n,exports.INSTRUCTION_STOP_EPOCH_MISMATCH,t.targetPid);if(t.workspaceId!==void 0&&n.workspace_id!==t.workspaceId)return wn(n,exports.INSTRUCTION_STOP_WORKSPACE_MISMATCH,t.targetPid);let r=new Date().toISOString(),o;try{o=e.requestTaskStop({id:t.taskId,requestedAt:r,sourceRunEpoch:t.sourceRunEpoch,settleRunEpoch:t.settleRunEpoch,...t.workspaceId!==void 0?{workspaceId:t.workspaceId}:{}});}catch{return wn(n,exports.INSTRUCTION_STOP_REQUEST_FAILED,t.targetPid)}let i=e.getTask(t.taskId);if(!i||i.status!=="running")return kT(i,t.targetPid);if(o.runEpoch!==t.settleRunEpoch||wT(i.run_epoch)!==t.settleRunEpoch)return wn(i,exports.INSTRUCTION_STOP_EPOCH_MISMATCH,t.targetPid);if(t.workspaceId!==void 0&&i.workspace_id!==t.workspaceId)return wn(i,exports.INSTRUCTION_STOP_WORKSPACE_MISMATCH,t.targetPid);if(!MO(t.targetPid))return wn(i,exports.INSTRUCTION_STOP_TARGET_PID_MISSING);let s=AG(t);if(await BO({pid:t.targetPid,startedAt:i.pid_started_at},{ownershipMarkers:t.ownershipMarkers,processControl:t.processControl,processControlOptions:s})!=="owned")return HO(i,t.targetPid);let d=e.getTask(t.taskId);if(!d||d.status!=="running")return kT(d,t.targetPid);if(wT(d.run_epoch)!==t.settleRunEpoch)return wn(d,exports.INSTRUCTION_STOP_EPOCH_MISMATCH,t.targetPid);if(t.workspaceId!==void 0&&d.workspace_id!==t.workspaceId)return wn(d,exports.INSTRUCTION_STOP_WORKSPACE_MISMATCH,t.targetPid);let c=t.processControl?.terminateProcessTree??an,l;try{l=await c(t.targetPid,{...s,signal:cs});}catch{return wn(e.getTask(t.taskId),exports.INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED,t.targetPid)}if(l.status==="failed")return wn(e.getTask(t.taskId),exports.INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED,t.targetPid);let u;try{u=e.finalizeTaskStop({id:t.taskId,runEpoch:t.settleRunEpoch,method:"forced"});}catch{return wn(e.getTask(t.taskId),exports.INSTRUCTION_STOP_SETTLE_CAS_FAILED,t.targetPid)}return u?Vo(e.getTask(t.taskId),t.targetPid):wn(e.getTask(t.taskId),exports.INSTRUCTION_STOP_SETTLE_CAS_FAILED,t.targetPid)}function Vm(e,t,n={}){if(typeof e=="string"){let r=e,o=t??{};return Promise.resolve().then(()=>(co(),$O)).then(({TaskRepository:i})=>LO(new i,r,o))}return LO(e,t,n)}exports.TASK_STOP_DEFAULT_GRACE_MS=void 0;exports.TASK_STOP_DEFAULT_POLL_MS=void 0;exports.TASK_STOP_OWNED_PROCESS_MARKERS=void 0;exports.INSTRUCTION_STOP_TARGET_PID_MISSING=void 0;exports.INSTRUCTION_STOP_EPOCH_MISMATCH=void 0;exports.INSTRUCTION_STOP_WORKSPACE_MISMATCH=void 0;exports.INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED=void 0;exports.INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED=void 0;exports.INSTRUCTION_STOP_SETTLE_CAS_FAILED=void 0;exports.INSTRUCTION_STOP_REQUEST_FAILED=void 0;var Wm=M(()=>{h();gi();Ic();exports.TASK_STOP_DEFAULT_GRACE_MS=5e3,exports.TASK_STOP_DEFAULT_POLL_MS=250;exports.TASK_STOP_OWNED_PROCESS_MARKERS=["crewx","claude","codex","opencode","grok","node"];exports.INSTRUCTION_STOP_TARGET_PID_MISSING="INSTRUCTION_STOP_TARGET_PID_MISSING",exports.INSTRUCTION_STOP_EPOCH_MISMATCH="INSTRUCTION_STOP_EPOCH_MISMATCH",exports.INSTRUCTION_STOP_WORKSPACE_MISMATCH="INSTRUCTION_STOP_WORKSPACE_MISMATCH",exports.INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",exports.INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",exports.INSTRUCTION_STOP_SETTLE_CAS_FAILED="INSTRUCTION_STOP_SETTLE_CAS_FAILED",exports.INSTRUCTION_STOP_REQUEST_FAILED="INSTRUCTION_STOP_REQUEST_FAILED";});var $O={};Pl($O,{CANONICAL_USER_STOP_ERROR:()=>exports.CANONICAL_USER_STOP_ERROR,DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>exports.DEFAULT_TASK_REAPER_TICK_INTERVAL_MS,HOST_SHUTDOWN_TERMINAL_ERROR:()=>GO,PENDING_ADOPT_GRACE_MS:()=>KO,PID_NULL_REAP_GRACE_MS:()=>$T,RATED_TASK_EXCERPT_MAX_CHARS:()=>exports.RATED_TASK_EXCERPT_MAX_CHARS,RATED_TASK_LIST_MAX_LIMIT:()=>exports.RATED_TASK_LIST_MAX_LIMIT,TASK_HEARTBEAT_HARD_STALE_MS:()=>exports.TASK_HEARTBEAT_HARD_STALE_MS,TASK_HEARTBEAT_INTERVAL_MS:()=>exports.TASK_HEARTBEAT_INTERVAL_MS,TASK_HEARTBEAT_STALE_MS:()=>exports.TASK_HEARTBEAT_STALE_MS,TASK_RATINGS:()=>exports.TASK_RATINGS,TaskRatingError:()=>exports.TaskRatingError,TaskRepository:()=>exports.TaskRepository,WORKFLOW_ANCHOR_TASK_KINDS:()=>exports.WORKFLOW_ANCHOR_TASK_KINDS,buildRatedTasksCountQuery:()=>YO,buildRatedTasksQuery:()=>XO,countRatedTasks:()=>JT,hasRecordedUsage:()=>Yu,isWorkflowAnchorTaskKind:()=>Ja,listRatedTasks:()=>qT,mergeTerminalReason:()=>Xu,resolveTaskHeartbeatHardStaleMs:()=>Ac,resolveTaskHeartbeatIntervalMs:()=>Ya,resolveTaskHeartbeatStaleMs:()=>Rs,setTaskRating:()=>WT});function uo(e){return Ka(e)}function DT(e){return Ka(e)}function LT(){return drizzleOrm.or(...exports.WORKFLOW_ANCHOR_TASK_KINDS.map(e=>drizzleOrm.like(m.metadata,`%"kind":"${e}"%`)))}function VO(){return drizzleOrm.and(...exports.WORKFLOW_ANCHOR_TASK_KINDS.map(e=>drizzleOrm.notLike(m.metadata,`%"kind":"${e}"%`)))}function UT(e=m.model,t=m.metadata){let n=drizzleOrm.sql`
74
74
  CASE
75
75
  WHEN ${e} LIKE 'claude-%' OR ${e} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
@@ -397,7 +397,7 @@ ${e??""}
397
397
  `||e==="\r"||e==="\f"}function bq(e){if(!e)return false;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122||t>=48&&t<=57||e==="_"||e===":"||e==="-"}function vq(e){return e===void 0||_u(e)||e==="/"||e===">"}function bC(e,t){let n=e[t],r=t+1;for(;r<e.length;){if(e[r]===n)return {end:r+1,value:e.slice(t+1,r)};r++;}return {end:e.length,value:e.slice(t+1)}}function Cq(e,t){if(e[t]==='"'||e[t]==="'")return bC(e,t);let n=t;for(;n<e.length&&!_u(e[n])&&e[n]!==">";)n++;return {end:n,value:e.slice(t,n)}}function Pq(e,t){let n=Object.create(null),r=t+Dg.length,o=false;for(;r<e.length;){let i=e[r];if(i===">")return {end:r+1,closed:true,attrs:n,privileged:o};if(_u(i)||i==="/"){r++;continue}if(i==='"'||i==="'"){r=bC(e,r).end;continue}let s=r;for(;r<e.length&&bq(e[r]);)r++;if(r===s){r++;continue}let a=e.slice(s,r);for(a==="proof"&&(o=true);r<e.length&&_u(e[r]);)r++;if(e[r]!=="="){n[a]="";continue}for(r++;r<e.length&&_u(e[r]);)r++;let d=Cq(e,r);n[a]=d.value,r=d.end;}return {end:e.length,closed:false,attrs:n,privileged:o}}function wI(e,t){let n=Pq(e,t);return {start:t,end:n.end,raw:e.slice(t,n.end),closed:n.closed,attrs:n.attrs,privileged:n.privileged}}function Au(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(Dg,n);if(r<0)break;if(!vq(e[r+Dg.length])){n=r+Dg.length;continue}let o=wI(e,r);if(t.push(o),!o.closed)break;n=o.end;}return t}function vC(e){return e&&Au(e).find(r=>!!r.attrs.run_id?.trim())?.attrs.run_id?.trim()||void 0}Ot();Ca();Fa();var IP="[workflow card omitted from AI context]",jI="[workflow UI instance omitted from AI context]",h1=/\{\s*"instanceId"\s*:\s*"uic_[A-Za-z0-9_-]+"\s*\}/g;function gm(e){return typeof e=="string"?e.replace(h1,jI):""}function mm(e){if(typeof e!="string"||e.length===0)return "";let t="",n=0;for(let r of Au(e))if(t+=e.slice(n,r.start),t+=r.privileged?IP:r.raw,n=r.end,!r.closed)break;return t+=e.slice(n),t}function y1(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function _1(e,t){if(typeof e!="string")return "";let n=t?mm(e):e,r=t?gm(n):n;return y1(r)}function $I(e){return e.map(t=>({...t,text:_1(t.text,t.isAssistant)}))}function TP(e,t){let n=$I(e);if(!t||t.length===0)return n;let r=[];for(let o of t)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=_e(o),a=JSON.stringify(s);if(typeof a!="string"||Le(a)>64*1024)continue;r.push(s);}catch{}return r.length===0?n:[...n,{text:`CrewX workflow context:
398
398
  ${JSON.stringify(r)}`,isAssistant:true}]}function VI(e){return $I(e.messages.map(t=>({id:t.id,text:t.text,isAssistant:t.isAssistant,taskId:t.taskId,timestamp:t.timestamp,metadata:t.metadata,files:void 0})))}h();ds();As();co();var LG=new Set(["Read","Grep","Find","Glob"]),MG=["git status","git log","git branch","git diff --stat","git show","git remote","git rev-parse","git ls-files","pwd","ls ","echo ","cat ","head ","tail ","crewx skill tsserver find","crewx skill tsserver refs","crewx skill tsserver type","npx skill tsserver find","npx skill tsserver refs","npx skill tsserver type","crewx memory index","crewx memory find","crewx memory get","crewx doc toc","crewx doc section","crewx doc status","crewx search","crewx agent ls","crewx agent list"],UG=[/\bgit\s+(commit|push|pull|merge|rebase|reset|checkout|switch|add|rm)\b/,/\bnpm\s+(install|ci|publish|run\s+(test|lint|build))\b/,/\bnpx\s+tsc\b/,/\bpnpm\s+(install|run)\b/,/\bvitest\b/,/\bjest\b/],BG=8e3,FG=100,HG=3,jG=Number.MAX_SAFE_INTEGER,XT=3e3;function ed(){return typeof performance<"u"?performance.now():Date.now()}function $G(e){let t=e.toLowerCase();return t==="bash"||t==="terminal"?"Bash":t==="read"||t==="view"?"Read":t==="edit"||t==="apply_patch"?"Edit":t==="write"?"Write":t==="grep"||t==="rg"?"Grep":t==="glob"||t==="find"?"Find":e}function VG(e,t){if(LG.has(e))return true;if(e!=="Bash"||!t)return false;let n=t.split(`
399
399
  `)[0].trimStart();return UG.some(r=>r.test(n))?false:MG.some(r=>n.startsWith(r))}function Sc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function WG(e,t,n){if(e!=="Read"||!t)return "ok";let o=t.split(`
400
- `).find(i=>i.trim()&&!i.startsWith("Read "))?.trim()??t.trim();if(!o)return "unknown";try{let i=pn__namespace.statSync(o);if(n){let s=Date.parse(n);if(!Number.isNaN(s)&&i.mtimeMs>s)return "stale"}return "ok"}catch{return "unknown"}}var qG=new Set([...Object.keys(exports.BUILTIN_ADAPTERS),"gemini"]);function JG(e){let t=e?.split("/").pop()?.trim();return t&&qG.has(t)?t:void 0}function GG(e){if(e.type==="system"&&e.subtype==="init")return true;if(e.type!=="assistant"&&e.type!=="user")return false;let t=e.message;return typeof t=="object"&&t!==null&&Array.isArray(t.content)}function zG(e){let t={types:new Set,claudeShaped:false,typedRows:0};for(let n of e)try{let r=JSON.parse(n);if(typeof r!="object"||r===null||typeof r.type!="string"||!r.type)continue;t.types.add(r.type),t.typedRows+=1,!t.claudeShaped&&GG(r)&&(t.claudeShaped=!0);}catch{}return t}function KG(e){let{types:t}=e;return t.has("turn.started")||t.has("thread.started")?"codex":t.has("assistant.message_delta")?"copilot":t.has("step_start")&&t.has("step_finish")?"opencode":t.has("system")&&t.has("result")?"claude":t.has("init")&&t.has("message")?"gemini":t.has("result")&&t.has("assistant")||e.claudeShaped?"claude":t.has("tool_call")||t.has("tool_call_update")?"grok":null}function XG(e,t){if(!Array.isArray(e))return {entries:[],readable:true};let n=e,r=n.filter(d=>d.level==="stdout"&&d.message).map(d=>d.message),o=zG(r),i=r.length>0?JG(t)??KG(o):null,s;try{s=YG(n,i);}catch{return {entries:[],readable:false}}let a=s.length>0||r.length===0||i!==null&&o.typedRows>0;return {entries:s,readable:a}}function YG(e,t){let n=[],r=FA(t??void 0);for(let[s,a]of e.entries())a.level==="info"&&a.message?n.push(...no(a.message,a.timestamp)):a.level==="stdout"&&a.message&&t&&n.push(...r.parse(a.timestamp??"",a.message,s));let o=new Map,i=[];for(let s of n)if(s.type==="tool_use"){let a={tool:$G(s.toolName??""),input:s.toolInput??null,result:null,isError:false},d=s.toolUseId;if(d){if(o.has(d)){o.get(d).input=a.input;continue}o.set(d,a);}i.push(a);}else if(s.type==="tool_result"){if(s.toolUseId&&o.has(s.toolUseId)){let a=o.get(s.toolUseId);a.isError=s.isError===true,a.result=s.resultPreview??null;}else if(t!=="codex"){for(let a=i.length-1;a>=0;a--)if(i[a].result===null){i[a].isError=s.isError===true,i[a].result=s.resultPreview??null;break}}}return i}function QG(e,t){let n=[];for(let r of e){let o=r.tool==="Bash"?r.input?.split(`
400
+ `).find(i=>i.trim()&&!i.startsWith("Read "))?.trim()??t.trim();if(!o)return "unknown";try{let i=pn__namespace.statSync(o);if(n){let s=Date.parse(n);if(!Number.isNaN(s)&&i.mtimeMs>s)return "stale"}return "ok"}catch{return "unknown"}}var qG=new Set([...Object.keys(exports.BUILTIN_ADAPTERS),"gemini"]);function JG(e){let t=e?.split("/").pop()?.trim();return t&&qG.has(t)?t:void 0}function GG(e){if(e.type==="system"&&e.subtype==="init")return true;if(e.type!=="assistant"&&e.type!=="user")return false;let t=e.message;return typeof t=="object"&&t!==null&&Array.isArray(t.content)}function zG(e){let t={types:new Set,claudeShaped:false,typedRows:0};for(let n of e)try{let r=JSON.parse(n);if(typeof r!="object"||r===null||typeof r.type!="string"||!r.type)continue;t.types.add(r.type),t.typedRows+=1,!t.claudeShaped&&GG(r)&&(t.claudeShaped=!0);}catch{}return t}function KG(e){let{types:t}=e;return t.has("turn.started")||t.has("thread.started")?"codex":t.has("assistant.message_delta")?"copilot":t.has("step_start")&&t.has("step_finish")?"opencode":t.has("system")&&t.has("result")?"claude":t.has("init")&&t.has("message")?"gemini":t.has("result")&&t.has("assistant")||e.claudeShaped?"claude":t.has("tool_call")||t.has("tool_call_update")?"grok":null}function XG(e,t){if(!Array.isArray(e))return {entries:[],readable:true};let n=e,r=n.filter(d=>d.level==="stdout"&&d.message).map(d=>d.message),o=zG(r),i=r.length>0?JG(t)??KG(o):null,s;try{s=YG(n,i);}catch{return {entries:[],readable:false}}let a=s.length>0||r.length===0||i!==null&&o.typedRows>0;return {entries:s,readable:a}}function YG(e,t){let n=[],r=FA(t??void 0);for(let[s,a]of e.entries())if(a.level==="info"&&a.message)n.push(...no(a.message,a.timestamp));else if(a.level==="stdout"&&a.message&&t){let d=typeof a.seq=="number"&&Number.isFinite(a.seq)?a.seq:s;n.push(...r.parse(a.timestamp??"",a.message,d));}let o=new Map,i=[];for(let s of n)if(s.type==="tool_use"){let a={tool:$G(s.toolName??""),input:s.toolInput??null,result:null,isError:false},d=s.toolUseId;if(d){if(o.has(d)){o.get(d).input=a.input;continue}o.set(d,a);}i.push(a);}else if(s.type==="tool_result"){if(s.toolUseId&&o.has(s.toolUseId)){let a=o.get(s.toolUseId);a.isError=s.isError===true,a.result=s.resultPreview??null;}else if(t!=="codex"){for(let a=i.length-1;a>=0;a--)if(i[a].result===null){i[a].isError=s.isError===true,i[a].result=s.resultPreview??null;break}}}return i}function QG(e,t){let n=[];for(let r of e){let o=r.tool==="Bash"?r.input?.split(`
401
401
  `)[0]?.slice(0,150)??null:r.input?.slice(0,150)??null,i=VG(r.tool,r.input)&&!r.isError&&r.result!==null;n.push({tool:r.tool,cmd:o,result:r.result,status:WG(r.tool,r.input,t),reusable:i});}return n}function ZG(e,t){try{return e.readLogs(t)?.entries??[]}catch{return []}}function ez(e,t){try{let n=e.findTaskStatus(t)?.metadata;if(!n)return;let r=JSON.parse(n);if(typeof r!="object"||r===null||Array.isArray(r))return;let o=r.provider;return typeof o=="string"?o:void 0}catch{return}}function eN(e){let t=e.entry,n=`tool="${Sc(t.tool)}"`,r=t.cmd?` cmd="${Sc(t.cmd)}"`:"",o="";if(t.reusable&&(o=t.status==="stale"?' reused="stale"':' reused="ok"'),t.reusable&&t.status==="stale")return [` <entry ${n}${r}${o}>\u26A0\uFE0F changed since \u2014 re-read</entry>`];if(t.result){let i=mm(t.result),s=Math.min(e.bodyCharsShown??i.length,i.length);return [` <entry ${n}${r}${o}>`,i.length>s?Sc(i.slice(0,s))+` \u2026 [truncated, ${s}/${i.length} chars shown]`:Sc(i)," </entry>"]}return [` <entry ${n}${r}${o} />`]}function tN(e){let t=["<activity_log>"],{entries:n,omissions:r,tokenCap:o,totalEntries:i}=e,s=r.reduce((a,d)=>a+d.count,0);if(n.length===0&&s===0)t.push(" <!-- no activity found in previous tasks -->");else if(t.push(" <!-- tool activity from previous tasks -->"),r.length>0){t.push(` <!-- activity_log_budget token_cap="${o}" included_entries="${n.length}" omitted_entries="${s}" total_entries="${i}" -->`);for(let a of r)t.push(` <!-- omitted_entries reason="${Sc(a.reason)}" count="${a.count}": ${Sc(a.message)} -->`);}return t.push("</activity_log>"),t}function nN(e){return eN(e).join(`
402
402
  `)}function zT(e){let t=tN(e);return e.entries.length>0&&t.splice(t.length-1,0,...e.entries.flatMap(n=>eN(n))),t}function tz(e){return typeof e!="number"||!Number.isFinite(e)||e<0?BG:Math.floor(e)}function nz(e,t,n){let r=Math.floor(t/FG),o=Math.pow(2,e+r);return !Number.isFinite(o)||o<=0?0:Math.floor(n/o)}function QO(e,t){let n=Math.pow(2,t+HG);return !Number.isFinite(n)||n<=0?0:Math.floor(e/n)}function KT(e,t,n,r){let o=e.result?.length??null,i=o===null?null:Math.min(o,Math.max(0,n));return {entry:e,newestIndex:t,bodyLimitChars:n,bodyCharsShown:o===null?null:Math.max(0,Math.min(r??i??0,i??0)),originalBodyChars:o}}function eh(e,t){let n=[];return e>0&&n.push({reason:"token_cap",count:e,message:"older entries omitted after the per-task token cap was reached"}),t>0&&n.push({reason:"repository_limit",count:t,message:"older entries omitted by the explicit repository safety limit before budgeting"}),n}function rN(e){let t=eh(e.omittedByTokenCap,e.repositoryLimitOmitted);return zT({entries:e.entries,omissions:t,tokenCap:e.tokenCap,totalEntries:e.totalEntries}).join(`
403
403
  `)}function vs(e,t){let n=e(t);return !Number.isFinite(n)||n<0?0:Math.floor(n)}function rz(e){let{entry:t,bodyLimitChars:n}=e;if(!t.result)return null;let r=Math.min(t.result.length,Math.max(0,n)),o=y=>{let _=KT(t,e.newestIndex,n,y),A=`${nN(_)}
@@ -29,7 +29,7 @@ ${r.join(`
29
29
  OR
30
30
  (${t.status} IN ('deferred', 'failed') AND ${t.code} IS NOT NULL
31
31
  AND ${t.to_revision} IS NULL)
32
- )`)}));});var ji=x(()=>{_();sqliteCore.sqliteTable("ui_definition_archive",{definition_hash:sqliteCore.text("definition_hash").primaryKey().notNull(),definition_json:sqliteCore.text("definition_json").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({definitionHashCheck:sqliteCore.check("ui_definition_archive_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:sqliteCore.check("ui_definition_archive_definition_json_ck",drizzleOrm.sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:sqliteCore.check("ui_definition_archive_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`)}));});var Ki,Ji=x(()=>{_();Ki=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},t=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${t.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${t.stage_index} >= 1`)})),sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>Ki.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>Ki.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},t=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var ys,Es,v,Rs=x(()=>{_();ys=["THREAD_STATE","THREAD_PRIORITY"],Es=["gray","blue","violet","green","amber","orange","red","pink"],v=sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.code_group,t.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${t.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var Vi,Xi,Yi,Qi,Zi,G,F,H,ea=x(()=>{_();yn();Vi=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Xi=["user","agent","system"],Yi=["auto","manual"],Qi=["decision","judgment","issue","result","pivot"],Zi=["queued","running","completed","failed"],G=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),type:sqliteCore.text("type").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),payload_json:sqliteCore.text("payload_json").notNull(),created_at:sqliteCore.text("created_at").notNull(),actor_id:sqliteCore.text("actor_id"),task_id:sqliteCore.text("task_id"),highlight_id:sqliteCore.text("highlight_id")},t=>({typeCheck:sqliteCore.check("thread_events_type_ck",drizzleOrm.sql`${t.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:sqliteCore.check("thread_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:sqliteCore.check("thread_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:sqliteCore.index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:sqliteCore.index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:sqliteCore.uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),F=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),request_id:sqliteCore.text("request_id").notNull(),status:sqliteCore.text("status").notNull(),detector_version:sqliteCore.text("detector_version").notNull(),requested_at:sqliteCore.text("requested_at").notNull(),started_at:sqliteCore.text("started_at"),completed_at:sqliteCore.text("completed_at"),error_code:sqliteCore.text("error_code"),previous_auto_count:sqliteCore.integer("previous_auto_count"),new_auto_count:sqliteCore.integer("new_auto_count")},t=>({statusCheck:sqliteCore.check("thread_highlight_runs_status_ck",drizzleOrm.sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:sqliteCore.check("thread_highlight_runs_counts_ck",drizzleOrm.sql`(${t.previous_auto_count} IS NULL OR ${t.previous_auto_count} >= 0) AND (${t.new_auto_count} IS NULL OR ${t.new_auto_count} >= 0)`),threadRequestUnique:sqliteCore.uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:sqliteCore.uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(drizzleOrm.sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:sqliteCore.index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),H=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),source:sqliteCore.text("source").notNull(),kind:sqliteCore.text("kind").notNull(),status:sqliteCore.text("status").notNull().default("active"),text:sqliteCore.text("text"),covers_from_task_id:sqliteCore.text("covers_from_task_id").notNull(),covers_to_task_id:sqliteCore.text("covers_to_task_id").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),agent_id:sqliteCore.text("agent_id"),source_task_id:sqliteCore.text("source_task_id"),detector_version:sqliteCore.text("detector_version"),content_fingerprint:sqliteCore.text("content_fingerprint"),dismissed_at:sqliteCore.text("dismissed_at")},t=>({sourceCheck:sqliteCore.check("thread_highlights_source_ck",drizzleOrm.sql`${t.source} IN ('auto', 'manual')`),kindCheck:sqliteCore.check("thread_highlights_kind_ck",drizzleOrm.sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:sqliteCore.check("thread_highlights_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:sqliteCore.check("thread_highlights_active_text_ck",drizzleOrm.sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:sqliteCore.check("thread_highlights_covers_ck",drizzleOrm.sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:sqliteCore.check("thread_highlights_auto_key_ck",drizzleOrm.sql`${t.source} = 'manual' OR (${t.source} = 'auto' AND ${t.source_task_id} IS NOT NULL AND ${t.detector_version} IS NOT NULL AND ${t.content_fingerprint} IS NOT NULL AND length(${t.source_task_id}) > 0 AND length(${t.detector_version}) > 0 AND length(${t.content_fingerprint}) > 0)`),threadStatusCreatedIndex:sqliteCore.index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:sqliteCore.index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:sqliteCore.uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(drizzleOrm.sql`${t.source} = 'auto'`)}));});var na=x(()=>{_();sqliteCore.sqliteTable("storage_metadata",{source_kind:sqliteCore.text("source_kind").notNull(),source_id:sqliteCore.text("source_id").notNull(),utc_ts:sqliteCore.text("utc_ts"),bytes:sqliteCore.integer("bytes").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:sqliteCore.index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteCore.sqliteTable("storage_metadata_state",{unit:sqliteCore.text("unit").primaryKey().notNull(),cursor_rowid:sqliteCore.integer("cursor_rowid").notNull().default(0),end_rowid:sqliteCore.integer("end_rowid"),complete:sqliteCore.integer("complete").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()});});var Se,ra=x(()=>{_();Se=sqliteCore.sqliteTable("agent_send_history",{workspace_id:sqliteCore.text("workspace_id").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),last_accepted_at:sqliteCore.text("last_accepted_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:sqliteCore.index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var ia,aa=x(()=>{_();yn();ar();sqliteCore.sqliteTable("sidebar_states",{workspace_id:sqliteCore.text("workspace_id").primaryKey().references(()=>ee.id,{onDelete:"cascade"}),revision:sqliteCore.integer("revision").notNull().default(0),rail_collapsed:sqliteCore.integer("rail_collapsed").notNull().default(0),seeded_at:sqliteCore.text("seeded_at").notNull()},t=>({railCollapsedCheck:sqliteCore.check("sidebar_states_rail_collapsed_ck",drizzleOrm.sql`${t.rail_collapsed} IN (0, 1)`)})),ia=sqliteCore.sqliteTable("sidebar_groups",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),name:sqliteCore.text("name").notNull(),color:sqliteCore.text("color").notNull(),collapsed:sqliteCore.integer("collapsed").notNull().default(0),position:sqliteCore.integer("position").notNull()},t=>({colorCheck:sqliteCore.check("sidebar_groups_color_ck",drizzleOrm.sql`${t.color} IN ('cyan', 'orange', 'purple', 'blue')`),collapsedCheck:sqliteCore.check("sidebar_groups_collapsed_ck",drizzleOrm.sql`${t.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:sqliteCore.index("idx_sidebar_groups_workspace_position").on(t.workspace_id,t.position)})),sqliteCore.sqliteTable("sidebar_tabs",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>ia.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})})),sqliteCore.sqliteTable("sidebar_closed_tabs",{id:sqliteCore.integer("id").primaryKey({autoIncrement:true}),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>ia.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull(),closed_at:sqliteCore.text("closed_at").notNull()},t=>({idxSidebarClosedTabsWorkspaceId:sqliteCore.index("idx_sidebar_closed_tabs_workspace_id").on(t.workspace_id,t.id)})),sqliteCore.sqliteTable("thread_reads",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),read_through_at:sqliteCore.text("read_through_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var da=x(()=>{_();sqliteCore.sqliteTable("schedule_runs",{id:sqliteCore.text("id").primaryKey(),schedule_id:sqliteCore.text("schedule_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),mode:sqliteCore.text("mode").notNull(),trigger:sqliteCore.text("trigger").notNull(),occurrence_key:sqliteCore.text("occurrence_key"),task_id:sqliteCore.text("task_id"),app_id:sqliteCore.text("app_id"),schedule_name:sqliteCore.text("schedule_name"),builtin_id:sqliteCore.text("builtin_id"),command:sqliteCore.text("command"),high_frequency:sqliteCore.integer("high_frequency").notNull().default(0),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),exit_code:sqliteCore.integer("exit_code"),signal:sqliteCore.text("signal"),started_at:sqliteCore.text("started_at").notNull(),finished_at:sqliteCore.text("finished_at"),duration_ms:sqliteCore.integer("duration_ms"),pid:sqliteCore.integer("pid"),host_pid:sqliteCore.integer("host_pid"),output_tail:sqliteCore.text("output_tail"),output_bytes:sqliteCore.integer("output_bytes"),output_truncated:sqliteCore.integer("output_truncated").notNull().default(0)},t=>({idx_schedule_runs_workspace_started:sqliteCore.index("idx_schedule_runs_workspace_started").on(t.workspace_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_schedule_started:sqliteCore.index("idx_schedule_runs_schedule_started").on(t.schedule_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_task_id:sqliteCore.index("idx_schedule_runs_task_id").on(t.task_id),idx_schedule_runs_running:sqliteCore.index("idx_schedule_runs_running").on(t.workspace_id,t.started_at).where(drizzleOrm.sql`${t.status} = 'running'`)}));});var ua=x(()=>{_();sqliteCore.sqliteTable("run_column_backfill",{name:sqliteCore.text("name").primaryKey(),cursor:sqliteCore.integer("cursor"),anchor_id:sqliteCore.text("anchor_id"),completed_at:sqliteCore.text("completed_at")});});var xt=x(()=>{_();ar();Wt();ki();wi();yn();Ri();Ii();Ai();bi();xi();vi();Di();Li();$i();Ui();Fi();Bi();Wi();ji();Ji();Rs();ea();na();ra();aa();da();ua();});function On(t){return typeof t=="string"&&lt.includes(t)}function ca(t){if(!t||!t.includes("workflow"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.workflowRunId;if(typeof r=="string"&&r!=="")return r;let s=n.workflow;if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let o=s.exec_id;if(typeof o=="string"&&o!=="")return o}return null}var lt,kr=x(()=>{_();lt=["workflow_card","workflow_ui_instance","workflow_run"];});var jt,Ns,la,xs=x(()=>{_();jt={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5-5":{input:4,cachedInput:.2,output:20},"claude-opus-5":{input:5,cachedInput:.5,output:25},"claude-opus-4-8":{input:5,cachedInput:.5,output:25},"claude-opus-4-7":{input:5,cachedInput:.5,output:25},"claude-opus-4-6":{input:5,cachedInput:.5,output:25},"claude-sonnet-5-5":{input:2,cachedInput:.1,output:10},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-5-5":{input:.1,cachedInput:.01,output:.5},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-6.1-sol":{input:2,cachedInput:.1,output:10},"gpt-6-sol":{input:2,cachedInput:.2,output:10},"gpt-6-luna":{input:.1,cachedInput:.01,output:.5},"gpt-5.6-sol":{input:4,cachedInput:.4,output:20},"gpt-5.6-terra":{input:2,cachedInput:.2,output:12},"gpt-5.6-luna":{input:.2,cachedInput:.02,output:1.2},"gpt-5.5":{input:5,cachedInput:.5,output:30},"gpt-5.4":{input:2.5,cachedInput:.25,output:15},"gpt-5.4-mini":{input:.75,cachedInput:.075,output:4.5},"gpt-5.3-codex":{input:1.75,cachedInput:.175,output:14},"gpt-5-mini":{input:.4,cachedInput:.1,output:1.6},"gpt-4.1":{input:2,cachedInput:.5,output:8},"gpt-4o":{input:2.5,cachedInput:1.25,output:10},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"gemini-3.7-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-3.6-flash":{input:1.5,cachedInput:.15,output:7.5},"grok-4.7":{input:2,cachedInput:.5,output:6},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},Ns=new Set(["gpt-5.3-codex-spark"]),la=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-haiku-5-5","claude-opus-4-6","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7","claude-opus-4-7[1m]","claude-opus-4-8","claude-opus-4-8[1m]","claude-opus-5","claude-opus-5-5","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","glm-5.1","glm-5.2","gpt-4.1","gpt-4o","gpt-5-mini","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini","gpt-5.5","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra","gpt-6-luna","gpt-6-sol","gpt-6.1-sol","gpt-oss-120b","grok-4.5","grok-4.6","grok-4.7"]);});function vs(t){let e=t.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let n=e.lastIndexOf("/");return n>=0&&(e=e.slice(n+1)),e=e.replace(/-\d{8}$/,""),e}function Al(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),bn;let e=vs(t),n=Il[e];if(n)return Tr[n]??jt[n]??bn;if(Tr[e])return Tr[e];if(jt[e])return jt[e];if(Ns.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),bn;if(la.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),bn;let r={...jt,...Tr};for(let s of Object.keys(r))if(e.includes(s))return r[s];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),bn}function Ol(t,e,n,r=0,s){let o=Al(n),i=Math.min(r,t),d=(t-i)*o.input/1e6,c=i*o.cachedInput/1e6,l=e*o.output/1e6;return d+c+l}function pa(t,e,n,r,s,o){return t&&t>0?t:!e&&!n?0:Ol(e??0,n??0,s,r??0)}var Il,bn,Tr,wr=x(()=>{_();xs();xs();Il={opus:"claude-opus-4-8",sonnet:"claude-sonnet-4-6",haiku:"claude-haiku-4-5","codex-mini":"gpt-5.3-codex",codex:"gpt-5.3-codex"},bn={input:0,cachedInput:0,output:0},Tr={};});function ha(t){if(!t||!t.includes("schedule_id"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.trigger;if(typeof r!="string"||!bl.includes(r))return null;let s=n.schedule_id;return typeof s=="string"&&s!==""?s:null}var bl,ma=x(()=>{_();bl=["cron","cron_manual"];});function Ps(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function ka(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function yr(t){return Number.isSafeInteger(t)&&t>0}function Dl(t,e){try{let n=child_process.spawnSync(t,e,{encoding:"utf8",timeout:Cs,windowsHide:!0});return {status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",error:n.error}}catch(n){return {status:null,stdout:"",stderr:"",error:Ps(n)}}}function Ll(t,e){return new Promise(n=>{let r;try{r=child_process.spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:Ps(c)});return}let s="",o="",i=false,u,d=setTimeout(()=>{try{r.kill();}catch{}u({status:null,stdout:s,stderr:o,error:new Error(`Command timed out after ${Cs}ms`)});},Cs);u=c=>{i||(i=true,clearTimeout(d),n(c));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",c=>{s+=String(c);}),r.stderr?.on("data",c=>{o+=String(c);}),r.once("error",c=>{u({status:null,stdout:s,stderr:o,error:c});}),r.once("close",c=>{u({status:c,stdout:s,stderr:o});});})}async function Ds(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Ll(t,e)}function Ml(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function $l(){return new Promise(t=>{setImmediate(t);})}function pt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return ka(n)==="ESRCH"?"not_found":ka(n)==="EPERM"?"alive":"unknown"}}function Hl(t,e){let n=pt(-t,e),r=pt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function wa(t,e,n,r){let s=Math.max(0,n),o=Math.max(1,r.pollIntervalMs??Cl),i=Date.now()+s,u,d=s===0,c=r.sleep?Promise.resolve().then(()=>r.sleep(s)).then(()=>{},()=>{}):new Promise(l=>{u=setTimeout(l,s);});c.then(()=>{d=true;});try{for(await $l();;){let l=Hl(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([c,Ml(Math.min(o,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function Ta(t,e,n,r,s){let o=await wa(t,e,s.hardConfirmMs??Pl,{...s,sleep:void 0});return o==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:o==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function ya(t,e,n={}){if(!yr(t))return "unknown";let r=n.platform??process.platform,s=r==="win32"?"powershell.exe":"ps",o=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],i;try{i=await Ds(s,o,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let u=i.stdout.trim();if(!u)return "not_found";let d=r==="win32"?u.toLowerCase():u;return e.filter(l=>l.trim().length>0).some(l=>{let p=r==="win32"?l.toLowerCase():l;return d.includes(p)})?"owned":"not_owned"}function Bl(t){let e=Ul.exec(t.trim());if(!e)return;let[,n="0",r="0",s="0",o="0"]=e;return ((Number(n)*24+Number(r))*60+Number(s))*60+Number(o)}function Wl(t){let e=t.trim(),n=ql.exec(e);if(n){let[,s,o,i,u,d,c,l,p]=n;return Date.UTC(Number(s),Number(o)-1,Number(i),Number(u),Number(d),Number(c),Math.trunc(Number(l)/1e3))-Number(p)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function Ea(t,e){return e==="win32"?{command:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write($p.CreationDate.ToUniversalTime().ToString('o')) }`]}:{command:"ps",args:["-p",String(t),"-o","pgid=","-o","etime=","-o","stat="]}}function Ra(t,e,n){if(t.error)return {status:"unknown"};let r=t.stdout.trim();if(!r)return t.status===0||t.status===1?{status:"not_found"}:{status:"unknown"};if(t.status!==0)return {status:"unknown"};if(e==="win32"){let i=Wl(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let s=Fl.exec(r),o=s?Bl(s[2]):void 0;return !s||o===void 0?{status:"unknown"}:s[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-o*1e3,groupId:Number(s[1])}}function Sa(t,e={}){if(!yr(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=Ea(t,n),o=e.runCommand??Dl,i;try{i=o(r,s);}catch{return {status:"unknown"}}return Ra(i,n,Date.now())}async function Ia(t,e={}){if(!yr(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=Ea(t,n),o;try{o=await Ds(r,s,e);}catch{return {status:"unknown"}}return Ra(o,n,Date.now())}async function gt(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",s=g=>({status:"failed",pid:t,method:r,error:g});if(!yr(t))return s("Invalid process ID");let o=e.kill??process.kill,i=pt(t,o);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return s("Unable to determine whether the process is alive");if(n==="win32"){let g;try{g=await Ds("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){g={status:null,stdout:"",stderr:"",error:Ps(m)};}let h=pt(t,o);return h==="not_found"?g.status===0&&!g.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:s(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let u,d=e.signal??"SIGKILL";try{o(-t,d);}catch(g){u=g;}if(d==="SIGKILL")return Ta(t,o,u,r,e);if(await wa(t,o,e.graceMs??vl,e)==="not_found")return u?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{o(-t,"SIGKILL");}catch(g){l=g;}let p=await Ta(t,o,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?u?p:{status:"terminated",pid:t,method:r}:s(p.error??"Process termination failed")}var Cs,ft,vl,Cl,Pl,Er,Ul,Fl,ql,Rr=x(()=>{_();Cs=3e3,ft="SIGINT",vl=2e3,Cl=25,Pl=100;Er=3e3,Ul=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,Fl=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,ql=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function xa(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new f("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new f("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function ba(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new f("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,s)=>xa(r,s))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function va(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new f("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new f("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new f("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Na(t){return {taskId:t.id,source:va(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Vl(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var Sr,Ca=x(()=>{_();dt();Et();Rt();at();xt();Sr=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=le.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?yt(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=le.dirname(n);fs.existsSync(s)||fs.mkdirSync(s,{recursive:true});}else if(!fs.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=M(n);if(e)try{Ne(r.db,n);}catch(s){throw r.close(),s}return r}findStateRow(e,n){return e.db.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(drizzleOrm.eq(a.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(drizzleOrm.eq(a.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new f("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((o,i)=>xa(o,i));if(r.length===0){let o=this.getLogState(e);if(!o)throw new f("NOT_FOUND",`Task not found: ${e}`);return o}let s=this.openHandle(true);try{return s.db.transaction(i=>{let u=this.requireStateRowInTransaction(i,e),d=va(u);if(d==="blob"){let g=ba(e,u.logs);if(i.update(a).set({logs:JSON.stringify([...g,...r]),log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:u.last_log_seq}}let c=u.last_log_seq+1,l=u.last_log_seq+r.length;if(i.insert(Ve).values(r.map((g,h)=>({task_id:e,seq:c+h,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),i.update(a).set({last_log_seq:l,log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to append task log",o)}finally{s.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?Na(r):void 0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return Vl(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(s=>{let o=this.findStateRowInTransaction(s,e);if(!o)return;let i=Na(o);if(i.source==="blob"){let l=ba(e,o.logs);return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let u=s.select({seq:Ve.seq,timestamp:Ve.timestamp,level:Ve.level,message:Ve.message}).from(Ve).where(drizzleOrm.eq(Ve.task_id,e)).orderBy(n===void 0?drizzleOrm.asc(Ve.seq):drizzleOrm.desc(Ve.seq)),c=(n===void 0?u.all():u.limit(n).all()).map(({timestamp:l,level:p,message:g})=>({timestamp:l,level:p,message:g}));return n!==void 0&&c.reverse(),{...i,entries:c}},{behavior:"deferred"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read task logs",s)}finally{r.close();}}};});var ep,Ir,Da=x(()=>{_();dt();Et();Rt();at();xt();ep=50,Ir=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=`${e.dbRoot}/.crewx/crewx.db`);}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(){let e=this.resolveDbPath(),n=M(e);try{return Ne(n.db,e),n}catch(r){throw n.close(),r}}recordAccepted(e){if(e.actorKind!=="human"||!e.workspaceId||!e.actorId||!e.agentId)return false;let n;try{n=this.openHandle();let r=e.acceptedAt??new Date().toISOString();return n.db.insert(Se).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[Se.workspace_id,Se.actor_id,Se.agent_id],set:{last_accepted_at:drizzleOrm.sql`MAX(${Se.last_accepted_at}, excluded.last_accepted_at)`}}).run(),!0}catch(r){return console.error("[AgentSendHistoryRepository] Failed to record accepted agent send",r),false}finally{n?.close();}}findRecentAgents(e,n){let r;try{return r=this.openHandle(),r.db.select({agentId:Se.agent_id,lastAcceptedAt:Se.last_accepted_at}).from(Se).where(drizzleOrm.and(drizzleOrm.eq(Se.workspace_id,e),drizzleOrm.eq(Se.actor_id,n))).orderBy(drizzleOrm.desc(Se.last_accepted_at),drizzleOrm.asc(Se.agent_id)).limit(ep).all()}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to find recent agent sends",s)}finally{r?.close();}}};});var La=x(()=>{_();});var Q,vt=x(()=>{_();Q=class extends Error{constructor(n,r,s){super(n);this.providerStr=r;this.name="ProviderError",this.code=s?.code??"UNKNOWN",this.kind=s?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=s?.retryAfterMs;}providerStr;code;kind;retryAfterMs;stdout};});var Ct,Ls=x(()=>{_();vt();Ct=class extends Q{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function $a(t){if(typeof t!="string")return;let e=t.trim();if(e)return e=e.replace(/^\s*at\s+[^\r\n]+(?:\r?\n|$)/gim,""),e=e.replace(/(^|[\r\n])\s*(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-auth-token|cookie|set-cookie)\s*:\s*[^\r\n]*/gim,`$1[HTTP HEADER ${_e}]`),e=np(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${_e}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,_e),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,_e),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,_e),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,_e),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,_e),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,_e),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,_e),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,_e),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,_e),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${_e}${r}${_e}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${_e}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,Ma),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,Ma),e=e.replace(/[\r\n]{3,}/g,`
32
+ )`)}));});var ji=x(()=>{_();sqliteCore.sqliteTable("ui_definition_archive",{definition_hash:sqliteCore.text("definition_hash").primaryKey().notNull(),definition_json:sqliteCore.text("definition_json").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({definitionHashCheck:sqliteCore.check("ui_definition_archive_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:sqliteCore.check("ui_definition_archive_definition_json_ck",drizzleOrm.sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:sqliteCore.check("ui_definition_archive_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`)}));});var Ki,Ji=x(()=>{_();Ki=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},t=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${t.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${t.stage_index} >= 1`)})),sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>Ki.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>Ki.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},t=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var ys,Es,v,Rs=x(()=>{_();ys=["THREAD_STATE","THREAD_PRIORITY"],Es=["gray","blue","violet","green","amber","orange","red","pink"],v=sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.code_group,t.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${t.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var Vi,Xi,Yi,Qi,Zi,G,F,H,ea=x(()=>{_();yn();Vi=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Xi=["user","agent","system"],Yi=["auto","manual"],Qi=["decision","judgment","issue","result","pivot"],Zi=["queued","running","completed","failed"],G=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),type:sqliteCore.text("type").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),payload_json:sqliteCore.text("payload_json").notNull(),created_at:sqliteCore.text("created_at").notNull(),actor_id:sqliteCore.text("actor_id"),task_id:sqliteCore.text("task_id"),highlight_id:sqliteCore.text("highlight_id")},t=>({typeCheck:sqliteCore.check("thread_events_type_ck",drizzleOrm.sql`${t.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:sqliteCore.check("thread_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:sqliteCore.check("thread_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:sqliteCore.index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:sqliteCore.index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:sqliteCore.uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),F=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),request_id:sqliteCore.text("request_id").notNull(),status:sqliteCore.text("status").notNull(),detector_version:sqliteCore.text("detector_version").notNull(),requested_at:sqliteCore.text("requested_at").notNull(),started_at:sqliteCore.text("started_at"),completed_at:sqliteCore.text("completed_at"),error_code:sqliteCore.text("error_code"),previous_auto_count:sqliteCore.integer("previous_auto_count"),new_auto_count:sqliteCore.integer("new_auto_count")},t=>({statusCheck:sqliteCore.check("thread_highlight_runs_status_ck",drizzleOrm.sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:sqliteCore.check("thread_highlight_runs_counts_ck",drizzleOrm.sql`(${t.previous_auto_count} IS NULL OR ${t.previous_auto_count} >= 0) AND (${t.new_auto_count} IS NULL OR ${t.new_auto_count} >= 0)`),threadRequestUnique:sqliteCore.uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:sqliteCore.uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(drizzleOrm.sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:sqliteCore.index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),H=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),source:sqliteCore.text("source").notNull(),kind:sqliteCore.text("kind").notNull(),status:sqliteCore.text("status").notNull().default("active"),text:sqliteCore.text("text"),covers_from_task_id:sqliteCore.text("covers_from_task_id").notNull(),covers_to_task_id:sqliteCore.text("covers_to_task_id").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),agent_id:sqliteCore.text("agent_id"),source_task_id:sqliteCore.text("source_task_id"),detector_version:sqliteCore.text("detector_version"),content_fingerprint:sqliteCore.text("content_fingerprint"),dismissed_at:sqliteCore.text("dismissed_at")},t=>({sourceCheck:sqliteCore.check("thread_highlights_source_ck",drizzleOrm.sql`${t.source} IN ('auto', 'manual')`),kindCheck:sqliteCore.check("thread_highlights_kind_ck",drizzleOrm.sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:sqliteCore.check("thread_highlights_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:sqliteCore.check("thread_highlights_active_text_ck",drizzleOrm.sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:sqliteCore.check("thread_highlights_covers_ck",drizzleOrm.sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:sqliteCore.check("thread_highlights_auto_key_ck",drizzleOrm.sql`${t.source} = 'manual' OR (${t.source} = 'auto' AND ${t.source_task_id} IS NOT NULL AND ${t.detector_version} IS NOT NULL AND ${t.content_fingerprint} IS NOT NULL AND length(${t.source_task_id}) > 0 AND length(${t.detector_version}) > 0 AND length(${t.content_fingerprint}) > 0)`),threadStatusCreatedIndex:sqliteCore.index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:sqliteCore.index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:sqliteCore.uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(drizzleOrm.sql`${t.source} = 'auto'`)}));});var na=x(()=>{_();sqliteCore.sqliteTable("storage_metadata",{source_kind:sqliteCore.text("source_kind").notNull(),source_id:sqliteCore.text("source_id").notNull(),utc_ts:sqliteCore.text("utc_ts"),bytes:sqliteCore.integer("bytes").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:sqliteCore.index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteCore.sqliteTable("storage_metadata_state",{unit:sqliteCore.text("unit").primaryKey().notNull(),cursor_rowid:sqliteCore.integer("cursor_rowid").notNull().default(0),end_rowid:sqliteCore.integer("end_rowid"),complete:sqliteCore.integer("complete").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()});});var Se,ra=x(()=>{_();Se=sqliteCore.sqliteTable("agent_send_history",{workspace_id:sqliteCore.text("workspace_id").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),last_accepted_at:sqliteCore.text("last_accepted_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:sqliteCore.index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var ia,aa=x(()=>{_();yn();ar();sqliteCore.sqliteTable("sidebar_states",{workspace_id:sqliteCore.text("workspace_id").primaryKey().references(()=>ee.id,{onDelete:"cascade"}),revision:sqliteCore.integer("revision").notNull().default(0),rail_collapsed:sqliteCore.integer("rail_collapsed").notNull().default(0),seeded_at:sqliteCore.text("seeded_at").notNull()},t=>({railCollapsedCheck:sqliteCore.check("sidebar_states_rail_collapsed_ck",drizzleOrm.sql`${t.rail_collapsed} IN (0, 1)`)})),ia=sqliteCore.sqliteTable("sidebar_groups",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),name:sqliteCore.text("name").notNull(),color:sqliteCore.text("color").notNull(),collapsed:sqliteCore.integer("collapsed").notNull().default(0),position:sqliteCore.integer("position").notNull()},t=>({colorCheck:sqliteCore.check("sidebar_groups_color_ck",drizzleOrm.sql`${t.color} IN ('cyan', 'orange', 'purple', 'blue')`),collapsedCheck:sqliteCore.check("sidebar_groups_collapsed_ck",drizzleOrm.sql`${t.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:sqliteCore.index("idx_sidebar_groups_workspace_position").on(t.workspace_id,t.position)})),sqliteCore.sqliteTable("sidebar_tabs",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>ia.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})})),sqliteCore.sqliteTable("sidebar_closed_tabs",{id:sqliteCore.integer("id").primaryKey({autoIncrement:true}),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>ia.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull(),closed_at:sqliteCore.text("closed_at").notNull()},t=>({idxSidebarClosedTabsWorkspaceId:sqliteCore.index("idx_sidebar_closed_tabs_workspace_id").on(t.workspace_id,t.id)})),sqliteCore.sqliteTable("thread_reads",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ee.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>k.id,{onDelete:"cascade"}),read_through_at:sqliteCore.text("read_through_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var da=x(()=>{_();sqliteCore.sqliteTable("schedule_runs",{id:sqliteCore.text("id").primaryKey(),schedule_id:sqliteCore.text("schedule_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),mode:sqliteCore.text("mode").notNull(),trigger:sqliteCore.text("trigger").notNull(),occurrence_key:sqliteCore.text("occurrence_key"),task_id:sqliteCore.text("task_id"),app_id:sqliteCore.text("app_id"),schedule_name:sqliteCore.text("schedule_name"),builtin_id:sqliteCore.text("builtin_id"),command:sqliteCore.text("command"),high_frequency:sqliteCore.integer("high_frequency").notNull().default(0),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),exit_code:sqliteCore.integer("exit_code"),signal:sqliteCore.text("signal"),started_at:sqliteCore.text("started_at").notNull(),finished_at:sqliteCore.text("finished_at"),duration_ms:sqliteCore.integer("duration_ms"),pid:sqliteCore.integer("pid"),host_pid:sqliteCore.integer("host_pid"),output_tail:sqliteCore.text("output_tail"),output_bytes:sqliteCore.integer("output_bytes"),output_truncated:sqliteCore.integer("output_truncated").notNull().default(0)},t=>({idx_schedule_runs_workspace_started:sqliteCore.index("idx_schedule_runs_workspace_started").on(t.workspace_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_schedule_started:sqliteCore.index("idx_schedule_runs_schedule_started").on(t.schedule_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_task_id:sqliteCore.index("idx_schedule_runs_task_id").on(t.task_id),idx_schedule_runs_running:sqliteCore.index("idx_schedule_runs_running").on(t.workspace_id,t.started_at).where(drizzleOrm.sql`${t.status} = 'running'`)}));});var ua=x(()=>{_();sqliteCore.sqliteTable("run_column_backfill",{name:sqliteCore.text("name").primaryKey(),cursor:sqliteCore.integer("cursor"),anchor_id:sqliteCore.text("anchor_id"),completed_at:sqliteCore.text("completed_at")});});var xt=x(()=>{_();ar();Wt();ki();wi();yn();Ri();Ii();Ai();bi();xi();vi();Di();Li();$i();Ui();Fi();Bi();Wi();ji();Ji();Rs();ea();na();ra();aa();da();ua();});function On(t){return typeof t=="string"&&lt.includes(t)}function ca(t){if(!t||!t.includes("workflow"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.workflowRunId;if(typeof r=="string"&&r!=="")return r;let s=n.workflow;if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let o=s.exec_id;if(typeof o=="string"&&o!=="")return o}return null}var lt,kr=x(()=>{_();lt=["workflow_card","workflow_ui_instance","workflow_run"];});var jt,Ns,la,xs=x(()=>{_();jt={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5-5":{input:4,cachedInput:.2,output:20},"claude-opus-5":{input:5,cachedInput:.5,output:25},"claude-opus-4-8":{input:5,cachedInput:.5,output:25},"claude-opus-4-7":{input:5,cachedInput:.5,output:25},"claude-opus-4-6":{input:5,cachedInput:.5,output:25},"claude-sonnet-5-5":{input:2,cachedInput:.1,output:10},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-5-5":{input:.1,cachedInput:.01,output:.5},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-6.1-sol":{input:2,cachedInput:.1,output:10},"gpt-6-sol":{input:2,cachedInput:.2,output:10},"gpt-6-luna":{input:.1,cachedInput:.01,output:.5},"gpt-5.6-sol":{input:4,cachedInput:.4,output:20},"gpt-5.6-terra":{input:2,cachedInput:.2,output:12},"gpt-5.6-luna":{input:.2,cachedInput:.02,output:1.2},"gpt-5.5":{input:5,cachedInput:.5,output:30},"gpt-5.4":{input:2.5,cachedInput:.25,output:15},"gpt-5.4-mini":{input:.75,cachedInput:.075,output:4.5},"gpt-5.3-codex":{input:1.75,cachedInput:.175,output:14},"gpt-5-mini":{input:.4,cachedInput:.1,output:1.6},"gpt-4.1":{input:2,cachedInput:.5,output:8},"gpt-4o":{input:2.5,cachedInput:1.25,output:10},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"gemini-3.7-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-3.6-flash":{input:1.5,cachedInput:.15,output:7.5},"grok-4.7":{input:2,cachedInput:.5,output:6},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},Ns=new Set(["gpt-5.3-codex-spark"]),la=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-haiku-5-5","claude-opus-4-6","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7","claude-opus-4-7[1m]","claude-opus-4-8","claude-opus-4-8[1m]","claude-opus-5","claude-opus-5-5","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","glm-5.1","glm-5.2","gpt-4.1","gpt-4o","gpt-5-mini","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini","gpt-5.5","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra","gpt-6-luna","gpt-6-sol","gpt-6.1-sol","gpt-oss-120b","grok-4.5","grok-4.6","grok-4.7"]);});function vs(t){let e=t.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let n=e.lastIndexOf("/");return n>=0&&(e=e.slice(n+1)),e=e.replace(/-\d{8}$/,""),e}function Al(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),bn;let e=vs(t),n=Il[e];if(n)return Tr[n]??jt[n]??bn;if(Tr[e])return Tr[e];if(jt[e])return jt[e];if(Ns.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),bn;if(la.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),bn;let r={...jt,...Tr};for(let s of Object.keys(r))if(e.includes(s))return r[s];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),bn}function Ol(t,e,n,r=0,s){let o=Al(n),i=Math.min(r,t),d=(t-i)*o.input/1e6,c=i*o.cachedInput/1e6,l=e*o.output/1e6;return d+c+l}function pa(t,e,n,r,s,o){return t&&t>0?t:!e&&!n?0:Ol(e??0,n??0,s,r??0)}var Il,bn,Tr,wr=x(()=>{_();xs();xs();Il={opus:"claude-opus-4-8",sonnet:"claude-sonnet-4-6",haiku:"claude-haiku-4-5","codex-mini":"gpt-5.3-codex",codex:"gpt-5.3-codex"},bn={input:0,cachedInput:0,output:0},Tr={};});function ha(t){if(!t||!t.includes("schedule_id"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.trigger;if(typeof r!="string"||!bl.includes(r))return null;let s=n.schedule_id;return typeof s=="string"&&s!==""?s:null}var bl,ma=x(()=>{_();bl=["cron","cron_manual"];});function Ps(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function ka(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function yr(t){return Number.isSafeInteger(t)&&t>0}function Dl(t,e){try{let n=child_process.spawnSync(t,e,{encoding:"utf8",timeout:Cs,windowsHide:!0});return {status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",error:n.error}}catch(n){return {status:null,stdout:"",stderr:"",error:Ps(n)}}}function Ll(t,e){return new Promise(n=>{let r;try{r=child_process.spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:Ps(c)});return}let s="",o="",i=false,u,d=setTimeout(()=>{try{r.kill();}catch{}u({status:null,stdout:s,stderr:o,error:new Error(`Command timed out after ${Cs}ms`)});},Cs);u=c=>{i||(i=true,clearTimeout(d),n(c));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",c=>{s+=String(c);}),r.stderr?.on("data",c=>{o+=String(c);}),r.once("error",c=>{u({status:null,stdout:s,stderr:o,error:c});}),r.once("close",c=>{u({status:c,stdout:s,stderr:o});});})}async function Ds(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Ll(t,e)}function Ml(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function $l(){return new Promise(t=>{setImmediate(t);})}function pt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return ka(n)==="ESRCH"?"not_found":ka(n)==="EPERM"?"alive":"unknown"}}function Hl(t,e){let n=pt(-t,e),r=pt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function wa(t,e,n,r){let s=Math.max(0,n),o=Math.max(1,r.pollIntervalMs??Cl),i=Date.now()+s,u,d=s===0,c=r.sleep?Promise.resolve().then(()=>r.sleep(s)).then(()=>{},()=>{}):new Promise(l=>{u=setTimeout(l,s);});c.then(()=>{d=true;});try{for(await $l();;){let l=Hl(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([c,Ml(Math.min(o,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function Ta(t,e,n,r,s){let o=await wa(t,e,s.hardConfirmMs??Pl,{...s,sleep:void 0});return o==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:o==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function ya(t,e,n={}){if(!yr(t))return "unknown";let r=n.platform??process.platform,s=r==="win32"?"powershell.exe":"ps",o=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],i;try{i=await Ds(s,o,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let u=i.stdout.trim();if(!u)return "not_found";let d=r==="win32"?u.toLowerCase():u;return e.filter(l=>l.trim().length>0).some(l=>{let p=r==="win32"?l.toLowerCase():l;return d.includes(p)})?"owned":"not_owned"}function Bl(t){let e=Ul.exec(t.trim());if(!e)return;let[,n="0",r="0",s="0",o="0"]=e;return ((Number(n)*24+Number(r))*60+Number(s))*60+Number(o)}function Wl(t){let e=t.trim(),n=ql.exec(e);if(n){let[,s,o,i,u,d,c,l,p]=n;return Date.UTC(Number(s),Number(o)-1,Number(i),Number(u),Number(d),Number(c),Math.trunc(Number(l)/1e3))-Number(p)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function Ea(t,e){return e==="win32"?{command:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write($p.CreationDate.ToUniversalTime().ToString('o')) }`]}:{command:"ps",args:["-p",String(t),"-o","pgid=","-o","etime=","-o","stat="]}}function Ra(t,e,n){if(t.error)return {status:"unknown"};let r=t.stdout.trim();if(!r)return t.status===0||t.status===1?{status:"not_found"}:{status:"unknown"};if(t.status!==0)return {status:"unknown"};if(e==="win32"){let i=Wl(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let s=Fl.exec(r),o=s?Bl(s[2]):void 0;return !s||o===void 0?{status:"unknown"}:s[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-o*1e3,groupId:Number(s[1])}}function Sa(t,e={}){if(!yr(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=Ea(t,n),o=e.runCommand??Dl,i;try{i=o(r,s);}catch{return {status:"unknown"}}return Ra(i,n,Date.now())}async function Ia(t,e={}){if(!yr(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=Ea(t,n),o;try{o=await Ds(r,s,e);}catch{return {status:"unknown"}}return Ra(o,n,Date.now())}async function gt(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",s=g=>({status:"failed",pid:t,method:r,error:g});if(!yr(t))return s("Invalid process ID");let o=e.kill??process.kill,i=pt(t,o);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return s("Unable to determine whether the process is alive");if(n==="win32"){let g;try{g=await Ds("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){g={status:null,stdout:"",stderr:"",error:Ps(m)};}let h=pt(t,o);return h==="not_found"?g.status===0&&!g.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:s(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let u,d=e.signal??"SIGKILL";try{o(-t,d);}catch(g){u=g;}if(d==="SIGKILL")return Ta(t,o,u,r,e);if(await wa(t,o,e.graceMs??vl,e)==="not_found")return u?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{o(-t,"SIGKILL");}catch(g){l=g;}let p=await Ta(t,o,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?u?p:{status:"terminated",pid:t,method:r}:s(p.error??"Process termination failed")}var Cs,ft,vl,Cl,Pl,Er,Ul,Fl,ql,Rr=x(()=>{_();Cs=3e3,ft="SIGINT",vl=2e3,Cl=25,Pl=100;Er=3e3,Ul=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,Fl=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,ql=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function xa(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new f("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new f("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function ba(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new f("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,s)=>xa(r,s))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function va(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new f("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new f("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new f("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Na(t){return {taskId:t.id,source:va(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Vl(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var Sr,Ca=x(()=>{_();dt();Et();Rt();at();xt();Sr=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=le.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?yt(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=le.dirname(n);fs.existsSync(s)||fs.mkdirSync(s,{recursive:true});}else if(!fs.existsSync(n))throw new f("NOT_FOUND","Database not found");let r=M(n);if(e)try{Ne(r.db,n);}catch(s){throw r.close(),s}return r}findStateRow(e,n){return e.db.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(drizzleOrm.eq(a.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(drizzleOrm.eq(a.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new f("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((o,i)=>xa(o,i));if(r.length===0){let o=this.getLogState(e);if(!o)throw new f("NOT_FOUND",`Task not found: ${e}`);return o}let s=this.openHandle(true);try{return s.db.transaction(i=>{let u=this.requireStateRowInTransaction(i,e),d=va(u);if(d==="blob"){let g=ba(e,u.logs);if(i.update(a).set({logs:JSON.stringify([...g,...r]),log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:u.last_log_seq}}let c=u.last_log_seq+1,l=u.last_log_seq+r.length;if(i.insert(Ve).values(r.map((g,h)=>({task_id:e,seq:c+h,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),i.update(a).set({last_log_seq:l,log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to append task log",o)}finally{s.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?Na(r):void 0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return Vl(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(s=>{let o=this.findStateRowInTransaction(s,e);if(!o)return;let i=Na(o);if(i.source==="blob"){let l=ba(e,o.logs).map((p,g)=>({...p,seq:g+1}));return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let u=s.select({seq:Ve.seq,timestamp:Ve.timestamp,level:Ve.level,message:Ve.message}).from(Ve).where(drizzleOrm.eq(Ve.task_id,e)).orderBy(n===void 0?drizzleOrm.asc(Ve.seq):drizzleOrm.desc(Ve.seq)),c=(n===void 0?u.all():u.limit(n).all()).map(({seq:l,timestamp:p,level:g,message:h})=>({seq:l,timestamp:p,level:g,message:h}));return n!==void 0&&c.reverse(),{...i,entries:c}},{behavior:"deferred"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read task logs",s)}finally{r.close();}}};});var ep,Ir,Da=x(()=>{_();dt();Et();Rt();at();xt();ep=50,Ir=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=`${e.dbRoot}/.crewx/crewx.db`);}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(){let e=this.resolveDbPath(),n=M(e);try{return Ne(n.db,e),n}catch(r){throw n.close(),r}}recordAccepted(e){if(e.actorKind!=="human"||!e.workspaceId||!e.actorId||!e.agentId)return false;let n;try{n=this.openHandle();let r=e.acceptedAt??new Date().toISOString();return n.db.insert(Se).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[Se.workspace_id,Se.actor_id,Se.agent_id],set:{last_accepted_at:drizzleOrm.sql`MAX(${Se.last_accepted_at}, excluded.last_accepted_at)`}}).run(),!0}catch(r){return console.error("[AgentSendHistoryRepository] Failed to record accepted agent send",r),false}finally{n?.close();}}findRecentAgents(e,n){let r;try{return r=this.openHandle(),r.db.select({agentId:Se.agent_id,lastAcceptedAt:Se.last_accepted_at}).from(Se).where(drizzleOrm.and(drizzleOrm.eq(Se.workspace_id,e),drizzleOrm.eq(Se.actor_id,n))).orderBy(drizzleOrm.desc(Se.last_accepted_at),drizzleOrm.asc(Se.agent_id)).limit(ep).all()}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to find recent agent sends",s)}finally{r?.close();}}};});var La=x(()=>{_();});var Q,vt=x(()=>{_();Q=class extends Error{constructor(n,r,s){super(n);this.providerStr=r;this.name="ProviderError",this.code=s?.code??"UNKNOWN",this.kind=s?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=s?.retryAfterMs;}providerStr;code;kind;retryAfterMs;stdout};});var Ct,Ls=x(()=>{_();vt();Ct=class extends Q{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function $a(t){if(typeof t!="string")return;let e=t.trim();if(e)return e=e.replace(/^\s*at\s+[^\r\n]+(?:\r?\n|$)/gim,""),e=e.replace(/(^|[\r\n])\s*(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-auth-token|cookie|set-cookie)\s*:\s*[^\r\n]*/gim,`$1[HTTP HEADER ${_e}]`),e=np(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${_e}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,_e),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,_e),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,_e),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,_e),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,_e),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,_e),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,_e),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,_e),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,_e),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${_e}${r}${_e}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${_e}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,Ma),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,Ma),e=e.replace(/[\r\n]{3,}/g,`
33
33
 
34
34
  `).trim(),tp(e,1024)||void 0}function tp(t,e){let n=new TextEncoder;if(n.encode(t).byteLength<=e)return t;let r="",s=0;for(let o of t){let i=n.encode(o).byteLength;if(s+i>e)break;r+=o,s+=i;}return r}function np(t){let e=/\b(?:request|response|http)?\s*body\s*[:=]\s*/gim,n="",r=0,s;for(;(s=e.exec(t))!==null;){if(s.index<r)continue;let o=s.index+s[0].length,i=rp(t,o),u=i>=0?i:t.indexOf(`
35
35
  `,o)>=0?t.indexOf(`
@@ -39,7 +39,7 @@ export type { TaskRow, TaskKillResult, TaskKillStatus, TaskActivityLogRow, FindT
39
39
  export { classifyUsageAccountingReason, runUsageBackfill, USAGE_BACKFILL_MAX_LATE_USAGE_AGE_MS, USAGE_BACKFILL_TERMINAL_STATUSES, } from './usage-backfill.js';
40
40
  export type { UsageAccountingReason, UsageBackfillFailure, UsageBackfillMode, UsageBackfillOptions, UsageBackfillProviderStats, UsageBackfillReport, } from './usage-backfill.js';
41
41
  export { TaskLogRepository } from './task-log.repository.js';
42
- export type { TaskLogEntry, RawTaskLogEntry, TaskLogRawEntry, TaskLogStorage, TaskLogState, TaskLogReadResult, TaskLogRepositoryContract, } from './task-log.repository.js';
42
+ export type { TaskLogEntry, RawTaskLogEntry, TaskLogRawEntry, TaskLogStorage, TaskLogState, TaskLogReadEntry, TaskLogReadResult, TaskLogRepositoryContract, } from './task-log.repository.js';
43
43
  export { runTaskLogMigration, resolveTaskLogMigrationDbPath, taskLogBackupName, tryCheckpointTaskLogWal, hasSufficientTaskLogMigrationFreeSpace, } from './task-log-migration.js';
44
44
  export { TASK_LOG_MIGRATION_EVENT_ROW_BYTES, TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES, TASK_LOG_MIGRATION_TERMINAL_STATUSES, } from './task-log-migration.js';
45
45
  export type { TaskLogMigrationFailure, TaskLogMigrationFailureKind, TaskLogMigrationMode, TaskLogMigrationOptions, TaskLogMigrationReport, TaskLogWalCheckpointConnection, TaskLogVerificationIssue, TaskLogVerificationIssueKind, TaskLogVerificationReport, } from './task-log-migration.js';