@crewx/sdk 0.9.0-rc.93 → 0.9.0-rc.94

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.
@@ -314,7 +314,7 @@ ${r.join(`
314
314
  `),o=r.length>_o?`${r.slice(0,_o-1)}${ko}`:r;return [{timestamp:t,type:"info",content:o}]}function ua(t,e){let n=J(e.type);if(n==="thought"){let r=J(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=J(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return ca(t,e);if(n==="tool_call"){let r=J(e.toolCallId),o=J(e.toolName)??J(e.title),s=e.rawInput===void 0?void 0:wt(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:o,toolInput:s}]}if(n==="tool_call_update"){let r=J(e.status);return r!=="completed"&&r!=="failed"&&r!=="error"?[]:[{timestamp:t,type:"tool_result",toolUseId:J(e.toolCallId),toolName:J(e.toolName)??J(e.title),resultPreview:ia(e),isError:r!=="completed"||e.isError===true}]}if(n==="error"){let r=To(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}var $n={command:"grok",createSessionId:()=>crypto.randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=Ge(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],d=n?je("grok").some(ae=>ae.id===n):false,l=n&&d?kt("grok",n):[],c=!o||l.length===0||l.includes(o)?o:void 0,u=to(c),g=e.additionalArgs??[],f=ae=>g.some(ee=>ee===ae||ee.startsWith(`${ae}=`)),m=e.providerOptions,R=m?.alwaysApprove,x=m?.sandbox,I=f("--permission-mode")?[]:Qr(e.mode),M=f("--always-approve")?[]:Zr(R),B=f("--sandbox")?[]:eo(x);return {args:["--no-auto-update",...s,"--single",t,"--output-format","streaming-json","--no-alt-screen",...i,...u,...I,...M,...B,...g]}},extractText(t){let e=[],n=false;for(let r of t.split(`
315
315
  `).flatMap(Tt))typeof r.type=="string"&&(n=true),r.type==="text"&&typeof r.data=="string"&&e.push(r.data);return e.length>0?e.join(""):n?"":t.trim()},extractFailure(t){for(let e of Tt(t))if(e.type==="error"){let n=To(e);return yo(wt(e))?new Pe(n,Jt):new W(n,Jt)}return null},interpretExit(t,e){if(t===0)return null;let n=wo(e)||`Grok CLI exited with code ${t}.`;return yo(e)?new Pe(n,Jt):new W(n,Jt)},parseResultMeta(t){let n=t.split(`
316
316
  `).flatMap(Tt).find(r=>r.type==="end");return n?{usage:da(n),model:aa(n)}:{usage:la(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return Tt(t).flatMap(r=>ua(ue(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return ot(n)&&typeof n.type=="string"?na.has(n.type):!1}catch{return false}}};var Eo={codex:Dn,claude:Cn,opencode:Pn,antigravity:Mn,copilot:Nn,grok:$n};function Ro(t){if(t.startsWith("cli/"))return Eo[t.slice(4)]}function pa(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let o=r.type;if(typeof o!="string")return false;let s=e?Ta[e]:void 0;return s?s(r,o):Object.values(vo).some(i=>i(r,o))}function Xt(t,e){let n=t.split(`
317
- `).filter(r=>r.trim());return n.length===0?false:n.every(r=>pa(r,e))}function se(t){return typeof t=="object"&&t!==null}function Io(t,e){if(e==="assistant"||e==="user"){let n=t.message;return se(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||se(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?se(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function ga(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:Io(t,e)}function fa(t,e){if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return se(n)&&typeof n.type=="string"}return false}function ha(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||se(t.part):e==="text"||e==="tool_use"?se(t.part):e==="result"?typeof t.result=="string":false}function ma(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||se(t.part)||e==="result"&&typeof t.result=="string")}function _a(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?se(t.data):e==="result"?typeof t.result=="string":false}function ka(t,e){return e==="message"?typeof t.role=="string":e==="tool_use"?typeof t.tool_name=="string"||typeof t.tool_id=="string":e==="tool_result"?typeof t.tool_id=="string"||typeof t.status=="string":false}function ya(t,e){return e==="available_commands"?se(t.tools)||se(t.commands):e==="usage"?se(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||se(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var vo={claude:Io,codex:fa,opencode:ha,copilot:_a,gemini:ka},Ta={...vo,claude:ga,opencode:ma,grok:ya,antigravity:()=>false};var Ea=200,Ra=200;function Ia(t){if(typeof t!="object"||t===null||!("code"in t))return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function va(t){let e=t instanceof p?t.code:void 0,n=t instanceof p?t.cause:t,r=Ia(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function xo(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function Aa(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xa(t){if(!t)return {};try{let e=JSON.parse(t);return Aa(e)?e:{}}catch{return {}}}function So(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Un=class extends He{name="sqlite-tracing";unsubs=[];dbPath;version;taskRepo;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super(),this.dbPath=Ae.join(e?.dbRoot??ar.homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown";}attach(e){let n=new jt({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),s=fs.existsSync(Ae.join(r,"crewx.yaml"))||fs.existsSync(Ae.join(r,"crewx.yml"))?rr(r):null,i=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let l=d.callerAgentId??null,c=d.parentTaskId??null,u=d.rootTraceId??d.traceId,g=d.metadata?JSON.stringify(d.metadata):JSON.stringify({provider:d.provider??"cli/claude"});n.startTask({id:d.traceId,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:d.pid??null,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,command:i,codingAgentCommand:d.codingAgentCommand??null,workspaceId:d.workspaceId??s,projectId:d.projectId??null,callerAgentId:l,parentTaskId:c,traceId:u,metadata:g,threadId:d.threadId??null});}catch{}}),e.on("task:output",d=>{try{this.enqueueLog(d.traceId,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(l){let c={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(l,[c],xo(c));}}),e.on("task:end",d=>{try{this.flushTaskLogs(d.traceId);let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null,c=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{}}):null,u=d.result??null,g=!1;if(d.error&&(!u||u.trim()==="")){let f=this.recoverPartialResult(d.traceId,d,l);f&&(u=f,g=!0);}n.finishTask({id:d.traceId,status:d.error?"failed":"success",result:u,error:c,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,model:d.model??null,runEpoch:l,partialResultRecovered:g});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.taskRepo=void 0;}}getMetrics(){let e=0,n=0;for(let r of this.queues.values())e+=r.entries.length,n+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:n}}enqueueLog(e,n){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(n),r.bytes+=xo(n),this.metrics.maxQueueEntries=Math.max(this.metrics.maxQueueEntries,r.entries.length),this.metrics.maxQueueBytes=Math.max(this.metrics.maxQueueBytes,r.bytes),r.entries.length>=Ea){this.flushTaskLogs(e);return}if(!r.timer){let o=setTimeout(()=>{let s=this.queues.get(e);!s||s.timer!==o||(s.timer=void 0,this.flushTaskLogs(e));},Ra);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo?.getTask(e);if(!o||o.status!=="running"||So(o.run_epoch)!==So(r))return;let s=xa(o.metadata),i=typeof s.provider=="string"?s.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!i)return;let d=Ro(i);if(!d?.extractPartialText)return;let c=this.taskRepo?.readLogs(e)?.entries.filter(g=>g.level==="stdout").map(g=>g.message).join(`
317
+ `).filter(r=>r.trim());return n.length===0?false:n.every(r=>pa(r,e))}function se(t){return typeof t=="object"&&t!==null}function Io(t,e){if(e==="assistant"||e==="user"){let n=t.message;return se(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||se(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?se(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function ga(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:Io(t,e)}function fa(t,e){if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return se(n)&&typeof n.type=="string"}return false}function ha(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||se(t.part):e==="text"||e==="tool_use"?se(t.part):e==="result"?typeof t.result=="string":false}function ma(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||se(t.part)||e==="result"&&typeof t.result=="string")}function _a(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?se(t.data):e==="result"?typeof t.result=="string":false}function ka(t,e){return e==="message"?typeof t.role=="string":e==="tool_use"?typeof t.tool_name=="string"||typeof t.tool_id=="string":e==="tool_result"?typeof t.tool_id=="string"||typeof t.status=="string":false}function ya(t,e){return e==="available_commands"?se(t.tools)||se(t.commands):e==="usage"?se(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||se(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var vo={claude:Io,codex:fa,opencode:ha,copilot:_a,gemini:ka},Ta={...vo,claude:ga,opencode:ma,grok:ya,antigravity:()=>false};var Ea=200,Ra=200;function Ia(t){if(typeof t!="object"||t===null||!("code"in t))return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function va(t){let e=t instanceof p?t.code:void 0,n=t instanceof p?t.cause:t,r=Ia(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function xo(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function Aa(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xa(t){if(!t)return {};try{let e=JSON.parse(t);return Aa(e)?e:{}}catch{return {}}}function So(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Un=class extends He{name="sqlite-tracing";unsubs=[];dbPath;version;taskRepo;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super(),this.dbPath=Ae.join(e?.dbRoot??ar.homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown";}attach(e){let n=new jt({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),s=fs.existsSync(Ae.join(r,"crewx.yaml"))||fs.existsSync(Ae.join(r,"crewx.yml"))?rr(r):null,i=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let l=d.callerAgentId??null,c=d.parentTaskId??null,u=d.rootTraceId??d.traceId,g=d.metadata?JSON.stringify(d.metadata):JSON.stringify({provider:d.provider??"cli/claude"});n.startTask({id:d.traceId,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:d.pid??null,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,command:i,codingAgentCommand:d.codingAgentCommand??null,workspaceId:d.workspaceId??s,projectId:d.projectId??null,callerAgentId:l,parentTaskId:c,traceId:u,metadata:g,threadId:d.threadId??null});}catch{}}),e.on("task:output",d=>{try{this.enqueueLog(d.traceId,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(l){let c={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(l,[c],xo(c));}}),e.on("task:end",d=>{try{this.flushTaskLogs(d.traceId);let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null,c=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{},...d.error.mode?{mode:d.error.mode}:{}}):null,u=d.result??null,g=!1;if(d.error&&(!u||u.trim()==="")){let f=this.recoverPartialResult(d.traceId,d,l);f&&(u=f,g=!0);}n.finishTask({id:d.traceId,status:d.error?"failed":"success",result:u,error:c,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,model:d.model??null,runEpoch:l,partialResultRecovered:g});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.taskRepo=void 0;}}getMetrics(){let e=0,n=0;for(let r of this.queues.values())e+=r.entries.length,n+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:n}}enqueueLog(e,n){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(n),r.bytes+=xo(n),this.metrics.maxQueueEntries=Math.max(this.metrics.maxQueueEntries,r.entries.length),this.metrics.maxQueueBytes=Math.max(this.metrics.maxQueueBytes,r.bytes),r.entries.length>=Ea){this.flushTaskLogs(e);return}if(!r.timer){let o=setTimeout(()=>{let s=this.queues.get(e);!s||s.timer!==o||(s.timer=void 0,this.flushTaskLogs(e));},Ra);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo?.getTask(e);if(!o||o.status!=="running"||So(o.run_epoch)!==So(r))return;let s=xa(o.metadata),i=typeof s.provider=="string"?s.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!i)return;let d=Ro(i);if(!d?.extractPartialText)return;let c=this.taskRepo?.readLogs(e)?.entries.filter(g=>g.level==="stdout").map(g=>g.message).join(`
318
318
  `)??"";if(!c.trim())return;let u=d.extractPartialText(c);return !u||!u.trim()||Xt(u,i)?void 0:u}catch{return}}flushTaskLogs(e){let n=this.queues.get(e);if(!n||n.entries.length===0){n?.timer&&clearTimeout(n.timer),this.queues.delete(e);return}n.timer&&(clearTimeout(n.timer),n.timer=void 0);let r=n.entries,o=n.bytes;n.entries=[],n.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(i){this.recordAppendFailure(i,r,o);}let s=this.queues.get(e);s&&s.entries.length===0&&(s.timer&&clearTimeout(s.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,n,r){let o=va(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=n.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[o.code]=(this.metrics.appendFailureByCode[o.code]??0)+1,this.metrics.appendFailureByCause[o.cause]=(this.metrics.appendFailureByCause[o.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:o.code,cause:o.cause,pendingEntries:n.length,pendingBytes:r});}};var st=class extends p{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function Rt(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Na(t){let n=Rt(t).threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {priority:null,state:null};let r=n;return {priority:typeof r.priority=="string"?r.priority:null,state:typeof r.state=="string"?r.state:null}}var Qt=class extends te{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);fs.existsSync(o)||fs.mkdirSync(o,{recursive:true});}else if(!fs.existsSync(n))throw new p("NOT_FOUND","Database not found");let r=P(n);if(e)try{fe(r.db,n);}catch(o){throw r.close(),o}return r}validateWorkspaceId(e,n){return e.db.select({id:Ze.id}).from(Ze).where(drizzleOrm.eq(Ze.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(e="child"){return drizzleOrm.sql.raw(`NOT EXISTS (
319
319
  SELECT 1 FROM tasks parent
320
320
  WHERE parent.id = ${e}.parent_task_id
@@ -374,7 +374,7 @@ ${r.join(`
374
374
  `),c},{behavior:"immediate"})}}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(h).set({last_message:n,updated_at:s}).where(drizzleOrm.eq(h.id,e)).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};n.title!==void 0&&(o.title=n.title,o.title_locked=1),n.titleLocked!==void 0&&(o.title_locked=n.titleLocked?1:0),r.db.update(h).set(o).where(drizzleOrm.eq(h.id,e)).run();}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let o=n;if(!o||typeof o!="object"||Array.isArray(o))return new st("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new st("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new st("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let l of [i.priority,i.state])if(l!=null&&(typeof l!="string"||l.length===0))return new st("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let l=r?drizzleOrm.and(drizzleOrm.eq(h.id,e),drizzleOrm.eq(h.workspace_id,r)):drizzleOrm.eq(h.id,e);return d.db.transaction(c=>{let u=c.select({metadata:h.metadata}).from(h).where(l).get();if(!u)return null;let g=Rt(u.metadata),f=g.threadTitle,m=f&&typeof f=="object"&&!Array.isArray(f)?{...f}:{};i.priority===null?delete m.priority:i.priority!==void 0&&(m.priority=i.priority),i.state===null?delete m.state:i.state!==void 0&&(m.state=i.state),Object.keys(m).length>0?g.threadTitle=m:delete g.threadTitle;let R=Object.keys(g).length>0?JSON.stringify(g):null,x=new Date().toISOString();c.update(h).set({metadata:R,updated_at:x}).where(l).run();let I=c.select({metadata:h.metadata}).from(h).where(l).get();if(!I)throw new p("DB_ERROR","Thread-title metadata update could not be read back");let M=Na(I.metadata);return {threadId:e,priority:M.priority,state:M.state}},{behavior:"immediate"})}catch(l){throw l instanceof p?l:new p("DB_ERROR","Failed to patch thread-title metadata",l)}finally{d.close();}}togglePin(e,n){let r=this.openHandle(true);try{let o=n?drizzleOrm.and(drizzleOrm.eq(h.id,e),drizzleOrm.eq(h.workspace_id,n)):drizzleOrm.eq(h.id,e);return r.db.transaction(s=>{let i=s.select({pinned:h.pinned,metadata:h.metadata}).from(h).where(o).get();if(!i)return null;let d=i.pinned?0:1,l=Rt(i.metadata);if(d){let c=n?drizzleOrm.and(drizzleOrm.eq(h.pinned,1),drizzleOrm.eq(h.workspace_id,n)):drizzleOrm.eq(h.pinned,1),u=s.select({metadata:h.metadata}).from(h).where(c).all(),g=null;for(let f of u){let m=Rt(f.metadata);typeof m.pinOrder=="number"&&(g===null||m.pinOrder<g)&&(g=m.pinOrder);}l.pinOrder=g===null?0:g-1;}else delete l.pinOrder;return s.update(h).set({pinned:d,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(o).run(),{pinned:!!d}},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>{for(let s=0;s<e.length;s++){let i=n?drizzleOrm.and(drizzleOrm.eq(h.id,e[s]),drizzleOrm.eq(h.workspace_id,n)):drizzleOrm.eq(h.id,e[s]),d=o.select({metadata:h.metadata}).from(h).where(i).get();if(!d)continue;let l=Rt(d.metadata);l.pinOrder=s+1,o.update(h).set({metadata:JSON.stringify(l)}).where(i).run();}},{behavior:"immediate"});}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?drizzleOrm.and(drizzleOrm.eq(h.id,e),drizzleOrm.eq(h.workspace_id,n)):drizzleOrm.eq(h.id,e),s=r.db.select({starred:h.starred}).from(h).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(h).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let i=this.openHandle(true);try{let d=n?drizzleOrm.and(drizzleOrm.eq(h.id,e),drizzleOrm.eq(h.workspace_id,n)):drizzleOrm.eq(h.id,e);return i.db.transaction(c=>{let u=c.select({metadata:h.metadata}).from(h).where(d).get();if(!u)return null;let g=u.metadata?JSON.parse(u.metadata):{},f=g.overdrive??{},m=o?.defaultTurns??f.defaultTurns??3,R=o?.updatedBy??"ui",x=new Date().toISOString(),I,M,B,ae;switch(r){case "enable-count":{let ee=o?.turns??m,$e=o?.consumeCurrent?Math.max(ee-1,0):ee;I=$e>0?"count":"off",M=$e,B=!0,ae="count";break}case "enable-latch":{I="latch",M=0,B=!0,ae="latch";break}case "disable":{I="off",M=0,B=!1;break}default:{let ee=f.state??"off",$e=typeof f.remaining=="number"?f.remaining:0;if(ee==="count"&&$e>0){let O=$e-1;O<=0?(I="off",M=0):(I="count",M=O),B=!0,ae="count";}else ee==="latch"?(I="latch",M=0,B=!0,ae="latch"):(I="off",M=0,B=!1);break}}return g.overdrive={state:I,remaining:M,defaultTurns:m,updatedAt:x,updatedBy:R},c.update(h).set({metadata:JSON.stringify(g),updated_at:x}).where(d).run(),{applied:B,appliedMode:ae,state:I,remaining:M}},{behavior:"immediate"})}catch(d){throw d instanceof p?d:new p("DB_ERROR","Failed to resolve overdrive",d)}finally{i.close();}}};var Fn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Da(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let o=e[r];o<248&&(n+=Fn[o%62]);}for(;n.length<t;)n+=Fn[crypto.randomBytes(1)[0]%62];return n}function It(t){return `${t}_${Da(8)}`}function Do(t,e){let{createHash:n}=ut("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=r[i];let s="";for(let i of o)s+=Fn[i%62];return `${t}_${s}`}var Pa=["urgent","high","medium","low"],La=["investigating","in-progress","in-review","on-hold","done"],Po="custom:";var Ma=new Set(Pa),$a=new Set(La);function qn(t){return typeof t=="string"&&Ma.has(t)}function Bn(t){if(typeof t!="string")return false;if($a.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Po))return false;let e=t.slice(Po.length);return e.length>=1&&e.length<=20}function Lo(t){if(!t)return null;try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function jn(t){let e=Lo(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return qn(r.priority)&&(o.priority=r.priority),Bn(r.state)&&(o.state=r.state),o}function Mo(t,e){let n=Lo(t)??{},r={...jn(t)};return e.priority===null?delete r.priority:e.priority!==void 0&&(r.priority=e.priority),e.state===null?delete r.state:e.state!==void 0&&(r.state=e.state),r.priority===void 0&&r.state===void 0?delete n.threadTitle:n.threadTitle=r,Object.keys(n).length===0?null:JSON.stringify(n)}var Ba="regeneration_replaced";var ja="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Ga="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",zn=class extends p{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=o;}},Ct=class extends zn{},Vn=class extends p{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},Wa=new Set(Ir),za=new Set(Rr),Va=new Set(vr),Ka=new Set(Ar),Ja=50,Ho=100,Uo=280,Fo=40,Ya=new Set(xr),Zt=["queued","running"],Xa=["success","completed","done","failed","error"];function Wn(t){return Ya.has(t)}function N(t){throw new p("VALIDATION",t)}function ge(t){throw new p("NOT_FOUND",t)}function w(t,e){(typeof t!="string"||t.trim().length===0)&&N(`${e} is required`);}function At(t={}){let e=t.actor??t,n=e.actorType??"system";return Wa.has(n)||N(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&N("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Qa(t){w(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&w(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&N("title must not be empty"),t.title.length>120&&N("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!qn(t.priority)&&N(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Bn(t.state)&&N(`invalid state: ${String(t.state)}`);}function Za(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&N("beforeSeq and afterSeq cannot be used together");for(let[n,r]of [["beforeSeq",t.beforeSeq],["afterSeq",t.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&N(`${n} must be a non-negative integer`);let e=t.limit??Ja;return (!Number.isInteger(e)||e<1||e>Ho)&&N(`limit must be between 1 and ${Ho}`),e}function Kn(t){typeof t!="string"&&N("text is required");let e=t.trim();return e.length===0&&N("text must not be empty"),e.length>Uo&&N(`text must be at most ${Uo} characters`),e}function Me(t,e){return w(t??"",e),t}function Jn(t){Ka.has(t)||N(`invalid highlight kind: ${String(t)}`);}function ed(t){Va.has(t)||N(`invalid highlight source: ${String(t)}`);}function td(t){w(t.threadId,"threadId"),w(t.workspaceId,"workspaceId");let e=t.source??"manual";ed(e),Jn(t.kind);let n=Kn(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let u=t.taskId??(r&&o&&r===o?r:void 0),g=Me(u,"taskId");return (r!==g||o!==g)&&N("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:g,coversToTaskId:g,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=Me(r,"coversFromTaskId"),i=Me(o,"coversToTaskId"),d=t.sourceTaskId??s,l=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return Me(d??void 0,"sourceTaskId"),Me(l??void 0,"detectorVersion"),Me(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:d,detectorVersion:l,contentFingerprint:c}}function nd(t,e){(!t||typeof t!="object")&&N(`candidates[${e}] is required`),Jn(t.kind);let n=Kn(t.text),r=Me(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Me(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Me(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Do("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return w(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function rd(t){Array.isArray(t)||N("candidates must be an array"),t.length>Fo&&N(`candidates must contain at most ${Fo} items`);let e=new Map;for(let[n,r]of t.entries()){let o=nd(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function bt(t){let e=jn(t.metadata);return {threadId:t.id,workspaceId:t.workspace_id,title:t.title,priority:e.priority??null,state:e.state??null,metadata:t.metadata,titleLocked:t.title_locked===1,updatedAt:t.updated_at}}function od(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&N("event payload must be a JSON object"),e}catch(e){throw new p("VALIDATION","event payload must be JSON serializable",e)}}function xt(t,e){return t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${b.seq}), 0)`}).from(b).where(drizzleOrm.eq(b.thread_id,e)).get()?.maxSeq??0}function St(t,e){return !!t.select({id:b.id}).from(b).where(drizzleOrm.eq(b.thread_id,e)).limit(1).get()}function Qe(t,e){za.has(e.type)||N(`invalid thread event type: ${String(e.type)}`);let n=It("the");t.insert(b).values({id:n,thread_id:e.threadId,seq:e.seq,type:e.type,actor_type:e.actorType,actor_id:e.actorId,task_id:e.taskId??null,highlight_id:e.highlightId??null,payload_json:od(e.payload),created_at:e.createdAt}).run();let r=t.select().from(b).where(drizzleOrm.eq(b.id,n)).get();if(!r)throw new p("DB_ERROR","Thread event insert did not return a row");return r}function Ot(t,e,n,r,o){let s=bt(e);Qe(t,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function tn(t){return {highlightId:t.id,source:t.source,kind:t.kind,status:t.status,coversFromTaskId:t.covers_from_task_id,coversToTaskId:t.covers_to_task_id,revision:t.revision,...t.dismissed_at===null?{}:{dismissedAt:t.dismissed_at}}}function en(t,e,n,r,o,s,i){let d=o==="thread.highlight.created"?tn(e):{before:i?tn({...e,...i,id:e.id}):void 0,after:tn(e)};return Qe(t,{threadId:e.thread_id,seq:s,type:o,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:d})}function sd(t,e,n,r,o,s){return Qe(t,{threadId:e.thread_id,seq:o,type:"thread.highlight.deleted",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:tn(e),...s??{}}})}var nn=class extends te{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs.existsSync(n))throw new p("NOT_FOUND","Database not found");if(e){let o=Ae.dirname(n);fs.existsSync(o)||fs.mkdirSync(o,{recursive:true});}let r=P(n);if(e)try{fe(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=drizzleOrm.eq(h.id,n),s=r===void 0?o:r===null?drizzleOrm.and(o,drizzleOrm.isNull(h.workspace_id)):drizzleOrm.and(o,drizzleOrm.eq(h.workspace_id,r));return e.select().from(h).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(A).where(drizzleOrm.eq(A.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(w(e,"threadId"),!fs.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:h.workspace_id}).from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(w(e,"threadId"),!fs.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?bt(o):null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Qa(e);let n=At(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||ge(`Thread ${e.threadId} not found`);let d=bt(i),l=e.title!==void 0,c=l&&e.title!==d.title,u=l&&i.title_locked!==1,g=e.priority!==void 0&&e.priority!==d.priority,f=e.state!==void 0&&e.state!==d.state,m=c||g||f;if(!m&&!u)return d;let R=i.metadata;(g||f)&&(R=Mo(i.metadata,{priority:e.priority,state:e.state}));let x={};if(m&&(x.metadata=R,x.updated_at=r),c&&(x.title=e.title),l&&(x.title_locked=1),s.update(h).set(x).where(e.workspaceId===void 0?drizzleOrm.eq(h.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(h.id,e.threadId),drizzleOrm.isNull(h.workspace_id)):drizzleOrm.and(drizzleOrm.eq(h.id,e.threadId),drizzleOrm.eq(h.workspace_id,e.workspaceId))).run(),!m){let B={...i,title_locked:1};return bt(B)}let I=xt(s,i.id)+1;St(s,i.id)||(Ot(s,i,n,r,I),I+=1),c&&(Qe(s,{threadId:i.id,seq:I,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),I+=1),g&&(Qe(s,{threadId:i.id,seq:I,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),I+=1),f&&Qe(s,{threadId:i.id,seq:I,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let M={...i,title:c?e.title:i.title,metadata:R,title_locked:l?1:i.title_locked,updated_at:r};return bt(M)},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(w(e,"threadId"),!fs.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${b.seq}), 0)`}).from(b).where(drizzleOrm.eq(b.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(w(e,"threadId"),w(n,"workspaceId"),!fs.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:a.id,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.started_at,completedAt:a.completed_at}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,Xa),drizzleOrm.or(drizzleOrm.isNull(a.parent_task_id),drizzleOrm.eq(a.parent_task_id,"")),drizzleOrm.sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.asc(a.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){w(e.threadId,"threadId"),w(e.workspaceId,"workspaceId"),w(e.requestId,"requestId"),w(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&w(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findThread(o,e.threadId,e.workspaceId);s||ge(`Thread ${e.threadId} not found`);let i=o.select().from(A).where(drizzleOrm.and(drizzleOrm.eq(A.thread_id,s.id),drizzleOrm.eq(A.request_id,e.requestId))).orderBy(drizzleOrm.desc(A.requested_at),drizzleOrm.desc(A.id)).limit(1).get();if(i)return {run:i,created:!1};let d=o.select().from(A).where(drizzleOrm.and(drizzleOrm.eq(A.thread_id,s.id),drizzleOrm.inArray(A.status,Zt))).orderBy(drizzleOrm.asc(A.requested_at),drizzleOrm.asc(A.id)).limit(1).get();if(d)throw new Vn(d);let l=e.runId??It("thr");o.insert(A).values({id:l,thread_id:s.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let c=o.select().from(A).where(drizzleOrm.eq(A.id,l)).get();if(!c)throw new p("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to create highlight regeneration run",o)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(w(e,"runId"),n!==void 0&&w(n,"workspaceId"),!fs.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(w(e,"threadId"),w(n,"workspaceId"),w(r,"requestId"),!fs.existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(A).where(drizzleOrm.and(drizzleOrm.eq(A.thread_id,e),drizzleOrm.eq(A.request_id,r))).orderBy(drizzleOrm.desc(A.requested_at),drizzleOrm.desc(A.id)).limit(1).get()??null:null}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to read highlight regeneration request",s)}finally{o.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){w(e,"runId"),n!==void 0&&w(n,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findRegenerationRun(s,e,n);if(i||ge(`Highlight regeneration run ${e} not found`),Wn(i.status)||N(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(A).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq(A.id,i.id),drizzleOrm.eq(A.status,"queued"))).run();let d=s.select().from(A).where(drizzleOrm.eq(A.id,i.id)).get();if(!d)throw new p("DB_ERROR","Highlight regeneration run start did not return a row");return d},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){w(e.runId,"runId"),w(e.errorCode,"errorCode"),e.workspaceId!==void 0&&w(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findRegenerationRun(o,e.runId,e.workspaceId);if(s||ge(`Highlight regeneration run ${e.runId} not found`),Wn(s.status)||N(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(A).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq(A.id,s.id),drizzleOrm.inArray(A.status,Zt))).run();let i=o.select().from(A).where(drizzleOrm.eq(A.id,s.id)).get();if(!i)throw new p("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=ja){w(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(A).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray(A.status,Zt)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){w(e.runId,"runId"),w(e.threadId,"threadId"),w(e.workspaceId,"workspaceId"),w(e.detectorVersion,"detectorVersion");let n=rd(e.candidates),r=At(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let d=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!d||d.thread_id!==e.threadId)&&ge(`Highlight regeneration run ${e.runId} not found`),Wn(d.status)||N(`invalid highlight regeneration status: ${d.status}`),d.status==="failed")throw new p("CONFLICT","Highlight regeneration run has already failed");if(d.status==="completed")return {run:d,deletedCount:0,createdCount:0,previousAutoCount:d.previous_auto_count??0,newAutoCount:d.new_auto_count??0};s=!0;let l=this.findThread(i,e.threadId,e.workspaceId);l||ge(`Thread ${e.threadId} not found`),d.detector_version!==e.detectorVersion&&N("detectorVersion does not match the regeneration run");let c=i.select().from(E).where(drizzleOrm.eq(E.thread_id,l.id)).orderBy(drizzleOrm.asc(E.created_at),drizzleOrm.asc(E.id)).all(),u=new Set(n.map(O=>O.contentFingerprint)),g=c.filter(O=>O.source==="auto"&&O.status==="active"&&O.revision===0&&!u.has(O.content_fingerprint??"")),f=c.filter(O=>O.source==="auto"&&O.status==="active").length,m=new Set(c.filter(O=>!g.includes(O)&&O.content_fingerprint).map(O=>O.content_fingerprint)),R=n.filter(O=>!m.has(O.contentFingerprint)),x=new Date().toISOString(),I=xt(i,l.id)+1;St(i,l.id)||(Ot(i,l,r,x,I),I+=1);for(let O of g)i.delete(E).where(drizzleOrm.eq(E.id,O.id)).run(),sd(i,O,r,x,I,{runId:e.runId,reason:Ba}),I+=1;let M=0,B=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let O of R){let Xn=It("thl");i.insert(E).values({id:Xn,thread_id:l.id,source:"auto",kind:O.kind,status:"active",text:O.text,covers_from_task_id:O.coversFromTaskId,covers_to_task_id:O.coversToTaskId,revision:0,created_at:x,updated_at:x,agent_id:B,source_task_id:O.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:O.contentFingerprint,dismissed_at:null}).run();let Qn=i.select().from(E).where(drizzleOrm.eq(E.id,Xn)).get();if(!Qn)throw new p("DB_ERROR","Regenerated highlight insert did not return a row");en(i,Qn,r,x,"thread.highlight.created",I),I+=1,M+=1;}let ee=i.select().from(E).where(drizzleOrm.eq(E.thread_id,l.id)).all().filter(O=>O.source==="auto"&&O.status==="active").length;Qe(i,{threadId:l.id,seq:I,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:x,payload:{runId:d.id,detectorVersion:e.detectorVersion,previousAutoCount:f,newAutoCount:ee,deletedCount:g.length,createdCount:M}}),i.update(A).set({status:"completed",started_at:d.started_at??x,completed_at:x,error_code:null,previous_auto_count:f,new_auto_count:ee}).where(drizzleOrm.and(drizzleOrm.eq(A.id,d.id),drizzleOrm.inArray(A.status,Zt))).run();let $e=i.select().from(A).where(drizzleOrm.eq(A.id,d.id)).get();if(!$e)throw new p("DB_ERROR","Highlight regeneration completion did not return a row");return {run:$e,deletedCount:g.length,createdCount:M,previousAutoCount:f,newAutoCount:ee}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Ga});}catch{}throw i instanceof p?i:new p("DB_ERROR","Failed to complete highlight regeneration",i)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;w(o.threadId,"threadId"),w(o.workspaceId,"workspaceId");let s=Za(o);if(!fs.existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let d=i.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${b.seq}), 0)`}).from(b).where(drizzleOrm.eq(b.thread_id,o.threadId)).get()?.maxSeq??0,l;o.beforeSeq!==void 0?l=i.db.select().from(b).where(drizzleOrm.and(drizzleOrm.eq(b.thread_id,o.threadId),drizzleOrm.lt(b.seq,o.beforeSeq))).orderBy(drizzleOrm.desc(b.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?l=i.db.select().from(b).where(drizzleOrm.and(drizzleOrm.eq(b.thread_id,o.threadId),drizzleOrm.sql`${b.seq} > ${o.afterSeq}`)).orderBy(drizzleOrm.asc(b.seq)).limit(s+1).all():l=i.db.select().from(b).where(drizzleOrm.eq(b.thread_id,o.threadId)).orderBy(drizzleOrm.desc(b.seq)).limit(s+1).all().reverse();let c=l.length>s,u=o.afterSeq!==void 0?l.slice(0,s):c?l.slice(1):l,g=!1,f=u[0];return f&&(g=!!i.db.select({id:b.id}).from(b).where(drizzleOrm.and(drizzleOrm.eq(b.thread_id,o.threadId),drizzleOrm.lt(b.seq,f.seq))).limit(1).get()),{items:u,latestSeq:d,hasMoreOlder:g}}catch(d){throw d instanceof p?d:new p("DB_ERROR","Failed to list thread timeline",d)}finally{i.close();}}listEvents(e,n,r){return this.listTimeline(e,n,r)}getTimeline(e,n,r){return this.listTimeline(e,n,r)}createHighlight(e){let n=td(e),r=At(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);if(d||ge(`Thread ${e.threadId} not found`),n.source==="auto"){let f=i.select().from(E).where(drizzleOrm.and(drizzleOrm.eq(E.thread_id,e.threadId),drizzleOrm.eq(E.source_task_id,n.sourceTaskId),drizzleOrm.eq(E.detector_version,n.detectorVersion),drizzleOrm.eq(E.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc(E.created_at),drizzleOrm.asc(E.id)).limit(1).get();if(f)return f}let l=e.id??It("thl"),c={id:l,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(E).values(c).run();let u=i.select().from(E).where(drizzleOrm.eq(E.id,l)).get();if(!u)throw new p("DB_ERROR","Highlight insert did not return a row");let g=xt(i,d.id)+1;return St(i,d.id)||(Ot(i,d,r,o,g),g+=1),en(i,u,r,o,"thread.highlight.created",g),u},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){w(e.threadId,"threadId"),w(e.workspaceId,"workspaceId"),w(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&N("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&N("highlight update requires at least one field"),e.kind!==void 0&&Jn(e.kind);let n=e.text===void 0?void 0:Kn(e.text),r=At(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);d||ge(`Thread ${e.threadId} not found`);let l=i.select().from(E).where(drizzleOrm.and(drizzleOrm.eq(E.id,e.highlightId),drizzleOrm.eq(E.thread_id,d.id))).limit(1).get();if(l||ge(`Highlight ${e.highlightId} not found`),l.revision!==e.expectedRevision)throw new Ct(d.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new Ct(d.id,l.id,e.expectedRevision,l.revision);let c=e.kind??l.kind,u=n??l.text,g=e.coversFromTaskId??l.covers_from_task_id,f=e.coversToTaskId??l.covers_to_task_id;(!u||g.length===0||f.length===0)&&N("highlight projection is incomplete");let m=c!==l.kind||u!==l.text||g!==l.covers_from_task_id||f!==l.covers_to_task_id,R=r.actorType==="user"&&l.source==="auto"&&m?"manual":l.source;if(!(m||R!==l.source))return l;let I=l.revision+1;i.update(E).set({source:R,kind:c,text:u,covers_from_task_id:g,covers_to_task_id:f,revision:I,updated_at:o}).where(drizzleOrm.and(drizzleOrm.eq(E.id,l.id),drizzleOrm.eq(E.revision,l.revision))).run();let M=i.select().from(E).where(drizzleOrm.eq(E.id,l.id)).get();if(!M)throw new p("DB_ERROR","Highlight update did not return a row");let B=xt(i,d.id)+1;return St(i,d.id)||(Ot(i,d,r,o,B),B+=1),en(i,M,r,o,"thread.highlight.updated",B,l),M},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){w(e.threadId,"threadId"),w(e.workspaceId,"workspaceId"),w(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&N("expectedRevision must be a non-negative integer");let n=At(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||ge(`Thread ${e.threadId} not found`);let d=s.select().from(E).where(drizzleOrm.and(drizzleOrm.eq(E.id,e.highlightId),drizzleOrm.eq(E.thread_id,i.id))).limit(1).get();if(d||ge(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new Ct(i.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let l=d.revision+1;s.update(E).set({status:"dismissed",text:null,revision:l,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(E.id,d.id),drizzleOrm.eq(E.revision,d.revision))).run();let c=s.select().from(E).where(drizzleOrm.eq(E.id,d.id)).get();if(!c)throw new p("DB_ERROR","Highlight dismissal did not return a row");let u=xt(s,i.id)+1;return St(s,i.id)||(Ot(s,i,n,r,u),u+=1),en(s,c,n,r,"thread.highlight.deleted",u,d),c},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(w(e,"threadId"),w(n,"workspaceId"),r.taskId!==void 0&&w(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&w(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&w(r.coversToTaskId,"coversToTaskId"),!fs.existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,n))return null;let i=o.db.select().from(E).where(drizzleOrm.and(drizzleOrm.eq(E.thread_id,e),drizzleOrm.eq(E.status,"active"))).orderBy(drizzleOrm.asc(E.created_at),drizzleOrm.asc(E.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let d=o.db.all(drizzleOrm.sql`
375
375
  SELECT id, started_at FROM tasks WHERE thread_id = ${e}
376
376
  ORDER BY started_at ASC, id ASC
377
- `),l=new Map(d.map((f,m)=>[f.id,m])),c=r.taskId===void 0?void 0:l.get(r.taskId),u=r.coversFromTaskId===void 0?void 0:l.get(r.coversFromTaskId),g=r.coversToTaskId===void 0?void 0:l.get(r.coversToTaskId);return i.filter(f=>{let m=l.get(f.covers_from_task_id),R=l.get(f.covers_to_task_id);if(m===void 0||R===void 0)return !1;let x=Math.min(m,R),I=Math.max(m,R);return !(c!==void 0&&(c<x||c>I)||u!==void 0&&I<u||g!==void 0&&x>g)})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};var U=class extends p{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Bo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function fd(){let t=crypto.randomBytes(16),e="";for(let n of t)e+=Bo[n%Bo.length];return e.slice(0,12)}function jo(){return `c_${fd()}`}function hd(t){return typeof t=="string"&&kn.includes(t)}function md(t){return typeof t=="string"&&yn.includes(t)}function lt(t){if(!hd(t))throw new U("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Go(t){if(!md(t))throw new U("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function Wo(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new U("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function ct(t){if(typeof t!="string"||t.trim().length===0)throw new U("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function rn(t){if(typeof t!="string"||t.trim().length===0)throw new U("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function We(t,e){return drizzleOrm.and(drizzleOrm.eq(_.code_group,t),drizzleOrm.or(drizzleOrm.isNull(_.workspace_id),drizzleOrm.eq(_.workspace_id,e)))}var on=class extends te{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs.existsSync(n))throw new p("NOT_FOUND","Database not found");e&&fs.mkdirSync(Ae.dirname(n),{recursive:true});let r=P(n);if(e)try{fe(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(lt(e),ct(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(_).where(drizzleOrm.and(We(e,n),drizzleOrm.eq(_.is_archived,0))).orderBy(drizzleOrm.asc(_.sort_order),drizzleOrm.asc(_.code)).all()}catch(o){throw new p("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(lt(e),ct(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(_).where(We(e,n)).orderBy(drizzleOrm.asc(_.sort_order),drizzleOrm.asc(_.code)).all()}catch(o){throw new p("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(lt(n),ct(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)rn(o);if(new Set(e.codes).size!==e.codes.length)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(_).where(We(n,e.workspaceId)).all(),i=s.filter(m=>m.is_archived===0),d=new Set(s.map(m=>m.code)),l=new Set(i.map(m=>m.code)),c=e.codes.find(m=>!d.has(m));if(c)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${c}`);if(e.codes.length!==i.length||e.codes.some(m=>!l.has(m)))throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let u=new Map(i.map(m=>[m.code,m])),g=e.codes.map(m=>{let R=u.get(m);if(!R)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${m}`);return R}),f;for(let[m,R]of g.entries())R.sort_order!==m&&(f??=new Date().toISOString(),o.update(_).set({sort_order:m,updated_at:f}).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,n),drizzleOrm.eq(_.code,R.code))).run());return o.select().from(_).where(We(n,e.workspaceId)).orderBy(drizzleOrm.asc(_.sort_order),drizzleOrm.asc(_.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(lt(e),rn(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).limit(1).get()??null}catch(o){throw new p("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){ct(e.workspaceId);let n=Wo(e.name);Go(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:_.code}).from(_).where(drizzleOrm.and(We("THREAD_STATE",e.workspaceId),drizzleOrm.eq(_.is_archived,0),drizzleOrm.eq(_.code_name,n))).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=o.select({maxSortOrder:drizzleOrm.sql`max(${_.sort_order})`}).from(_).where(We("THREAD_STATE",e.workspaceId)).get(),d=new Date().toISOString(),l=jo();for(;o.select({code:_.code}).from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,"THREAD_STATE"),drizzleOrm.eq(_.code,l))).limit(1).get();)l=jo();o.insert(_).values({code_group:"THREAD_STATE",code:l,code_name:n,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:d,updated_at:d}).run();let c=o.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,"THREAD_STATE"),drizzleOrm.eq(_.code,l))).limit(1).get();if(!c)throw new p("DB_ERROR","Created common code could not be read back");return c},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(lt(e.group),rn(e.code),ct(e.workspaceId),e.name===void 0&&e.color===void 0)throw new U("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:Wo(e.name);e.color!==void 0&&Go(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e.group),drizzleOrm.eq(_.code,e.code))).limit(1).get();if(!s)throw new U("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(s,e.workspaceId),n===null&&s.is_builtin!==1)throw new U("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let l=drizzleOrm.and(We(e.group,e.workspaceId),drizzleOrm.eq(_.is_archived,0));if(o.select({code:_.code}).from(_).where(drizzleOrm.and(l,drizzleOrm.eq(_.code_name,n),drizzleOrm.sql`${_.code} <> ${e.code}`)).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`)}let i={updated_at:new Date().toISOString()};e.name!==void 0&&(i.code_name=n??null),e.color!==void 0&&(i.color=e.color),o.update(_).set(i).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e.group),drizzleOrm.eq(_.code,e.code))).run();let d=o.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e.group),drizzleOrm.eq(_.code,e.code))).limit(1).get();if(!d)throw new p("DB_ERROR","Updated common code could not be read back");return d},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(lt(e),rn(n),ct(r),typeof o!="boolean")throw new U("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let d=i.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).limit(1).get();if(!d)throw new U("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(d.is_builtin===1)throw new U("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(d,r),!o&&d.code_name!==null&&i.select({code:_.code}).from(_).where(drizzleOrm.and(We(e,r),drizzleOrm.eq(_.is_archived,0),drizzleOrm.eq(_.code_name,d.code_name),drizzleOrm.ne(_.code,n))).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${d.code_name}`);i.update(_).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).run();let l=i.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).limit(1).get();if(!l)throw new p("DB_ERROR","Archived common code could not be read back");return l},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to archive common code",i)}finally{s.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new U("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function yd(t){return t.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
377
+ `),l=new Map(d.map((f,m)=>[f.id,m])),c=r.taskId===void 0?void 0:l.get(r.taskId),u=r.coversFromTaskId===void 0?void 0:l.get(r.coversFromTaskId),g=r.coversToTaskId===void 0?void 0:l.get(r.coversToTaskId);return i.filter(f=>{let m=l.get(f.covers_from_task_id),R=l.get(f.covers_to_task_id);if(m===void 0||R===void 0)return !1;let x=Math.min(m,R),I=Math.max(m,R);return !(c!==void 0&&(c<x||c>I)||u!==void 0&&I<u||g!==void 0&&x>g)})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};var U=class extends p{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Bo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function fd(){let t=crypto.randomBytes(16),e="";for(let n of t)e+=Bo[n%Bo.length];return e.slice(0,12)}function jo(){return `c_${fd()}`}function hd(t){return typeof t=="string"&&kn.includes(t)}function md(t){return typeof t=="string"&&yn.includes(t)}function lt(t){if(!hd(t))throw new U("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Go(t){if(!md(t))throw new U("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function Wo(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new U("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function ct(t){if(typeof t!="string"||t.trim().length===0)throw new U("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function rn(t){if(typeof t!="string"||t.trim().length===0)throw new U("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function We(t,e){return drizzleOrm.and(drizzleOrm.eq(_.code_group,t),drizzleOrm.or(drizzleOrm.isNull(_.workspace_id),drizzleOrm.eq(_.workspace_id,e)))}var on=class extends te{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs.existsSync(n))throw new p("NOT_FOUND","Database not found");e&&fs.mkdirSync(Ae.dirname(n),{recursive:true});let r=P(n);if(e)try{fe(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(lt(e),ct(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(_).where(drizzleOrm.and(We(e,n),drizzleOrm.eq(_.is_archived,0))).orderBy(drizzleOrm.asc(_.sort_order),drizzleOrm.asc(_.code)).all()}catch(o){throw new p("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(lt(e),ct(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(_).where(We(e,n)).orderBy(drizzleOrm.asc(_.sort_order),drizzleOrm.asc(_.code)).all()}catch(o){throw new p("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(lt(n),ct(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)rn(o);if(new Set(e.codes).size!==e.codes.length)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(_).where(We(n,e.workspaceId)).all(),i=s.filter(m=>m.is_archived===0),d=new Set(s.map(m=>m.code)),l=new Set(i.map(m=>m.code)),c=e.codes.find(m=>!d.has(m));if(c)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${c}`);if(e.codes.length!==i.length||e.codes.some(m=>!l.has(m)))throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let u=new Map(i.map(m=>[m.code,m])),g=e.codes.map(m=>{let R=u.get(m);if(!R)throw new U("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${m}`);return R}),f;for(let[m,R]of g.entries())R.sort_order!==m&&(f??=new Date().toISOString(),o.update(_).set({sort_order:m,updated_at:f}).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,n),drizzleOrm.eq(_.code,R.code))).run());return o.select().from(_).where(We(n,e.workspaceId)).orderBy(drizzleOrm.asc(_.sort_order),drizzleOrm.asc(_.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(lt(e),rn(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).limit(1).get()??null}catch(o){throw new p("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){ct(e.workspaceId);let n=Wo(e.name);Go(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:_.code}).from(_).where(drizzleOrm.and(We("THREAD_STATE",e.workspaceId),drizzleOrm.eq(_.is_archived,0),drizzleOrm.eq(_.code_name,n))).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=o.select({maxSortOrder:drizzleOrm.sql`max(${_.sort_order})`}).from(_).where(We("THREAD_STATE",e.workspaceId)).get(),d=new Date().toISOString(),l=jo();for(;o.select({code:_.code}).from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,"THREAD_STATE"),drizzleOrm.eq(_.code,l))).limit(1).get();)l=jo();o.insert(_).values({code_group:"THREAD_STATE",code:l,code_name:n,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:d,updated_at:d}).run();let c=o.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,"THREAD_STATE"),drizzleOrm.eq(_.code,l))).limit(1).get();if(!c)throw new p("DB_ERROR","Created common code could not be read back");return c},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(lt(e.group),rn(e.code),ct(e.workspaceId),e.name===void 0&&e.color===void 0)throw new U("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:Wo(e.name);e.color!==void 0&&Go(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e.group),drizzleOrm.eq(_.code,e.code))).limit(1).get();if(!s)throw new U("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(s,e.workspaceId),n===null&&s.is_builtin!==1)throw new U("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let l=drizzleOrm.and(We(e.group,e.workspaceId),drizzleOrm.eq(_.is_archived,0));if(o.select({code:_.code}).from(_).where(drizzleOrm.and(l,drizzleOrm.eq(_.code_name,n),drizzleOrm.sql`${_.code} <> ${e.code}`)).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`)}let i={updated_at:new Date().toISOString()};e.name!==void 0&&(i.code_name=n??null),e.color!==void 0&&(i.color=e.color),o.update(_).set(i).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e.group),drizzleOrm.eq(_.code,e.code))).run();let d=o.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e.group),drizzleOrm.eq(_.code,e.code))).limit(1).get();if(!d)throw new p("DB_ERROR","Updated common code could not be read back");return d},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(lt(e),rn(n),ct(r),typeof o!="boolean")throw new U("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let d=i.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).limit(1).get();if(!d)throw new U("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(d.is_builtin===1)throw new U("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(d,r),!o&&d.code_name!==null&&i.select({code:_.code}).from(_).where(drizzleOrm.and(We(e,r),drizzleOrm.eq(_.is_archived,0),drizzleOrm.eq(_.code_name,d.code_name),drizzleOrm.ne(_.code,n))).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${d.code_name}`);i.update(_).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).run();let l=i.select().from(_).where(drizzleOrm.and(drizzleOrm.eq(_.code_group,e),drizzleOrm.eq(_.code,n))).limit(1).get();if(!l)throw new p("DB_ERROR","Archived common code could not be read back");return l},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to archive common code",i)}finally{s.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new U("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function yd(t){return t.replace(/<crewx_thread_context[^>]*>[\s\S]*?<\/crewx_thread_context>/g,"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
378
378
  `).filter(o=>!(o.startsWith("Loaded ")&&o.includes("layouts from")||o.includes("[dotenv@")||o.includes("[Nest]")&&o.includes("DEBUG")||o.startsWith("Registered custom layout:")||o.startsWith("Updated custom layout:"))).join(`
379
379
  `).trim()}function Td(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.provider;return typeof n=="string"?n:void 0}catch{return}}function wd(t,e,n){if(!t||e==="failed"&&Xt(t,n))return "";let r=t;try{let o=JSON.parse(r);Array.isArray(o)?r=o.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
380
380
  `):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=yd(r);}return r}var sn=class{dbPath;constructor(e){this.dbPath=e??Ae.join(ar.homedir(),".crewx","crewx.db");}getThreadRepo(){return new Qt({dbPath:this.dbPath})}getThreadHistoryRepo(){return new nn({dbPath:this.dbPath})}updateThread(e,n){this.getThreadRepo().updateThread(e,{title:n.title});}async ensureThread(e,n,r){let o=this.getThreadRepo(),s=o.findThreadById(e);if(s){if(s.platform!==n)throw new Error(`Thread '${e}' already exists with platform '${s.platform}' \u2014 cannot change to '${n}' (platform is immutable)`);return {created:false}}return o.ensureThread(e,n,r),{created:true}}async fetchHistory(e,n){let r=n?.limit??100,o=this.getThreadRepo(),s=o.findThreadById(e),i=o.findTopLevelTasks(e,void 0,r),d=new Set(["queued","cancelled"]);i=i.filter(g=>(!g.status||!d.has(g.status))&&(!n?.currentTraceId||g.trace_id!==n.currentTraceId));let l=s?.platform??"cli",c=this.rowsToMessages(i),u=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,s?.workspace_id??null);return {threadId:e,platform:l,messages:c,...u?{highlights:u}:{},metadata:{title:s?.title??void 0,firstMessage:s?.first_message??void 0,lastMessage:s?.last_message??void 0,messageCount:s?.message_count??0,updatedAt:s?.updated_at?new Date(s.updated_at).getTime():void 0}}}async fetchThreadState(e){try{let n=this.getThreadHistoryRepo().getSnapshot(e);if(!n)return;let r=new on({dbPath:this.dbPath}),o=(s,i)=>{try{return r.resolve(s,i)?.code_name||i}catch{return i}};return {...n.title?{title:n.title}:{},...n.priority?{priority:{code:n.priority,name:o("THREAD_PRIORITY",n.priority)}}:{},...n.state?{state:{code:n.state,name:o("THREAD_STATE",n.state)}}:{}}}catch{return}}async fetchHighlights(e){let n=this.getThreadRepo().findThreadById(e);return this.readActiveHighlights(e,n?.workspace_id??null)}async saveUserMessage(e,n,r,o){let{firstMessage:s}=this.getThreadRepo().saveUserMessage(e,n);return {id:e,firstMessage:s}}async saveAssistantMessage(e,n,r,o){return this.getThreadRepo().saveAssistantMessage(e,n),{id:e}}close(){}normalizeStatus(e){if(e&&!["success","completed","done"].includes(e)){if(["failed","error"].includes(e))return "failed";if(e==="running")return "running"}}readActiveHighlights(e,n){if(!n)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,n)??[]).filter(o=>typeof o.text=="string"&&o.text.length>0).map(o=>({id:o.id,text:o.text,kind:o.kind,source:o.source,coversFromTaskId:o.covers_from_task_id,coversToTaskId:o.covers_to_task_id,createdAt:o.created_at}))}catch{return}}rowsToMessages(e){let n=[];for(let r of e){r.prompt&&n.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let o=this.normalizeStatus(r.status),s=Td(r.metadata),i=wd(r.result,o??r.status??null,s);if(i||o==="running"||o==="failed"){let d={agent_id:r.agent_id,task_id:r.id};o&&(d.status=o),o==="failed"&&r.error&&(d.reason=r.error.split(`
@@ -0,0 +1,18 @@
1
+ export declare const PROMPT_TAGS: {
2
+ readonly crewxSystemPrompt: "crewx_system_prompt";
3
+ readonly systemPrompt: "system_prompt";
4
+ readonly threadContext: "crewx_thread_context";
5
+ readonly threadState: "thread_state";
6
+ readonly highlights: "highlights";
7
+ readonly highlight: "highlight";
8
+ readonly omittedTurns: "omitted_turns";
9
+ readonly messages: "messages";
10
+ readonly message: "message";
11
+ readonly userQuery: "user_query";
12
+ readonly execOutput: "exec_output";
13
+ };
14
+ export declare const LEGACY_PROMPT_TAGS: {
15
+ readonly conversationHistory: "conversation_history";
16
+ readonly semanticContinuity: "semantic_continuity";
17
+ readonly execOutput: "exec-output";
18
+ };
@@ -1,4 +1,4 @@
1
- export type TaskErrorCode = 'USAGE_LIMITED' | 'CONTEXT_WINDOW_EXCEEDED' | 'INPUT_TOO_LARGE' | 'MODEL_NOT_SUPPORTED' | 'MODEL_AT_CAPACITY' | 'AUTH_REQUIRED' | 'CLI_NOT_AVAILABLE' | 'CLI_UPDATE_REQUIRED' | 'AGENT_NOT_FOUND' | 'PERMISSION_OR_TRUST' | 'TIMEOUT_OR_STUCK' | 'NETWORK_OR_PROVIDER_TRANSIENT' | 'PROVIDER_CONFIGURATION' | 'PROCESS_FAILED';
1
+ export type TaskErrorCode = 'USAGE_LIMITED' | 'CONTEXT_WINDOW_EXCEEDED' | 'INPUT_TOO_LARGE' | 'MODEL_NOT_SUPPORTED' | 'MODEL_AT_CAPACITY' | 'AUTH_REQUIRED' | 'CLI_NOT_AVAILABLE' | 'CLI_UPDATE_REQUIRED' | 'AGENT_NOT_FOUND' | 'PERMISSION_OR_TRUST' | 'TIMEOUT_OR_STUCK' | 'NETWORK_OR_PROVIDER_TRANSIENT' | 'PROVIDER_CONFIGURATION' | 'AGENT_MODE_RESTRICTED' | 'PROCESS_FAILED';
2
2
  export interface TaskErrorMeta {
3
3
  resetAt?: string | number;
4
4
  model?: string;
@@ -6,6 +6,7 @@ export interface TaskErrorMeta {
6
6
  envKey?: string;
7
7
  upstreamType?: string;
8
8
  upstreamCode?: string | number;
9
+ mode?: string;
9
10
  referenceId?: string;
10
11
  technicalMessage?: string;
11
12
  }
@@ -2860,6 +2860,7 @@ export interface QueryResult {
2860
2860
  code: string;
2861
2861
  message: string;
2862
2862
  providerCode?: string;
2863
+ mode?: string;
2863
2864
  };
2864
2865
  meta: {
2865
2866
  agentId: string;
@@ -2898,6 +2899,7 @@ export interface ExecuteResult {
2898
2899
  code: string;
2899
2900
  message: string;
2900
2901
  providerCode?: string;
2902
+ mode?: string;
2901
2903
  };
2902
2904
  meta: {
2903
2905
  agentId: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewx/sdk",
3
- "version": "0.9.0-rc.93",
3
+ "version": "0.9.0-rc.94",
4
4
  "license": "UNLICENSED",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"
@@ -94,6 +94,7 @@
94
94
  "@modelcontextprotocol/sdk": "1.27.0",
95
95
  "ai": "4.0.0",
96
96
  "drizzle-orm": "0.45.2",
97
+ "dotenv": "17.2.3",
97
98
  "handlebars": "4.7.9",
98
99
  "js-tiktoken": "1.0.21",
99
100
  "js-yaml": "4.1.0",
@@ -26,7 +26,7 @@ layouts:
26
26
  type: boolean
27
27
  default: true
28
28
  template: |
29
- <crewx_system_prompt key="{{vars.security_key}}">
29
+ <crewx_system_prompt>
30
30
  {{#if props.showAgentProfile}}
31
31
  <agent_profile>
32
32
  <identity>
@@ -348,15 +348,7 @@ layouts:
348
348
 
349
349
  ---
350
350
 
351
- {{#if props.showConversationHistory}}
352
- {{#if thread_state.rendered}}
353
- {{{thread_state.rendered}}}
354
- {{/if}}
355
- {{#if semanticContinuity.rendered}}
356
- {{{semanticContinuity.rendered}}}
357
- {{/if}}
358
- {{#if messages.length}}
359
- {{#if has_activity_log}}
351
+ {{#if props.showConversationHistory}}{{#if messages.length}}{{#if has_activity_log}}
360
352
  **Activity log instructions**: If `<activity_log>` contains entries with `reused="ok"`, treat those results as current — do **not** re-run the same tool. Only re-run entries marked `reused="stale"` (file changed) or when you need fresher data than what is shown.
361
353
 
362
354
  {{else}}{{#if thread_id}}
@@ -368,7 +360,23 @@ layouts:
368
360
  </crewx_system_message>
369
361
 
370
362
  {{/if}}{{/if}}
371
- <conversation_history platform="{{platform}}">
363
+ {{/if}}{{/if}}
364
+ </system_prompt>
365
+
366
+ {{#if props.showConversationHistory}}
367
+ {{#if hasThreadContext}}
368
+ <crewx_thread_context{{#if thread_id}} thread_id="{{thread_id}}"{{/if}}>
369
+ {{#if thread_state.rendered}}
370
+ {{{thread_state.rendered}}}
371
+ {{/if}}
372
+ {{#if semanticContinuity.rendered}}
373
+ {{{semanticContinuity.rendered}}}
374
+ {{/if}}
375
+ {{#if messages.length}}
376
+ <messages platform="{{platform}}">
377
+ {{#if semanticContinuity.omittedRendered}}
378
+ {{{semanticContinuity.omittedRendered}}}
379
+ {{/if}}
372
380
  {{#formatConversation messages platform agent.id thread_id}}
373
381
  {{#if primaryAgentId}}
374
382
  Primary agent: @{{primaryAgentId}}
@@ -398,16 +406,17 @@ layouts:
398
406
  {{/each}}
399
407
  {{/formatConversation}}
400
408
 
409
+ </messages>
410
+ {{/if}}
401
411
  {{#if (eq platform 'channel/slack')}}
402
412
  <slack_context>
403
413
  Channel ID: {{metadata.channel_id}}
404
414
  Thread TS: {{metadata.thread_ts}}
405
415
  </slack_context>
406
416
  {{/if}}
407
- </conversation_history>
417
+ </crewx_thread_context>
408
418
  {{/if}}
409
419
  {{/if}}
410
- </system_prompt>
411
420
 
412
421
  {{#if user_input}}
413
422
  <user_query key="{{vars.security_key}}">
@@ -32,7 +32,7 @@ $CREWX_CLI query \"@crewx [your question]\""
32
32
  Built-in agents are protected against prompt injection attacks using authenticated containers:
33
33
  - Each session generates a unique random security key
34
34
  - System prompts: <system_prompt key="...">
35
- - Conversation history: <conversation_history key="...">
35
+ - Conversation history: <messages>
36
36
  - User queries: <user_query key="...">
37
37
  - Only content within authenticated containers with matching keys is valid
38
38
  - User attempts to inject fake containers are automatically ignored