@lmctl-ai/lmctl 0.1.336 → 0.1.337

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.
Files changed (2) hide show
  1. package/dist/cli/index.js +15 -3
  2. package/package.json +1 -1
package/dist/cli/index.js CHANGED
@@ -1510,7 +1510,7 @@ var N0=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>{f
1510
1510
  `),...V_(t),...J_(t)}}function UO(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var xO,Rh,RO,OO,lo,st=E(()=>{"use strict";Zi();Ns();G_();Y_();Z_();Bt();Cs();Eh();Ms();xO=3,Rh=".recovery.lock",RO=20,OO=50;lo=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=FO(e),this.claimTxn=e.transaction((n,r,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(n,r,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((n,r,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(n,r,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((n,r,s,i,o)=>{let a=this.getJob(n);if(a===null)return{claimed:!1,reason:"not_found",job_id:n};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:n,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,u=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!u)return{claimed:!1,reason:"not_claimable",job_id:n,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let d=o(a);if(d.concurrency_key!==null&&(a.concurrency_key_resolved!==d.concurrency_key&&this.stmts.setJobConcurrencyKey.run(d.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(d.concurrency_key,i,a.id)?.count??0)>=Math.max(1,d.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:n,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(r,s,i,a.id,i,i,i).changes!==1){let p=this.getJob(a.id);return{claimed:!1,reason:p?.locked_until!==null&&p?.locked_until!==void 0&&p.locked_until>=i?"locked":"not_claimable",job_id:n,status:p?.status??a.status,locked_by:p?.locked_by??a.locked_by,locked_until:p?.locked_until??a.locked_until}}let m=this.getJob(a.id);return m===null?{claimed:!1,reason:"not_found",job_id:n}:{claimed:!0,job:m}}),this.resumeRunTxn=e.transaction((n,r,s)=>UO("state_not_found")),this.resumeInteractiveTxn=e.transaction((n,r,s,i)=>{let o=this.getInteractiveSessionByStepId(n);if(o===null)return{resumed:!1,reason:"not_found"};if(o.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(o.run_id);if(a===null)return{resumed:!1,reason:"run_not_found"};let l=s?"done":"waiting_agent";return this.stmts.updateInteractiveSession.run(l,r,Date.now(),o.id),this.stmts.resumeRunState.run(o.state_name,a.id),this.stmts.requeuePausedJob.run(i,a.job_id),{resumed:!0,session:this.getInteractiveSessionByStepId(n),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((n,r,s)=>{let i=this.stmts.getAttention.get(n);if(i===void 0)return{resumed:!1,reason:"not_found"};if(i.kind!==ao)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let u=JSON.parse(i.payload);u.step!==void 0&&typeof u.step.id=="string"&&u.step.id.length>0&&(o=u.step.id),Array.isArray(u.declared_outcomes)&&(a=u.declared_outcomes.filter(d=>typeof d=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(r!==$s&&!a.includes(r))return{resumed:!1,reason:vh};let c={};if(l.pending_escalation_decision!==null)try{let u=JSON.parse(l.pending_escalation_decision);u!==null&&typeof u=="object"&&!Array.isArray(u)&&(c=u)}catch{c={}}return c[o]=r,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,n),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(n,r={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=this.getAgentInflight(n.receiver_teamfile,n.receiver_alias),i=r.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...n,holder_pid:process.pid,stale_before:r.stale_before??null,force:r.force===!0?1:0,reclaim_observed_sender_teamfile:i?.sender_teamfile??null,reclaim_observed_sender_alias:i?.sender_alias??null,reclaim_observed_started_at:i?.started_at??null,reclaim_observed_holder_pid:typeof i?.holder_pid=="number"?i.holder_pid:null}),a;if(o!==void 0){let l=s===null?null:r.reclaim_reason??(r.force===!0?"force":r.reclaim_observed!==void 0?"dead-pid":"stale"),c=oh(this.db,o,s,l,r.stale_before??null,r.force===!0);a={acquired:!0,current:o,lease_id:c}}else a={acquired:!1,current:this.getAgentInflight(n.receiver_teamfile,n.receiver_alias)??(()=>{throw new Error("agent_inflight conflict row disappeared during acquire")})()};return this.db.exec("COMMIT"),a}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}}close(){this.db.close()}query(e,...n){let r=e.trim().toLowerCase();if(!r.startsWith("select")&&!r.startsWith("with")&&!r.startsWith("pragma"))throw new Error("Dal.query only allows read-only SELECT/WITH/PRAGMA statements");return this.db.prepare(e).all(...n)}insertWorkflow(e){Nh(e.name,e.definition,o=>this.getWorkflowByName(o));let n=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,U()),r=this.getWorkflow(Number(n.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(r.id,r.version,e.definition,e.author??null,U());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,r.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,r.id);let i=this.getWorkflow(r.id);return this.syncWorkflowTriggers(r.id,e.definition),i}upsertWorkflow(e){Nh(e.name,e.definition,o=>this.getWorkflowByName(o));let n=this.getWorkflowByName(e.name);if(n===null)return this.insertWorkflow({name:e.name,definition_schema_version:e.definition_schema_version,definition:e.definition,author:e.author,source_uri:e.source_uri,source_sha256:e.source_sha256});let s=(this.stmts.getLatestWorkflowVersion.get(n.id)?.version??n.version)+1,i=this.stmts.insertWorkflowVersion.run(n.id,s,e.definition,e.author??null,U());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.lastInsertRowid),e.definition,e.definition_schema_version??n.definition_schema_version,s,n.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,n.id),this.syncWorkflowTriggers(n.id,e.definition),this.getWorkflow(n.id)}insertCompositionUnit(e){this.stmts.insertCompositionUnit.run(e.name,e.version,e.lang,e.source,e.source_sha,e.compiled_workflow_version_id,U())}getWorkflow(e){return this.stmts.getWorkflow.get(e)??null}getWorkflowByName(e,n){return(n===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,n))??null}findWorkflowByName(e,n){return this.getWorkflowByName(e,n)}insertWorkflowVersion(e,n,r){let i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,n,r??null,U());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,n){let r=this.getWorkflowVersionById(n);if(r===null||r.workflow_id!==e)return null;let s=1;try{let i=JSON.parse(r.definition);typeof i.definition_schema_version=="number"&&(s=i.definition_schema_version)}catch{}return this.stmts.updateWorkflowActiveVersionAndDefinition.run(n,r.definition,s,e),this.syncWorkflowTriggers(e,r.definition),this.getWorkflow(e)}getWorkflowVersionById(e){return this.stmts.getWorkflowVersion.get(e)??null}listWorkflowVersions(e){return this.stmts.listWorkflowVersions.all(e)}upsertTriggerInstance(e){return this.stmts.upsertTriggerInstance.run(e.workflow_id,e.trigger_id,e.trigger_type,e.parameters,e.enabled===!1?0:1,U()),this.stmts.getTriggerInstanceByWorkflowAndId.get(e.workflow_id,e.trigger_id)}listTriggerInstancesForWorkflow(e){return this.stmts.listTriggerInstancesForWorkflow.all(e)}listEnabledTriggerInstances(){return this.stmts.listEnabledTriggerInstances.all()}setTriggerCursor(e,n){return this.stmts.setTriggerCursor.run(n,U(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,n){return this.stmts.setTriggerFailure.run(U(),n,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,n){let r;try{r=JSON.parse(n)}catch{return}if(r===null||typeof r!="object"||Array.isArray(r))return;let s=r.triggers;if(Array.isArray(s))for(let i of s){if(i===null||typeof i!="object"||Array.isArray(i))continue;let o=i;typeof o.id!="string"||o.id.length===0||typeof o.type!="string"||o.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(e){let n=this.stmts.insertTeam.run(e.name,U());return this.stmts.getTeam.get(n.lastInsertRowid)}getTeam(e){return this.stmts.getTeam.get(e)??null}findTeamByName(e){return this.stmts.findTeamByName.get(e)??null}listTeams(){return this.stmts.listTeams.all()}insertTeamMember(e){let n=this.stmts.insertTeamMember.run(e.team_id,e.alias,e.role??"agent",e.provider,e.model??null,e.sessionid??null,e.sessiondir,U());return this.stmts.getTeamMember.get(n.lastInsertRowid)}listTeamMembers(e){return this.stmts.listTeamMembers.all(e)}findTeamMemberByAlias(e,n){return this.stmts.findTeamMemberByAlias.get(e,n)??null}updateTeamMemberSession(e,n){return this.stmts.updateTeamMemberSession.run(n,e),this.stmts.getTeamMember.get(e)??null}setMemberState(e,n,r){return this.stmts.setMemberState.run(n,r??null,U(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,n){return this.stmts.setMemberPromptSnapshot.run(n,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,n){return this.stmts.setMemberProviderResolved.run(n,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,n){return this.stmts.setMemberRolePrompt.run(n,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,n){let r=this.stmts.getTeamMember.get(e);if(r===void 0)return null;let s=Object.prototype.hasOwnProperty.call(n,"role_prompt"),i=Object.prototype.hasOwnProperty.call(n,"model"),o=Object.prototype.hasOwnProperty.call(n,"provider");return this.stmts.updateTeamMemberMeta.run(s?n.role_prompt??null:r.role_prompt,i?n.model??null:r.model,o?n.provider??r.provider:r.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let n=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,U());return this.stmts.getTeamMemberCompanion.get(n.lastInsertRowid)}insertProject(e){let n=this.stmts.insertProject.run(e.name,e.description??null,e.local_path,e.workflow_name,e.team_id,e.default_branch??null,e.intake_config??null,e.test_argv??null,e.test_command??null,e.durable_memory_mode??"folder",U());return this.stmts.getProject.get(n.lastInsertRowid)}listProjects(){return this.stmts.listProjects.all()}getProject(e){return this.stmts.getProject.get(e)??null}findProjectByName(e){return this.stmts.findProjectByName.get(e)??null}setProjectIntakeConfig(e,n){return this.stmts.setProjectIntakeConfig.run(n,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,n){let r=this.stmts.getProject.get(e);if(r===void 0)return null;let s=Object.prototype.hasOwnProperty.call(n,"local_path"),i=Object.prototype.hasOwnProperty.call(n,"durable_memory_mode"),o=Object.prototype.hasOwnProperty.call(n,"default_branch"),a=Object.prototype.hasOwnProperty.call(n,"intake_config");return this.stmts.updateProjectSettings.run(s?n.local_path:r.local_path,i?n.durable_memory_mode:r.durable_memory_mode,o?n.default_branch??null:r.default_branch,a?n.intake_config??null:r.intake_config,e),this.stmts.getProject.get(e)??null}listProjectsWithIntakeEnabled(){return this.stmts.listProjectsWithIntakeConfig.all().filter(e=>{if(e.intake_config===null)return!1;try{let n=JSON.parse(e.intake_config);return typeof n=="object"&&n!==null&&!Array.isArray(n)&&n.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let n=e.condition??null,r=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,n);if(r!==void 0)return r;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,n,e.parameters_override??null,e.enabled===!1?0:1,e.priority??100,U());return s.changes===1?this.stmts.getProjectWorkflow.get(s.lastInsertRowid):this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,n)}getProjectWorkflow(e){return this.stmts.getProjectWorkflow.get(e)??null}listProjectWorkflows(e,n={}){return n.enabled_only===!0?this.stmts.listEnabledProjectWorkflows.all(e):this.stmts.listProjectWorkflows.all(e)}removeProjectWorkflow(e){return this.stmts.removeProjectWorkflow.run(e).changes>0}setProjectWorkflowEnabled(e,n){return this.stmts.setProjectWorkflowEnabled.run(n?1:0,e),this.getProjectWorkflow(e)}createIssue(e){let n=U(),r=this.stmts.createIssue.run(e.project_id,e.title,e.body,e.severity??"medium",e.labels??null,e.ai_test_path??null,e.source_run_id??null,n,n);return this.stmts.getIssue.get(r.lastInsertRowid)}getIssue(e){return this.stmts.getIssue.get(e)??null}listIssues(e,n={}){return this.stmts.listIssuesForProject.all(e).filter(r=>!(n.status!==void 0&&!n.status.includes(r.status)||n.severity!==void 0&&!n.severity.includes(r.severity)||n.ai_test_path!==void 0&&r.ai_test_path!==n.ai_test_path))}claimNextIssue(e,n){return this.stmts.claimNextIssue.get(n,U(),e)??null}claimIssue(e,n){return this.stmts.claimIssue.get(n,U(),e)??null}closeIssue(e,n,r){let s=U(),i=this.stmts.closeIssue.get(n,r??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,n){let r=this.stmts.reopenIssue.get(n,U(),e);if(r===void 0)throw this.getIssue(e)===null?new Error(`issue not found: ${e}`):new Error(`issue ${e} is not closed`);return r}updateIssue(e,n){let r=this.getIssue(e);if(r===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(n,"labels"),i=Object.prototype.hasOwnProperty.call(n,"ai_test_path"),o=this.stmts.updateIssue.get(n.title??r.title,n.body??r.body,n.severity??r.severity,s?n.labels??null:r.labels,i?n.ai_test_path??null:r.ai_test_path,U(),e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,n){let r=this.stmts.getWebuiSession.get(e);if(r!==void 0)return r;let s=U();return this.stmts.insertWebuiSession.run(e,n,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,n,r,s,i){if(this.stmts.updateWebuiSessionTransition.run(n,r,s,i,U(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}setWebuiSessionChatbot(e,n){if(this.stmts.setWebuiSessionChatbot.run(n,U(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,n){let r=bh(),s=U();return this.stmts.insertChatbotSession.run(r,e,n??null,s,s,"active"),this.stmts.getChatbotSession.get(r)}getChatbotSession(e){return this.stmts.getChatbotSession.get(e)??null}listChatbotSessions(e){return this.stmts.listChatbotSessionsForUser.all(e)}appendChatbotMessage(e,n,r,s){let i=U(),o=this.stmts.insertChatbotMessage.run(e,n,r,s??null,i);return this.stmts.touchChatbotSession.run(i,e),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,n){this.stmts.upsertConfig.run(e,n,U())}getConfigAll(){let e=this.stmts.listConfig.all(),n={};for(let r of e)n[r.key]=r.value;return n}enqueueJob(e){let n=this.stmts.insertJob.run(e.project_id,e.workflow_id_override??null,e.source,e.source_ref??null,e.payload??null,e.priority??0,e.available_at??U(),e.dedupe_key??null,e.concurrency_key??null,U());if(n.changes===1)return this.stmts.getJob.get(n.lastInsertRowid);if(e.dedupe_key===void 0||e.dedupe_key===null)throw new Error("job insert ignored without dedupe key");return this.stmts.findJobByDedupe.get(e.source,e.dedupe_key)}claimNextJob(e){let n=U(),r=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,r,n)}claimNextJobWithConcurrency(e){let n=U(),r=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,r,n,e.evaluator)}claimJobByIdWithConcurrency(e){let n=U(),r=new Date(Date.now()+e.lease_ms).toISOString();return this.claimByIdWithConcurrencyTxn(e.job_id,e.worker_id,r,n,e.evaluator)}releaseJob(e,n,r){let s=n==="queued"||n==="running"?null:U();return this.stmts.releaseJob.run(n,r??null,s,e),this.getJob(e)}getJob(e){return this.stmts.getJob.get(e)??null}findJobBySourceAndDedupe(e,n){return this.stmts.findJobByDedupe.get(e,n)??null}insertRun(e){let n=this.getWorkflow(e.workflow_id);if(n===null)throw new Error(`workflow not found: ${e.workflow_id}`);let r=this.stmts.insertRun.run(e.job_id,e.workflow_id,e.team_id,e.current_state??null,n.active_version_id,e.parent_run_id??null,U()),s=this.stmts.getRun.get(r.lastInsertRowid);return(e.parent_run_id===void 0||e.parent_run_id===null)&&this.stmts.setJobRun.run(s.id,e.job_id),s}setJobRun(e,n){return this.stmts.setJobRun.run(n,e),this.getJob(e)}insertPromptDispatch(e){return this.stmts.insertPromptDispatch.run(e.prompt_id,e.project_id,e.job_id,e.text,e.context_json??null,U()),this.stmts.getPromptDispatch.get(e.prompt_id)}getPromptDispatch(e){return this.stmts.getPromptDispatch.get(e)??null}setPromptDispatchCompleted(e,n){return this.stmts.setPromptDispatchCompleted.run(n??U(),e),this.getPromptDispatch(e)}getWorkspace(e){return this.stmts.getWorkspace.get(e)??null}ensureWorkspace(e={}){let n=e.id??"default";this.stmts.ensureWorkspace.run(n,e.name??"Default workspace",e.idleThresholdMs??6e5,U());let r=this.getWorkspace(n);if(r===null)throw new Error(`workspace ${n} missing after upsert`);return r}listWebProjectsActive(e){return this.stmts.listWebProjectsActive.all(e)}getWebProject(e){return this.stmts.getWebProject.get(e)??null}insertWebProject(e){let n=U(),r=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,n,n),s=Number(r.lastInsertRowid),i=this.getWebProject(s);if(i===null)throw new Error(`web_project ${s} missing after insert`);return i}updateWebProject(e){let n=this.getWebProject(e.id);return n===null||n.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??n.name,e.config_json===void 0?n.config_json:e.config_json,U(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(U(),e).changes===1}loadMailboxCursor(e,n){return this.stmts.loadMailboxCursor.get(e,n)??null}saveMailboxCursor(e){this.stmts.saveMailboxCursor.run(e.user_id,e.mailbox_key,e.last_processed_version_id,e.last_processed_seq??null,e.last_processed_at)}addUsage(e){this.stmts.addUsage.run(e.user_id,e.device_id,e.period,e.put,e.get,e.list,e.updated_at)}loadUsage(e,n,r){return this.stmts.loadUsage.get(e,n,r)??null}sumUsageForPeriod(e,n){let r=this.stmts.sumUsageForPeriod.get(e,n);return{put:r?.put??0,get:r?.get??0,list:r?.list??0}}upsertRootTeam(e){this.stmts.upsertRootTeam.run(e.teamfile_path,e.name,e.raw_text,e.raw_sha256,e.registered_at,e.last_seeded_at)}getRootTeam(e){return this.stmts.getRootTeam.get(e)??null}listRootTeams(){return this.stmts.listRootTeams.all()}insertTeamChatLog(e){return this.db.transaction(()=>{let n=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.created_at),r=Number(n.lastInsertRowid);return Lc(this.db,r,e),so(this.db,r,e),r})()}beginTeamChatLog(e){return this.db.transaction(()=>{let n=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.created_at),r=Number(n.lastInsertRowid);return Lc(this.db,r,e),r})()}finishTeamChatLog(e,n){this.db.transaction(()=>{if(this.stmts.updateTeamChatLogResponse.run(n.response,n.status,n.error_detail,n.truncated,e).changes!==1)throw new Error(`team_chat_log row disappeared during finish: ${e}`);so(this.db,e,n)})()}setCurrentlyHandlingMessage(e,n,r){this.db.transaction(()=>{Os(this.db,e,n,r)})()}clearCurrentlyHandlingMessage(e,n,r){return this.db.transaction(()=>Oc(this.db,e,n,r))()}listTeamChatLog(e){return this.stmts.listTeamChatLog.all(e)}listTeamChatLogSinceId(e,n=500){return this.stmts.listTeamChatLogSinceId.all(e,Math.max(1,Math.trunc(n)))}getMaxTeamChatLogId(){return this.stmts.getMaxTeamChatLogId.get()?.max_id??0}loadTeamChatLogCursor(e){return this.stmts.loadTeamChatLogCursor.get(e)??null}saveTeamChatLogCursor(e){this.stmts.saveTeamChatLogCursor.run(e.cursor_key,e.last_pushed_id,e.updated_at)}startTrackedInvocation(e){return this.db.transaction(()=>this.startTrackedInvocationInner(e))()}startTrackedInvocationInner(e){let n=e.started_at??U(),r=e.holder_host??Dc(),s=e.last_heartbeat_at??n,i=this.stmts.insertTrackedInvocation.run(e.kind,e.origin,e.scope_teamfile??null,e.from_identity,e.target_teamfile??null,e.target_alias??null,e.root_teamfile??null,e.cwd??null,mt(e.command),n,e.holder_pid??null,r,s,mt(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return _h(this.db,o),o}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listTrackedInvocationsForTarget(e,n,r={}){let s=["target_teamfile = ?","target_alias = ?"],i=[e,n];r.sinceMs!==void 0&&(s.push("started_at >= ?"),i.push(new Date(r.sinceMs).toISOString())),r.untilMs!==void 0&&(s.push("started_at <= ?"),i.push(new Date(r.untilMs).toISOString()));let o=Math.max(1,Math.trunc(r.limit??200));return this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${s.join(" AND ")} ORDER BY started_at DESC LIMIT ?`).all(...i,o)}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}listRecentlyFinishedTrackedInvocations(e){return this.stmts.listRecentlyFinishedTrackedInvocations.all(e)}finishTrackedInvocation(e,n){return this.db.transaction(()=>{let r=n.ended_at??U();if(this.stmts.finishTrackedInvocation.run(n.status,r,n.exit_code??null,n.signal??null,mt(n.result_summary),mt(n.error),n.team_chat_log_id??null,mt(n.meta),mt(n.config_warnings),r,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return io(this.db,i),i})()}reclaimTrackedInvocationIfUnchanged(e,n,r){return this.db.transaction(()=>{let s=r.ended_at??U();if(this.stmts.reclaimTrackedInvocationIfUnchanged.run(r.status,s,r.exit_code??null,r.signal??null,mt(r.result_summary),mt(r.error),r.team_chat_log_id??null,mt(r.meta),mt(r.config_warnings),s,e,n.holder_pid,n.holder_host,n.started_at,n.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return io(this.db,o),o})()}heartbeatTrackedInvocation(e,n=U()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(n,e).changes!==1)return null;let s=this.getTrackedInvocation(e);return gh(this.db,s,n),s})()}updateTrackedInvocationRequestPayload(e,n){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(n,e).changes!==1?null:(yh(this.db,e,n),this.getTrackedInvocation(e)))()}linkTrackedInvocationMessage(e,n){return this.db.transaction(()=>this.stmts.linkTrackedInvocationChatLog.run(n,e).changes!==1?null:(wh(this.db,e,on(n)),this.getTrackedInvocation(e)))()}abortTrackedInvocationAndTerminalizeMessage(e,n,r){return this.db.transaction(()=>{let s=U();if(this.stmts.abortTrackedInvocationIfUnchanged.run(s,mt(r),e,n.holder_pid,n.holder_host,n.started_at,n.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return io(this.db,o),o.team_chat_log_id!==null&&this.terminalizeLinkedChatMessage(o.team_chat_log_id,r),o})()}terminalizeLinkedChatMessage(e,n){let r=this.stmts.getTeamChatLogById.get(e);r===void 0||r.status!=="running"||this.stmts.terminalizeTeamChatLogIfRunning.run("error",n,e).changes!==1||so(this.db,e,{root_teamfile:r.root_teamfile,sender_teamfile:r.sender_teamfile,sender_alias:r.sender_alias,receiver_teamfile:r.receiver_teamfile,receiver_alias:r.receiver_alias,message:r.message,response:null,origin:r.origin,status:"error",error_detail:n,truncated:r.truncated,created_at:U()})}listClaimableTerminalTrackedInvocations(e){let n=["status IN ('done', 'error', 'busy', 'cancelled', 'aborted')","ended_at IS NOT NULL","notified_by IS NULL"],r=[];e.from!==void 0&&(n.push("from_identity = ?"),r.push(e.from)),e.scope_teamfile!==void 0&&(n.push("scope_teamfile = ?"),r.push(e.scope_teamfile));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));return r.push(s),this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${n.join(" AND ")} ORDER BY ended_at ASC, id ASC LIMIT ?`).all(...r)}claimTrackedInvocationNotification(e,n,r=U()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(n,r,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return hh(this.db,i,n,r),i})()}listTrackedInvocations(e={}){let n=[],r=[];e.from!==void 0&&(n.push("from_identity = ?"),r.push(e.from)),e.scope_teamfile!==void 0&&(n.push("scope_teamfile = ?"),r.push(e.scope_teamfile)),e.status!==void 0&&(n.push("status = ?"),r.push(e.status)),e.kind!==void 0&&(n.push("kind = ?"),r.push(e.kind)),e.origin!==void 0&&(n.push("origin = ?"),r.push(e.origin));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));r.push(s);let i=n.length===0?"":` WHERE ${n.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${i} ORDER BY started_at DESC, id DESC LIMIT ?`).all(...r)}maxTrackedInvocationId(e={}){let n=[],r=[];e.from!==void 0&&(n.push("from_identity = ?"),r.push(e.from)),e.scope_teamfile!==void 0&&(n.push("scope_teamfile = ?"),r.push(e.scope_teamfile));let s=n.length===0?"":` WHERE ${n.join(" AND ")}`,i=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...r);return Number(i?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}updateTeamChatLogResponse(e,n){this.stmts.updateTeamChatLogResponse.run(n.response,n.status,n.error_detail,n.truncated,e)}getAgentInflight(e,n){return this.stmts.getAgentInflight.get(e,n)??null}listAgentInflight(){return this.stmts.listAgentInflight.all()}tryAcquireAgentInflight(e,n){return this.tryAcquireAgentInflightTxn(e,n)}heartbeatAgentInflight(e,n,r=U()){return this.db.transaction(()=>{let s=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);return s===null||s.sender_teamfile!==e.sender_teamfile||s.sender_alias!==e.sender_alias||s.started_at!==e.started_at?!1:ah(this.db,s,n,r)})()}clearAgentInflight(e,n){this.db.transaction(()=>{let s=this.getAgentInflight(e,n);if(s===null)return;this.stmts.clearAgentInflight.run(e,n).changes===1&&Ls(this.db,s,"INFLIGHT_RECLAIM","stale")})()}clearObservedTerminalAgentInflight(e,n,r){return this.db.transaction(()=>{let i=this.getAgentInflight(e,n),o=this.stmts.clearObservedTerminalAgentInflight.run({receiver_teamfile:e,receiver_alias:n,observed_sender_teamfile:r.sender_teamfile,observed_sender_alias:r.sender_alias,observed_started_at:r.started_at,observed_holder_pid:r.holder_pid});return o.changes===1&&i!==null&&Ls(this.db,i,"INFLIGHT_RELEASE"),o.changes===1})()}releaseAgentInflight(e,n){this.db.exec("BEGIN IMMEDIATE");try{let r=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);if(r===null||r.sender_teamfile!==e.sender_teamfile||r.sender_alias!==e.sender_alias)return this.db.exec("COMMIT"),!1;if(n!==void 0&&this.db.prepare(`SELECT lease_id FROM agent_state
1511
1511
  WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e.receiver_teamfile,e.receiver_alias)?.lease_id!==n)return this.db.exec("COMMIT"),!1;if(r.active_count<=1){let i=this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return i.changes===1&&Ls(this.db,r,"INFLIGHT_RELEASE"),this.db.exec("COMMIT"),i.changes===1}let s=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),s.changes===1}catch(r){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),r}}clearAgentInflightOlderThan(e){return this.db.transaction(()=>{let r=this.listAgentInflight().filter(i=>i.started_at<e),s=0;for(let i of r)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(Ls(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,n){let r=this.stmts.getRuntimeState.get(As,Rs(e,n),xs);return r===void 0?null:z_(r.data)}setTerminalLock(e){this.db.transaction(()=>{let r=this.getTerminalLock(e.teamfile,e.alias);r!==null&&r.lock_id!==e.lock_id&&Cc(this.db,r,!0),this.stmts.upsertRuntimeState.run(As,Rs(e.teamfile,e.alias),xs,JSON.stringify(e),e.last_heartbeat),r?.lock_id!==e.lock_id&&lh(this.db,e)})()}heartbeatTerminalLock(e,n,r,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,n);if(i===null||i.lock_id!==r)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(As,Rs(e,n),xs,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,n,r){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,n);if(s===null||s.lock_id!==r)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(As,Rs(e,n),xs);return i.changes===1&&Cc(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,n,r){let s=this.stmts.getRuntimeState.get(e,n,r);return s===void 0?null:jO(s.data)}tryAcquireRuntimeProcessLock(e,n,r,s,i=U()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,n,r);if(o!==null&&!PO(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:bh(),holder_pid:process.pid,holder_host:Dc(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,n,r,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,n,r,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,n,r);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,n,r);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,n){return this.stmts.setRunCurrentState.run(n,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,n,r){return this.stmts.setRunPausedState.run(n,r,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,n){return this.stmts.setRunPendingEscalationDecision.run(n,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,n){return this.stmts.setRunTerminalState.run(n,U(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,n){return this.resumeRunTxn(e,n,U())}insertStep(e){let n=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,U());return this.stmts.getStep.get(n.lastInsertRowid)}finishStep(e,n,r){return this.stmts.finishStep.run(n??null,r??null,U(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let n=this.stmts.listLatestStepOutcomesByState.all(e),r={};for(let s of n)r[s.state_name]=s.outcome;return r}insertSubmittedPr(e){let n=this.stmts.insertSubmittedPr.run(e.repo,e.pr_url,e.issue_url??null,e.local_path??null,e.branch??null,e.head_sha??null,e.status??"watching",e.submitted_at??U(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(n.lastInsertRowid)}listSubmittedPrs(e){return e?.status!==void 0?this.stmts.listSubmittedPrsByStatus.all(e.status):this.stmts.listSubmittedPrs.all()}getSubmittedPr(e){return this.stmts.getSubmittedPr.get(e)??null}findSubmittedPrByUrl(e){return this.stmts.findSubmittedPrByUrl.get(e)??null}insertStepArtifact(e){let n=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,U());return this.stmts.getStepArtifact.get(n.lastInsertRowid)}insertExternalObject(e){let r=this.stmts.insertExternalObject.run(e.type,e.provider,e.project_id,e.run_id??null,e.external_id,e.url??null,e.status??null,e.metadata??null,e.last_seen_at??null,U()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:r}}insertExternalSignal(e){let n=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,U()),r=n.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(n.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:r}}raiseAttention(e){let n=this.stmts.insertAttention.run(e.kind,e.severity??"warn",e.project_id??null,e.run_id??null,e.external_object_id??null,e.requires_user===!0?1:0,e.payload??null,U());return this.stmts.getAttention.get(n.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(U(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let n=U();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,n,n),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,n){return this.stmts.getDurableMemoryByName.get(e,n)??null}deleteDurableMemory(e,n){return this.stmts.deleteDurableMemory.run(e,n).changes>0}listDurableMemory(e,n){return n!==void 0?this.stmts.listDurableMemoryByType.all(e,n):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,n){return n!==void 0&&n.length>0?this.stmts.listDurableMemory.all(e).filter(s=>n.includes(s.type)).map(({name:s,description:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:r,description:s,type:i,updated_at:o})=>({name:r,description:s,type:i,updated_at:o}))}recordSessionSize(e){let n=this.stmts.insertSessionSize.run(e.team_name,e.alias,e.sessionid,e.input_tokens??null,e.cache_tokens??null,e.output_tokens??null,e.total_tokens??null,e.observed_at??U());return this.stmts.getSessionSize.get(n.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,n,r=20){return this.stmts.sessionSizeHistory.all(e,n,r)}insertSessionEvent(e){let n=this.stmts.insertSessionEvent.run(e.run_id,e.step_id??null,e.kind,e.timestamp_ms,e.payload,e.payload_truncated??0,e.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(n.lastInsertRowid)}listSessionEvents(e,n){return n!==void 0?this.stmts.listSessionEventsSince.all(e,n):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,n=1e3){return this.stmts.listAllEventsSince.all(e,n)}latestAgentCall(e){let n=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(n===void 0)return null;try{let r=JSON.parse(n.payload);return typeof r.alias!="string"||typeof r.provider!="string"?null:{alias:r.alias,provider:r.provider,...typeof r.model=="string"?{model:r.model}:{}}}catch{return null}}agentCallTokenTotals(e){let n=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),r=0,s=0,i=0;for(let o of n)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(r+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:r,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let n=this.stmts.insertDriftSignal.run(e.team_member_id,e.project_id??null,e.signal_kind,e.severity,e.description,e.detected_at,e.expires_at??null,e.payload??null);return this.stmts.getDriftSignal.get(n.lastInsertRowid)}listDriftSignals(e={}){return e.team_member_id!==void 0&&e.unacked?this.stmts.listUnackedDriftByMember.all(e.team_member_id):e.team_member_id!==void 0?this.stmts.listDriftByMember.all(e.team_member_id):e.project_id!==void 0?this.stmts.listDriftByProject.all(e.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(e,n,r){return this.stmts.findUnackedDrift.get(e,n??null,r)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let n=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,n,n),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,n){return this.stmts.getInteractiveSessionByRunAndState.get(e,n)??null}setInteractiveAgentOutput(e,n,r){this.stmts.setInteractiveAgentOutput.run(n,r,Date.now(),e)}resumeInteractive(e,n,r){return this.resumeInteractiveTxn(e,n,r,U())}resumeEscalation(e,n){return this.resumeEscalationTxn(e,n,U())}}});import{realpathSync as WO}from"node:fs";import{resolve as qO}from"node:path";function jc(t){let e=qO(t);try{return WO(e)}catch{return e}}var Oh=E(()=>{"use strict"});import{platform as Lh}from"node:os";function Jt(t){let e=new Ds;for(let n of t)e.registerAdapter(n);return e}var Ds,Pc=E(()=>{"use strict";Oh();Ds=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let n=[],r=e?.provider?this.providers.filter(o=>o.name===e.provider):this.providers,s=await Promise.all(r.map(o=>o.discoverSessions()));for(let o of s)n.push(...o);let i=n;if(e?.workspace){let o=jc(e.workspace);i=i.filter(a=>jc(a.cwd)===o)}if(e?.from){let o=e.from.getTime();i=i.filter(a=>a.modifiedAt.getTime()>=o)}if(e?.to){let o=e.to.getTime();i=i.filter(a=>a.modifiedAt.getTime()<=o)}return i.sort((o,a)=>a.modifiedAt.getTime()-o.modifiedAt.getTime()),e?.limit&&(i=i.slice(0,e.limit)),i}async getSession(e,n){let r=n?this.providers.filter(s=>s.name===n):this.providers;for(let s of r){let i=await s.loadSession(e);if(i)return i}return null}async resolveSession(e,n){let r=await this.resolveSessions(e,n);return r.length===1?r[0]:null}async resolveSessions(e,n){let r=n?this.providers.filter(i=>i.name===n):this.providers,s=[];for(let i of r){let o=await i.resolveSessionPath(e);o&&s.push({provider:i,filePath:o})}return s}getWatchTargets(){let e=Lh()==="darwin"||Lh()==="win32",n=[];for(let r of this.providers)if(typeof r.getWatchPaths=="function")for(let s of r.getWatchPaths())n.push({provider:r.name,directory:s.directory,recursive:e,filePattern:s.filePattern});return n}async deleteSession(e,n){let r=await this.resolveSession(e,n);return r?r.provider.deleteSession(e):!1}registerAdapter(e){this.adapters.set(e.name,e),this.providers.push({name:e.name,discoverSessions:()=>e.discover(),loadSession:n=>e.load(n),resolveSessionPath:n=>e.resolvePath(n),deleteSession:n=>e.delete(n),getWatchPaths:()=>e.getWatchPaths?.()??[]})}getAdapter(e){return this.adapters.get(e)}getAllAdapters(){return[...this.adapters.values()]}}});import{createReadStream as Ch}from"node:fs";import{createInterface as $h}from"node:readline";import{stat as HO}from"node:fs/promises";import{homedir as BO}from"node:os";function Mh(t){try{let e=JSON.parse(t);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*De(t){let e=Ch(t,{encoding:"utf-8"}),n=$h({input:e,crlfDelay:1/0});try{for await(let r of n){let s=r.trim();if(!s)continue;let i=Mh(s);i!==void 0&&(yield i)}}finally{e.destroy()}}async function Nt(t,e){let n=[],r=Ch(t,{encoding:"utf-8"}),s=$h({input:r,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=Mh(o);if(a!==void 0&&n.push(a),n.length>=e)break}}finally{s.close(),r.destroy()}return n}async function Le(t){let e=await HO(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function _e(t){return t.replace(/\\n/g,`
1512
1512
  `).replace(/\\t/g," ").replace(/\\r/g,"\r")}function B(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function _t(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var ge,At=E(()=>{"use strict";ge=BO()});import{readdir as uo,stat as Dh,unlink as XO}from"node:fs/promises";import{join as xr,basename as jh}from"node:path";function JO(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function GO(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return _e(e.trim());if(e!==void 0)return JSON.stringify(e,null,2)}return t.type==="progress"&&t.data!==void 0?JSON.stringify(t.data,null,2):JSON.stringify(t,null,2)}async function Ph(t){let e=0,n=0,r=0,s=0,i=0,o=0,a,l;for await(let c of De(t))if(!c.isSidechain){if(c.type==="user"&&!c.isMeta&&c.message){let u=c.message.content;if(typeof u=="string"){if(u.includes("<command-name>")||u.includes("<local-command-"))continue;e++,l=B(u.trim(),80)}}else if(c.type==="assistant"&&c.message){let u=c.message.content;if(Array.isArray(u))for(let f of u)f.type==="text"&&e++;let d=c.message.usage;if(d){let f=d.input_tokens||0,m=d.cache_creation_input_tokens||0,p=d.cache_read_input_tokens||0,h=d.output_tokens||0;n+=f+m+p,r+=p,s+=m,i+=h;let _=f+m+p;_&&(o=_),a={inputTokens:f,cacheWriteInputTokens:m,cachedInputTokens:p,outputTokens:h}}}}return{messageCount:e,totalInputTokens:n,totalCacheReadInputTokens:r,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a,lastUserMessage:l}}function KO(t){let e=VO(t),n=new Set;for(let r of t){if(r.role!=="tool_use"||r.toolName!=="Bash"||r.toolInputData?.run_in_background!==!0||r.toolCallId===void 0)continue;let s=e.get(r.toolCallId);if(s===void 0)continue;let i=s.content.match(/Command running in background with ID:\s*([A-Za-z0-9_-]+)/)?.[1];i!==void 0&&(n.add(i),r.backgroundTaskId=i,s.backgroundTaskId=i)}for(let r of t){if(r.role!=="tool_use"||r.toolName!=="TaskOutput"&&r.toolName!=="TaskStop"||r.toolCallId===void 0)continue;let s=r.toolInputData?.task_id;if(typeof s!="string"||!n.has(s))continue;r.backgroundTaskId=s;let i=e.get(r.toolCallId);i!==void 0&&(i.backgroundTaskId=s)}}function VO(t){let e=new Map;for(let n of t)n.role==="tool_result"&&n.toolCallId!==void 0&&e.set(n.toolCallId,n);return e}var fo,Fh=E(()=>{"use strict";At();fo=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||xr(ge,".claude"),this.projectsDir=xr(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],n;try{n=await uo(this.projectsDir)}catch{return e}for(let r of n){let s=xr(this.projectsDir,r);if(!(await Dh(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await uo(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=jh(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=xr(s,a);try{let u=await this.extractSummary(c,l);u&&e.push(u)}catch{}}}return e}async extractSummary(e,n){let r=await Nt(e,50),s=await Le(e),i="",o,a,l,c,u,d;for(let m of r)if(!JO(m.type)&&(!i&&m.cwd&&(i=m.cwd),!o&&m.slug&&(o=m.slug),!a&&m.version&&(a=m.version),!d&&m.timestamp&&(d=new Date(m.timestamp)),m.type==="assistant"&&m.message?.model&&(l=m.message.model),m.type==="user"&&!m.isMeta&&m.message)){let p=m.message.content;if(typeof p=="string"){if(p.includes("<command-name>")||p.includes("<local-command-"))continue;c||(c=B(p.trim(),80)),u=B(p.trim(),80)}}if(!i)return null;let f=await Ph(e);return{provider:"claude",sessionId:n,slug:o,cwd:i,createdAt:d||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,lastUserMessage:f.lastUserMessage??u,messageCount:f.messageCount,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:f.totalCacheWriteInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,lastInputTokens:f.lastInputTokens||void 0,lastTokenUsage:f.lastTokenUsage}}async loadSession(e){let n=await this.resolveSessionFile(e);if(!n)return null;let r=await Le(n),s=[],i="",o,a,l,c,u,d,f,m=e,p;for await(let _ of De(n))if(_.type!=="file-history-snapshot"&&!_.isSidechain){if(!i&&_.cwd&&(i=_.cwd),!o&&_.slug&&(o=_.slug),!a&&_.version&&(a=_.version),!c&&_.gitBranch&&(c=_.gitBranch),!f&&_.timestamp&&(f=new Date(_.timestamp)),_.sessionId&&(m=_.sessionId),_.type==="system"||_.type==="progress"||_.type==="queue-operation"){s.push({role:"system",timestamp:new Date(_.timestamp||0),content:GO(_)});continue}if(_.type==="user"&&_.message){if(_.isMeta)continue;let g=new Date(_.timestamp||0),y=_.message.content;if(typeof y=="string"){if(y.includes("<command-name>")||y.includes("<local-command-"))continue;u||(u=B(y.trim(),80)),d=B(y.trim(),80),p=void 0,s.push({role:"user",timestamp:g,content:_e(y.trim())})}else if(Array.isArray(y)){for(let w of y)if(w.type==="tool_result"){let v=typeof w.content=="string"?_e(w.content):JSON.stringify(w.content);s.push({role:"tool_result",timestamp:g,content:v,toolCallId:w.tool_use_id})}}}if(_.type==="assistant"&&_.message){_.message.stop_reason===null||_.message.stop_reason==="tool_use"?p="in_progress":typeof _.message.stop_reason=="string"&&(p="complete"),_.message.model&&(l=_.message.model);let g=new Date(_.timestamp||0),y=_.message.content;if(Array.isArray(y))for(let w of y)w.type==="text"&&w.text?s.push({role:"assistant",timestamp:g,content:_e(w.text),model:_.message.model,...typeof _.message.stop_reason=="string"?{stopReason:_.message.stop_reason}:{}}):w.type==="tool_use"?s.push({role:"tool_use",timestamp:g,content:w.name||"unknown tool",toolName:w.name,toolInput:JSON.stringify(w.input,null,2),toolInputData:w.input,toolCallId:w.id,model:_.message.model,...typeof _.message.stop_reason=="string"?{stopReason:_.message.stop_reason}:{}}):w.type==="thinking"&&w.thinking&&s.push({role:"thinking",timestamp:g,content:w.thinking})}}if(!i)return null;KO(s);let h=await Ph(n);return{provider:"claude",sessionId:m,slug:o,cwd:i,createdAt:f||r.createdAt,modifiedAt:r.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,turnStatus:p,firstUserMessage:u,lastUserMessage:d,messageCount:h.messageCount,filePath:n,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:h.totalCacheWriteInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,lastInputTokens:h.lastInputTokens||void 0,lastTokenUsage:h.lastTokenUsage,messages:s}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let n=await this.resolveSessionFile(e);return n?(await XO(n),!0):!1}async resolveSessionFile(e){let n;try{n=await uo(this.projectsDir)}catch{return null}let r=[];for(let o of n){let a=xr(this.projectsDir,o);if(!(await Dh(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await uo(a)}catch{continue}for(let u of c){if(!u.endsWith(".jsonl"))continue;let d=jh(u,".jsonl");/^[0-9a-f]{8}-/.test(d)&&r.push({filePath:xr(a,u),fileSessionId:d})}}let s=r.find(o=>o.fileSessionId===e);if(s)return s.filePath;let i=r.filter(o=>o.fileSessionId.startsWith(e));if(i.length===1)return i[0].filePath;for(let o of r){let a=await Nt(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});import{readFileSync as YO,writeFileSync as B6,mkdirSync as X6}from"node:fs";import{join as zO,dirname as G6}from"node:path";import{homedir as ZO}from"node:os";function eL(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function tL(t){let e=t.indexOf("=");if(e===-1)return null;let n=t.slice(0,e).trim(),r=eL(t.slice(e+1).trim());return n?{key:n,value:r}:null}function nL(t){let e=t.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function mo(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function rL(){return zO(ZO(),".lmctl","config.toml")}function Wh(t){let e=t??rL(),n;try{n=YO(e,"utf-8")}catch{return{tools:{}}}return sL(n)}function Uh(t){if(typeof t=="number")return Number.isFinite(t)?t:null;let e=String(t).trim();if(!e)return null;let n=e.match(/^(\d+(?:\.\d+)?)\s*([KkMm]?)$/);if(!n)return null;let r=parseFloat(n[1]);if(!Number.isFinite(r))return null;switch(n[2]){case"K":case"k":return Math.round(r*1e3);case"M":case"m":return Math.round(r*1e6);default:return Math.round(r)}}function sL(t){let e={},n={},r=t.split(`
1513
- `),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let d=e[s.tool]??{};if(s.profile){let f=d.profiles?.[s.profile]??{};i.description&&(f.description=i.description),i.flags!==void 0&&(f.flags=i.flags),d.profiles||(d.profiles={}),d.profiles[s.profile]=f}else i.start&&(d.start=i.start),i.resume&&(d.resume=i.resume),i.agent&&(d.agent=i.agent),i.profile_flag!==void 0&&(d.profile_flag=i.profile_flag);e[s.tool]=d}else if(s.kind==="compact"){let d=s.provider?n.providers?.[s.provider]??{}:n.global??{};if(i.min!==void 0){let f=Uh(i.min);f!==null&&(d.min=f)}if(i.max!==void 0){let f=Uh(i.max);f!==null&&(d.max=f)}s.provider?(n.providers||(n.providers={}),n.providers[s.provider]=d):n.global=d}i={}}for(let d of r){let f=d.trim();if(!f||f.startsWith("#"))continue;let m=nL(f);if(m!==null){if(o=!0,l(),m.startsWith("tool.")){let h=".profile.",_=m.indexOf(h);_!==-1?s={kind:"tool",tool:m.slice(5,_),profile:m.slice(_+h.length)}:s={kind:"tool",tool:m.slice(5),profile:null}}else m==="compact"?s={kind:"compact",provider:null}:m.startsWith("compact.")?s={kind:"compact",provider:m.slice(8)}:s={kind:"none"};continue}let p=tL(f);p&&s.kind!=="none"?i[p.key]=p.value:p&&!o&&(a[p.key]=p.value)}l();let c={tools:e};(n.global||n.providers)&&(c.compact=n);let u=a.site_name;return u!==void 0&&u.length>0&&(c.site_name=u),c}function qh(t){return t.site_name??null}function iL(t,e,n){if(!n)return"";let r=t.tools[e]??Fc[e],s=r?.profiles?.[n]?.flags??Fc[e]?.profiles?.[n]?.flags;if(s!==void 0)return s.trim();if(r?.profile_flag)return r.profile_flag.replace(/\{\{profile\}\}/g,n).trim();throw new Error(`Profile "${n}" is not configured for tool "${e}"`)}function Hh(t,e){return!!t.tools[e]}function Bh(t,e,n,r,s){let i=t.tools[e]??Fc[e],o;if(i?.agent){let l=mo(r);o=i.agent.replace(/\{\{session_id\}\}/g,n).replace(/\{\{prompt\}\}/g,l)}else{let l=QO[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(u=>u.replace(/\{\{session_id\}\}/g,n).replace(/\{\{prompt\}\}/g,r));if(l.mode==="stdin"){let u=c.map(mo).join(" ");o=`printf '%s\\n' ${mo(r)} | ${u}`}else o=c.map(mo).join(" ")}let a=iL(t,e,s);return a&&(o+=" "+a),o}var Fc,QO,Uc=E(()=>{"use strict";Fc={claude:{start:"claude",resume:"claude --resume {{session_id}} --dangerously-skip-permissions",profiles:{default:{description:"Default profile",flags:""}}},codex:{start:"codex",resume:"codex resume {{session_id}} --dangerously-bypass-approvals-and-sandbox",profiles:{default:{description:"Default profile",flags:""}}},opencode:{start:"opencode",resume:"opencode --session {{session_id}}",profiles:{default:{description:"Default profile",flags:""}}},gemini:{start:"gemini",resume:"gemini --resume {{session_id}} -y",profiles:{default:{description:"Default profile",flags:""}}},copilot:{start:"copilot",resume:"copilot --resume={{session_id}} --yolo",profiles:{default:{description:"Default profile",flags:""}}},qwen:{start:"qwen",resume:"qwen --resume {{session_id}} --approval-mode yolo",profiles:{default:{description:"Default profile",flags:""}}},agy:{start:"agy",resume:"agy --conversation {{session_id}} --dangerously-skip-permissions",profiles:{default:{description:"Default profile",flags:""}}},kimi:{start:"kimi --auto",resume:"kimi --session {{session_id}} --auto",profiles:{default:{description:"Default profile",flags:""}}},hermes:{start:"hermes",resume:"hermes --yolo --resume {{session_id}}",profiles:{default:{description:"Default profile",flags:""}}}},QO={claude:{mode:"argv",argv:["claude","-p","{{prompt}}","--resume","{{session_id}}"]},codex:{mode:"argv",argv:["codex","exec","--dangerously-bypass-approvals-and-sandbox","--skip-git-repo-check","resume","{{session_id}}","{{prompt}}"]},opencode:{mode:"argv",argv:["opencode","run","--session","{{session_id}}","{{prompt}}"]},gemini:{mode:"argv",argv:["gemini","-p","{{prompt}}","--resume","{{session_id}}"]},copilot:{mode:"argv",argv:["gh","copilot","--","--resume={{session_id}}","-p","{{prompt}}","-s","--allow-all-tools"]},qwen:{mode:"argv",argv:["qwen","-p","{{prompt}}","--resume","{{session_id}}","--approval-mode","yolo"]},agy:{mode:"argv",argv:["agy","--conversation","{{session_id}}","-p","{{prompt}}","--dangerously-skip-permissions","--print-timeout","8h"]},kimi:{mode:"argv",argv:["kimi","-p","{{prompt}}","--session","{{session_id}}","--output-format","stream-json"]},hermes:{mode:"argv",argv:["hermes","--yolo","-z","{{prompt}}","--resume","{{session_id}}"]}}});function Xh(t=process.env){let e=t.LMCTL_ONE_SHOT_TIMEOUT_MS;if(!e)return 6e5;let n=Number(e);return!Number.isFinite(n)||n<=0?6e5:n}var Jh=E(()=>{"use strict"});var oL,ce,po,it=E(()=>{"use strict";oL="ACK: waiting for explicit lmctl task.",ce=`lmctl seed initial connection only. Create or pin this provider session, then stop. Do not inspect files, run commands, infer a task, delegate, edit, or begin work. Reply exactly: ${oL}`,po=`send this exact lmctl seed instruction: "${ce}"`});import{existsSync as aL}from"node:fs";function Gh(t){let e=t.CLAUDE_CODE_EXECPATH;if(e===void 0||e.length===0)return t;let n=process.platform!=="win32"&&e.toLowerCase().endsWith(".exe"),r=!n&&!aL(e);if(!n&&!r)return t;L({event:"claude_execpath_sanitized",reason:n?"wrong_platform_exe":"missing_file",value:e,platform:process.platform});let s={...t};return delete s.CLAUDE_CODE_EXECPATH,s}function Nn(t,e){let n={...t??process.env,PWD:e};return delete n.OLDPWD,n}function cL(t,e){return e===void 0||e.length===0?t:{...t??process.env,[js]:e}}function Ke(t,e,n,r="chat"){return{...cL(Nn(t,e),n),[lL]:r}}var js,lL,xt=E(()=>{"use strict";ae();js="LMCTL_SELF_SESSIONID",lL="LMCTL_LAUNCH_SOURCE"});function _o(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Wc=E(()=>{"use strict"});import{spawn as Kh}from"node:child_process";import{mkdirSync as dL}from"node:fs";var qc,Te,ht=E(()=>{"use strict";Uc();Jh();it();xt();Wc();qc=class t extends Error{cancelReason;constructor(e,n){super(e),this.name="TurnAbortError",this.cancelReason=n,Object.setPrototypeOf(this,t.prototype)}},Te=class t{name;capabilities;injection;provider;binary;seedArgs;seedStdin;resumeTemplate;startTemplate;transportFn;constructor(e){this.name=e.provider.name,this.provider=e.provider,this.capabilities=e.capabilities,this.injection=e.injection,this.binary=e.binary,this.seedArgs=e.seedArgs,this.seedStdin=e.seedStdin,this.resumeTemplate=e.resumeTemplate,this.startTemplate=e.startTemplate,this.transportFn=e.transport}discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return this.provider.getWatchPaths?.()??[]}seedArgsFor(e){let n=e?.prompt;return n===void 0?this.seedArgs:this.seedArgs.map(r=>r===ce?n:r)}turnOptsFor(e){return e}seed(e,n){return dL(e,{recursive:!0}),new Promise(r=>{let s;try{s=Kh(this.binary,this.seedArgsFor(n),{cwd:e,env:Nn(void 0,e),stdio:["pipe","pipe","pipe"],timeout:6e4})}catch(a){return r({success:!1,error:a instanceof Error?a.message:String(a)})}let i="";s.stderr?.on("data",a=>{i+=a.toString()});let o=n?.prompt!==void 0&&this.seedStdin!==void 0?`${n.prompt}
1513
+ `),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let d=e[s.tool]??{};if(s.profile){let f=d.profiles?.[s.profile]??{};i.description&&(f.description=i.description),i.flags!==void 0&&(f.flags=i.flags),d.profiles||(d.profiles={}),d.profiles[s.profile]=f}else i.start&&(d.start=i.start),i.resume&&(d.resume=i.resume),i.agent&&(d.agent=i.agent),i.profile_flag!==void 0&&(d.profile_flag=i.profile_flag);e[s.tool]=d}else if(s.kind==="compact"){let d=s.provider?n.providers?.[s.provider]??{}:n.global??{};if(i.min!==void 0){let f=Uh(i.min);f!==null&&(d.min=f)}if(i.max!==void 0){let f=Uh(i.max);f!==null&&(d.max=f)}s.provider?(n.providers||(n.providers={}),n.providers[s.provider]=d):n.global=d}i={}}for(let d of r){let f=d.trim();if(!f||f.startsWith("#"))continue;let m=nL(f);if(m!==null){if(o=!0,l(),m.startsWith("tool.")){let h=".profile.",_=m.indexOf(h);_!==-1?s={kind:"tool",tool:m.slice(5,_),profile:m.slice(_+h.length)}:s={kind:"tool",tool:m.slice(5),profile:null}}else m==="compact"?s={kind:"compact",provider:null}:m.startsWith("compact.")?s={kind:"compact",provider:m.slice(8)}:s={kind:"none"};continue}let p=tL(f);p&&s.kind!=="none"?i[p.key]=p.value:p&&!o&&(a[p.key]=p.value)}l();let c={tools:e};(n.global||n.providers)&&(c.compact=n);let u=a.site_name;return u!==void 0&&u.length>0&&(c.site_name=u),c}function qh(t){return t.site_name??null}function iL(t,e,n){if(!n)return"";let r=t.tools[e]??Fc[e],s=r?.profiles?.[n]?.flags??Fc[e]?.profiles?.[n]?.flags;if(s!==void 0)return s.trim();if(r?.profile_flag)return r.profile_flag.replace(/\{\{profile\}\}/g,n).trim();throw new Error(`Profile "${n}" is not configured for tool "${e}"`)}function Hh(t,e){return!!t.tools[e]}function Bh(t,e,n,r,s){let i=t.tools[e]??Fc[e],o;if(i?.agent){let l=mo(r);o=i.agent.replace(/\{\{session_id\}\}/g,n).replace(/\{\{prompt\}\}/g,l)}else{let l=QO[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(u=>u.replace(/\{\{session_id\}\}/g,n).replace(/\{\{prompt\}\}/g,r));if(l.mode==="stdin"){let u=c.map(mo).join(" ");o=`printf '%s\\n' ${mo(r)} | ${u}`}else o=c.map(mo).join(" ")}let a=iL(t,e,s);return a&&(o+=" "+a),o}var Fc,QO,Uc=E(()=>{"use strict";Fc={claude:{start:"claude",resume:"claude --resume {{session_id}} --dangerously-skip-permissions",profiles:{default:{description:"Default profile",flags:""}}},codex:{start:"codex",resume:"codex resume {{session_id}} --dangerously-bypass-approvals-and-sandbox",profiles:{default:{description:"Default profile",flags:""}}},opencode:{start:"opencode",resume:"opencode --session {{session_id}}",profiles:{default:{description:"Default profile",flags:""}}},gemini:{start:"gemini",resume:"gemini --resume {{session_id}} -y",profiles:{default:{description:"Default profile",flags:""}}},copilot:{start:"copilot",resume:"copilot --resume={{session_id}} --yolo",profiles:{default:{description:"Default profile",flags:""}}},qwen:{start:"qwen",resume:"qwen --resume {{session_id}} --approval-mode yolo",profiles:{default:{description:"Default profile",flags:""}}},agy:{start:"agy",resume:"agy --conversation {{session_id}} --dangerously-skip-permissions",profiles:{default:{description:"Default profile",flags:""}}},kimi:{start:"kimi --auto",resume:"kimi --session {{session_id}} --auto",profiles:{default:{description:"Default profile",flags:""}}},hermes:{start:"hermes",resume:"hermes --yolo --resume {{session_id}}",profiles:{default:{description:"Default profile",flags:""}}}},QO={claude:{mode:"argv",argv:["claude","-p","{{prompt}}","--resume","{{session_id}}"]},codex:{mode:"argv",argv:["codex","exec","--dangerously-bypass-approvals-and-sandbox","--skip-git-repo-check","resume","{{session_id}}","{{prompt}}"]},opencode:{mode:"argv",argv:["opencode","run","--session","{{session_id}}","{{prompt}}"]},gemini:{mode:"argv",argv:["gemini","-p","{{prompt}}","--resume","{{session_id}}"]},copilot:{mode:"argv",argv:["gh","copilot","--","--resume={{session_id}}","-p","{{prompt}}","-s","--allow-all-tools"]},qwen:{mode:"argv",argv:["qwen","-p","{{prompt}}","--resume","{{session_id}}","--approval-mode","yolo"]},agy:{mode:"argv",argv:["agy","--conversation","{{session_id}}","-p","{{prompt}}","--dangerously-skip-permissions","--print-timeout","8h"]},kimi:{mode:"argv",argv:["kimi","-p","{{prompt}}","--session","{{session_id}}","--output-format","stream-json"]},hermes:{mode:"argv",argv:["hermes","--yolo","-z","{{prompt}}","--resume","{{session_id}}"]}}});function Xh(t=process.env){let e=t.LMCTL_ONE_SHOT_TIMEOUT_MS;if(!e)return 6e5;let n=Number(e);return!Number.isFinite(n)||n<=0?6e5:n}var Jh=E(()=>{"use strict"});var oL,ce,po,it=E(()=>{"use strict";oL="ACK: waiting for explicit lmctl task.",ce=`lmctl seed initial connection only. Create or pin this provider session, then stop. Do not inspect files, run commands, infer a task, delegate, or edit. A dispatch that dies mid-turn is usually a timeout you set -- use --idle-timeout, not a shell timeout. Reply exactly: ${oL}`,po=`send this exact lmctl seed instruction: "${ce}"`});import{existsSync as aL}from"node:fs";function Gh(t){let e=t.CLAUDE_CODE_EXECPATH;if(e===void 0||e.length===0)return t;let n=process.platform!=="win32"&&e.toLowerCase().endsWith(".exe"),r=!n&&!aL(e);if(!n&&!r)return t;L({event:"claude_execpath_sanitized",reason:n?"wrong_platform_exe":"missing_file",value:e,platform:process.platform});let s={...t};return delete s.CLAUDE_CODE_EXECPATH,s}function Nn(t,e){let n={...t??process.env,PWD:e};return delete n.OLDPWD,n}function cL(t,e){return e===void 0||e.length===0?t:{...t??process.env,[js]:e}}function Ke(t,e,n,r="chat"){return{...cL(Nn(t,e),n),[lL]:r}}var js,lL,xt=E(()=>{"use strict";ae();js="LMCTL_SELF_SESSIONID",lL="LMCTL_LAUNCH_SOURCE"});function _o(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Wc=E(()=>{"use strict"});import{spawn as Kh}from"node:child_process";import{mkdirSync as dL}from"node:fs";var qc,Te,ht=E(()=>{"use strict";Uc();Jh();it();xt();Wc();qc=class t extends Error{cancelReason;constructor(e,n){super(e),this.name="TurnAbortError",this.cancelReason=n,Object.setPrototypeOf(this,t.prototype)}},Te=class t{name;capabilities;injection;provider;binary;seedArgs;seedStdin;resumeTemplate;startTemplate;transportFn;constructor(e){this.name=e.provider.name,this.provider=e.provider,this.capabilities=e.capabilities,this.injection=e.injection,this.binary=e.binary,this.seedArgs=e.seedArgs,this.seedStdin=e.seedStdin,this.resumeTemplate=e.resumeTemplate,this.startTemplate=e.startTemplate,this.transportFn=e.transport}discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return this.provider.getWatchPaths?.()??[]}seedArgsFor(e){let n=e?.prompt;return n===void 0?this.seedArgs:this.seedArgs.map(r=>r===ce?n:r)}turnOptsFor(e){return e}seed(e,n){return dL(e,{recursive:!0}),new Promise(r=>{let s;try{s=Kh(this.binary,this.seedArgsFor(n),{cwd:e,env:Nn(void 0,e),stdio:["pipe","pipe","pipe"],timeout:6e4})}catch(a){return r({success:!1,error:a instanceof Error?a.message:String(a)})}let i="";s.stderr?.on("data",a=>{i+=a.toString()});let o=n?.prompt!==void 0&&this.seedStdin!==void 0?`${n.prompt}
1514
1514
  `:this.seedStdin;o&&s.stdin?.write(o),s.stdin?.end(),s.on("exit",a=>{if(a===0||a===null)r({success:!0});else{let l=_o(i).trim();r({success:!1,error:l.slice(0,500)||`exit code ${a}`})}}),s.on("error",a=>{r({success:!1,error:a.message})})})}resumeCommand(e,n){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,e)}startCommand(e){return this.startTemplate}manualSeedHint(e){return{launchCommand:`cd ${e} && ${this.binary}`,postLaunchNote:po,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,n){let r=this.turnOptsFor(n);if(r.userConfig&&Hh(r.userConfig,this.name)){let i=r.userConfig.tools[this.name];if(i?.agent)return this.runOneShotAgent(e,r,i.agent)}let s=r.timeoutMs??t.DEFAULT_IDLE_TIMEOUT_MS;return s<=0&&!r.signal?this.transportFn(e,{...r,binary:this.binary}):this.withTimeouts(s,e,r)}withTimeouts(e,n,r){let s=new AbortController,i,o,a="",l,c=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{r.onIdleWarning?.(e),u(),s.abort(),l&&l({text:a,sessionId:r.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},u=()=>{clearTimeout(i)};r.signal&&(r.signal.aborted?(o="external",s.abort()):r.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),c();let d={...r,binary:this.binary,signal:s.signal,onDelta:p=>{a+=p,c(),r.onDelta?.(p)},onProgress:p=>{p.kind!=="api_retry"&&c(),r.onProgress?.(p)}},f=this.transportFn(n,d).then(p=>(u(),{...p,status:"ok"})).catch(p=>{throw u(),o==="external"?new qc("Turn cancelled","external"):p}),m=new Promise(p=>{l=p});return Promise.race([f,m])}runOneShotAgent(e,n,r){let s=Bh(n.userConfig,this.name,n.sessionId,e,n.profile),i=Date.now();return new Promise((o,a)=>{let l=Xh(n.env),c=Kh(s,{shell:!0,cwd:n.cwd,env:Ke(n.env,n.cwd,n.sessionId),stdio:["pipe","pipe","pipe"]}),u=!1,d=!1,f=setTimeout(()=>{d=!0,c.kill()},l),m="",p="";if(c.stdout?.on("data",h=>{let _=h.toString();m+=_,n.onDelta?.(_)}),c.stderr?.on("data",h=>{p+=h.toString()}),n.signal){if(n.signal.aborted)return clearTimeout(f),c.kill(),a(new Error("Aborted"));n.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",h=>{if(u)return;u=!0,clearTimeout(f);let _=Date.now()-i;d?a(new Error(`Agent command timed out after ${l}ms`)):h===0||h===null?o({text:m.trim(),sessionId:n.sessionId,durationMs:_}):a(new Error(p.trim().slice(0,200)||`Agent command exited with code ${h}`))}),c.on("error",h=>{u||(u=!0,clearTimeout(f),a(h))})})}}});function go(t,e){let n;if(e&&typeof e=="object"){let r=e.code;typeof r=="number"&&(n=r)}return new ln(t,n,e)}var gt,we,an,ho,ln,Rr=E(()=>{"use strict";gt=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},we=class extends gt{},an=class extends gt{exitCode;signal;stderr;constructor(e,n,r=null,s){super(e),this.exitCode=n,this.signal=r,this.stderr=s}},ho=class extends gt{line;constructor(e,n,r){super(e,{cause:r}),this.line=n}},ln=class extends gt{rpcCode;rpcData;constructor(e,n,r){super(e),n!==void 0&&(this.rpcCode=n),r!==void 0&&(this.rpcData=r)}}});import*as Bc from"node:child_process";function fL(t){if(typeof Bc.spawnSync=="function")try{Bc.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function Vh(t){return t.exitCode!==null||t.signalCode!==null}function Hc(t,e){return Vh(t)?Promise.resolve(!0):new Promise(n=>{let r=!1,s=()=>{r||(r=!0,clearTimeout(i),n(!0))},i=setTimeout(()=>{r||(r=!0,t.removeListener("exit",s),n(!1))},e);t.once("exit",s)})}async function Qe(t,e={}){let n=Date.now(),r=e.stdinEnd!==!1,s=e.softDelayMs??5e3,i=e.killDelayMs??5e3,o=e.platform??process.platform,a=e.runTaskkill??fL;if(Vh(t))return{signal:"natural",elapsedMs:Date.now()-n};if(r&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await Hc(t,s))return{signal:"stdin",elapsedMs:Date.now()-n};if(o==="win32"&&typeof t.pid=="number")a(t.pid);else try{t.kill("SIGTERM")}catch{}if(await Hc(t,i))return{signal:"SIGTERM",elapsedMs:Date.now()-n};if(o!=="win32")try{t.kill("SIGKILL")}catch{}return await Hc(t,uL)?{signal:"SIGKILL",elapsedMs:Date.now()-n}:{signal:"abandoned",elapsedMs:Date.now()-n}}var uL,Ps=E(()=>{"use strict";uL=1e3});function Yh(t){ue()&&Pe({event:"legacy",msg:`[debug] ${t}`},{always:!0})}function An(t,e){let n=pL[t];if(n)return n[e]??n.yolo}function hL(t,e){if(e.length===0)return!0;for(let n=0;n+e.length<=t.length;n++){let r=!0;for(let s=0;s<e.length;s++)if(t[n+s]!==e[s]){r=!1;break}if(r)return!0}return!1}function et(t,e,n="yolo"){if(_L.has(t)){Yh(`YOLO ${t} [mode=${n}]: ${t==="codex"?`JSON-RPC params (approvalPolicy=never, sandbox=${n==="plan"?"read-only":"danger-full-access"})`:t==="opencode"?".opencode/opencode.json (permission=allow)":t==="kimi"?`ACP session/set_config_option (configId=mode, value=${n==="plan"?"plan":"auto"})`:t==="dsh"?"DSH_PERMISSION_MODE=danger-full-access env var on the sidecar spawn \u2014 no argv flag":t==="hermes"?"HERMES_YOLO_MODE=1 shell gate + ACP session/set_mode (modeId=dont_ask) edit gate":"protocol/config (out-of-band)"} \u2014 no argv flag`);return}let r=n==="plan"?An(t,"plan"):mL[t];if(!r){let s=`unknown provider "${t}" \u2014 YOLO contract not configured. Add an entry to YOLO_FLAGS in src/providers/yolo-contract.ts before spawning this provider.`;throw L({event:"yolo_assert_failed",provider:t,reason:"unconfigured_provider",args:e.join(" "),message:s}),new we(s)}if(!hL(e,r)){let s=r.join(" "),i=`${t} spawn missing YOLO flag '${s}' \u2014 YOLO is mandatory for every provider; see src/providers/yolo-contract.ts. Got argv: [${e.map(o=>JSON.stringify(o)).join(", ")}]`;throw L({event:"yolo_assert_failed",provider:t,reason:"flag_missing",required_flag:s,mode:n,args:e.join(" "),message:i}),new we(i)}Yh(`YOLO ${t} [mode=${n}]: argv flag '${r.join(" ")}'`)}var mL,pL,_L,er=E(()=>{"use strict";Rr();ae();mL={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},pL={claude:{yolo:["--dangerously-skip-permissions"],plan:["--permission-mode","plan"]},qwen:{yolo:["--approval-mode","yolo"],plan:["--approval-mode","plan"]},gemini:{yolo:["-y"],plan:["--approval-mode","plan"]},copilot:{yolo:["--yolo"],plan:["--yolo"]},agy:{yolo:["--dangerously-skip-permissions"],plan:["--dangerously-skip-permissions"]},lmplayer:{yolo:["--dangerously-skip-permissions"],plan:["--dangerously-skip-permissions"]}};_L=new Set(["codex","opencode","kimi","dsh","hermes"])});async function vL(t,e,n){if(typeof t=="boolean")return t;let r,s;try{return await Promise.race([t,new Promise(i=>{r=setTimeout(()=>i(Xc),e),r.unref?.(),n!==void 0&&(s=()=>i(Xc),n.addEventListener("abort",s,{once:!0}))})])}finally{r!==void 0&&clearTimeout(r),s!==void 0&&n?.removeEventListener("abort",s)}}function yo(t,e){if(t===void 0){e.closeStdin();return}let n=!1,r=i=>{if(!n){n=!0;try{t.onRelease?.({elapsedMs:Date.now()-i.startedMs,held:i.held,reason:i.reason})}catch{}}e.closeStdin()},s=Date.now();SL(t,e,s,r).catch(()=>{r({startedMs:s,held:!1,reason:"check-error"})})}async function SL(t,e,n,r){let s=t.pollMs??gL,i=t.maxHoldMs??yL,o=t.settleMs??wL,a=t.backgroundGraceMs??EL,l=!1,c=null,u=d=>r({startedMs:n,held:l,reason:d});for(;;){if(e.isAborted())return u("aborted");if(e.hasChildExited())return u("child-exited");let d=i-(Date.now()-n);if(d<=0)return u("max-hold");let f;try{f=await vL(t.hasOutstandingWork(),d,e.signal)}catch{return u("check-error")}if(f===Xc)return u(e.isAborted()||e.signal?.aborted===!0?"aborted":"max-hold");if(f)c=null;else{if(!l&&e.wasBackgroundJobLaunched?.()===!0&&Date.now()-n<a){let h=a-(Date.now()-n);await new Promise(_=>setTimeout(_,Math.max(0,Math.min(s,TL,h))).unref?.());continue}if(!l||o<=0)return u("cleared");c===null&&(c=Date.now(),Fe(`${e.label}: dispatched work cleared \u2014 settling ${o}ms before closing stdin`));let p=Math.max(c,e.lastEventAtMs());if(!e.isTurnInFlight()&&Date.now()-p>=o)return u("cleared")}if(l||(l=!0,t.onHold?.(),Fe(`${e.label}: deferring stdin close \u2014 outstanding dispatched work (poll ${s}ms)`)),Date.now()-n>=i)return L({event:"transport_hold_open_max_wait",provider:e.label,elapsed_ms:Date.now()-n}),u("max-hold");let m=Math.max(0,Math.min(s,i-(Date.now()-n)));await new Promise(p=>setTimeout(p,m).unref?.())}}var gL,yL,wL,EL,TL,Xc,Jc=E(()=>{"use strict";ae();gL=2e3,yL=8*60*60*1e3,wL=5e3,EL=1e3,TL=50,Xc=Symbol("check-timed-out")});function zh(t){if(t.length===0)return"";if(t.length===1)return t[0];let e=[];for(let n=0;n<t.length;n++)n===0?e.push(t[n]):e.push(`
1515
1515
 
1516
1516
  --- additional response (turn ${n+1} of ${t.length}; likely an injected mid-call notification) ---
@@ -2332,7 +2332,7 @@ ${im(t)}`}function YS(t,e){let n=_r(t,e);return n.ok?{ok:!0,identity:n.identity,
2332
2332
  ORDER BY started_at DESC, id DESC
2333
2333
  `).all(...r)}function cm(t,e={}){return Sl(t,e).filter(r=>r.kind==="chat"&&r.status==="running"&&Xt(r)==="dead")}function XB(t){let e=new Set,n=[];for(let r of t)e.has(r.id)||(e.add(r.id),n.push(r));return n.sort((r,s)=>{let i=Date.parse(s.started_at)-Date.parse(r.started_at);return Number.isFinite(i)&&i!==0?i:s.id-r.id})}function dm(t){return t.filter(e=>Xt(e)!=="dead")}async function ab(t){let e=[];for(let n of t)e.push(await JB(n));return e}async function JB(t){let e=t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`,n={tracked_invocation_id:t.id,from_identity:t.from_identity,target:e??"(unknown)",started_at:t.started_at,tail_hint:e===null?"":`lmctl tail "${t.target_teamfile}" ${t.target_alias}`};if(e===null)return hr(n,"missing-target",null,null);if(t.request_payload===null||t.request_payload.length===0)return hr(n,"missing-request-payload",null,null);let r=GB(t.meta);if(r.provider===null||r.sessionid===null)return hr(n,"missing-session-metadata",r.provider,r.sessionid);if(!KB(r.provider))return hr(n,"unsupported-provider",r.provider,r.sessionid);let s;try{s=await Ne(r.sessionid,r.provider)}catch{return hr(n,"read-error",r.provider,r.sessionid)}if(s===null)return hr(n,"session-not-found",r.provider,r.sessionid);let i=VB(t.request_payload,s.messages);return i.state!=="completed"?hr(n,i.reason,r.provider,r.sessionid):{...n,state:"completed",reason:null,provider:r.provider,session_id:r.sessionid,result_payload:i.result,result_preview:ub(i.result),assistant_timestamp:i.assistantTimestamp,matched_user_index:i.userIndex}}function hr(t,e,n,r){return{...t,state:"unreconciled",reason:e,provider:n,session_id:r,result_payload:null,result_preview:null,assistant_timestamp:null,matched_user_index:null}}function GB(t){if(t===null||t.trim()==="")return{provider:null,sessionid:null};try{let e=JSON.parse(t);return{provider:typeof e.provider=="string"&&e.provider.length>0?e.provider:null,sessionid:typeof e.sessionid=="string"&&e.sessionid.length>0?e.sessionid:null}}catch{return{provider:null,sessionid:null}}}function KB(t){return["claude","codex","gemini","copilot","opencode","lmplayer","qwen","agy","kimi","dsh","hermes","ClaudeMock"].includes(t)}function VB(t,e){let n=e.map((i,o)=>({message:i,index:o})).filter(({message:i})=>i.role==="user"&&i.content===t);if(n.length===0)return{state:"unreconciled",reason:"request-not-found"};if(n.length>1)return{state:"unreconciled",reason:"duplicate-request"};let r=n[0].index,s=[];for(let i of e.slice(r+1)){if(i.role==="user")break;i.role==="assistant"&&i.content.trim().length>0&&s.push(i)}return s.length===0?{state:"unreconciled",reason:"no-assistant-response"}:{state:"completed",userIndex:r,result:s.map(i=>i.content).join(`
2334
2334
 
2335
- `),assistantTimestamp:YB(s[s.length-1]?.timestamp)}}function YB(t){if(t===void 0)return null;let e=t.getTime();return Number.isFinite(e)?t.toISOString():null}function zB(t){if(!(t===null||t.trim()===""))try{let e=JSON.parse(t);if(!Array.isArray(e))return;let n=e.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}catch{return}}function um(t){let e=zB(t.config_warnings);return{id:t.id,kind:t.kind,origin:t.origin,status:t.status,holder_liveness:Xt(t),from_identity:t.from_identity,target:t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`,started_at:t.started_at,ended_at:t.ended_at,result:nb(t.result_summary),error:nb(t.error),...e!==void 0?{config_warnings:e}:{}}}function ZB(t,e){return t.scope==="self"?e2(t,e):t2(t,e)}function QB(t){if(t===null)return"idle";let e=t.holder_pid!==null?`pid ${t.holder_pid}${t.holder_host!==null?` on ${t.holder_host}`:""}`:"holder",n=t.reason==="dead-pid"?"appears dead":"stale";return`idle (reclaimable lock: ${e} ${n})`}function e2(t,e){let n=[];n.push(`identity: ${t.identity}`),n.push(`team: ${t.team.name}`),n.push(`teamfile: ${t.team.teamfile}`),n.push(""),n.push("members:"),t.members.length===0&&n.push(" none");for(let r of t.members){let s=r.model===null?"":` model=${r.model}`,i=r.sessionid===null?"":` session=${r.sessionid}`,o=r.state==="idle"?QB(r.reclaimable):`busy (${r.reason})`,a=r.handling===null?"":` handling="${r.handling.request_preview}"`;n.push(` ${r.alias}: ${o} provider=${r.provider}${s}${i}${a}`)}return n.push(""),n.push("transcript harvest:"),cb(n,t.transcript_harvest,"self"),n.push(""),n.push("activity from me:"),fm(n,mm(t.activity.from_me,e.sinceIso),"from-me"),n.push(""),n.push("activity to me:"),fm(n,mm(t.activity.to_me,e.sinceIso),"to-me"),n.push(""),n.push(lb(t)),n.join(`
2335
+ `),assistantTimestamp:YB(s[s.length-1]?.timestamp)}}function YB(t){if(t===void 0)return null;let e=t.getTime();return Number.isFinite(e)?t.toISOString():null}function zB(t){if(!(t===null||t.trim()===""))try{let e=JSON.parse(t);if(!Array.isArray(e))return;let n=e.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}catch{return}}function um(t){let e=zB(t.config_warnings);return{id:t.id,kind:t.kind,origin:t.origin,status:t.status,holder_liveness:Xt(t),from_identity:t.from_identity,target:t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`,started_at:t.started_at,ended_at:t.ended_at,result:nb(t.result_summary),error:nb(t.error),...e!==void 0?{config_warnings:e}:{}}}function ZB(t,e){return t.scope==="self"?e2(t,e):t2(t,e)}function QB(t){if(t===null)return"idle";let e=t.holder_pid!==null?`pid ${t.holder_pid}${t.holder_host!==null?` on ${t.holder_host}`:""}`:"holder",n=t.reason==="dead-pid"?"appears dead -- usually a mid-turn kill, most often a shell `timeout` wrapper; use --idle-timeout instead":"stale";return`idle (reclaimable lock: ${e} ${n})`}function e2(t,e){let n=[];n.push(`identity: ${t.identity}`),n.push(`team: ${t.team.name}`),n.push(`teamfile: ${t.team.teamfile}`),n.push(""),n.push("members:"),t.members.length===0&&n.push(" none");for(let r of t.members){let s=r.model===null?"":` model=${r.model}`,i=r.sessionid===null?"":` session=${r.sessionid}`,o=r.state==="idle"?QB(r.reclaimable):`busy (${r.reason})`,a=r.handling===null?"":` handling="${r.handling.request_preview}"`;n.push(` ${r.alias}: ${o} provider=${r.provider}${s}${i}${a}`)}return n.push(""),n.push("transcript harvest:"),cb(n,t.transcript_harvest,"self"),n.push(""),n.push("activity from me:"),fm(n,mm(t.activity.from_me,e.sinceIso),"from-me"),n.push(""),n.push("activity to me:"),fm(n,mm(t.activity.to_me,e.sinceIso),"to-me"),n.push(""),n.push(lb(t)),n.join(`
2336
2336
  `)}function t2(t,e){let n=[];n.push("scope: db"),n.push("identity: none"),n.push(""),n.push("teams:"),t.teams.length===0&&n.push(" none");for(let r of t.teams){let s=r.name===null?"(unnamed)":r.name;n.push(` ${s}: ${r.teamfile} (${r.member_count} members)`)}return n.push(""),n.push("transcript harvest:"),cb(n,t.transcript_harvest,"db"),n.push(""),n.push("recent activity:"),fm(n,mm(t.activity,e.sinceIso),"db"),n.push(""),n.push(lb(t)),n.join(`
2337
2337
  `)}function lb(t){return vs(t.db_path)}function fm(t,e,n){if(e.length===0){t.push(" none");return}for(let r of e.slice(0,vl))n2(t,r,n);db(t,e.length,vl,"older")}function cb(t,e,n){if(e.length===0){t.push(" none");return}for(let r of e.slice(0,vl)){let s=n==="db"?` from ${bt(r.from_identity)} -> ${bt(r.target)}`:` -> ${bt(r.target)}`;if(r.state==="completed"){let i=r.result_preview===null?"":` "${r.result_preview}"`;t.push(` #${r.tracked_invocation_id} completed in transcript; lmctl DB not finalized${s} since ${r.started_at}${i}`)}else t.push(` #${r.tracked_invocation_id} unreconciled${s} since ${r.started_at} (${r.reason??"unknown"})`);r.tail_hint.length>0&&t.push(` inspect: ${r.tail_hint}`)}db(t,e.length,vl,"more transcript harvest rows")}function mm(t,e){let n=Date.parse(e);return Number.isFinite(n)?t.filter(r=>{let s=Date.parse(r.ended_at??r.started_at);return Number.isFinite(s)&&s>=n}):t}function n2(t,e,n){let r=s2(e,n),s=e.status==="running"?`since ${e.started_at}`:`ended ${e.ended_at??e.started_at}`,i=e.error??e.result,o=i===null?"":` "${ub(i)}"`;if(t.push(` #${e.id} ${r2(e)} ${e.kind}${r} ${s}${o}`),e.config_warnings!==void 0)for(let a of e.config_warnings)t.push(` config not applied: ${a}`)}function r2(t){return t.status==="running"&&t.holder_liveness==="unknown"?"RUNNING_UNKNOWN":t.status.toUpperCase()}function s2(t,e){if(e==="from-me")return t.target===null?"":` -> ${bt(t.target)}`;if(e==="to-me")return` from ${bt(t.from_identity)}`;let n=t.target===null?"":` -> ${bt(t.target)}`;return` from ${bt(t.from_identity)}${n}`}function db(t,e,n,r){let s=e-n;s>0&&t.push(` (+${s} ${r} -- use --json)`)}function nb(t){return t===null||t.length===0?null:t.replace(/\s+/g," ").trim()}function ub(t){let e=t.replace(/\s+/g," ").trim();return e.length<=QS?e:`${e.slice(0,QS-3)}...`}function i2(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=eb?e:`${e.slice(0,eb-3)}...`}function bl(t){let e=Math.max(0,Math.floor(t/1e3));if(e<60)return`${e}s`;let n=Math.floor(e/60);if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<48?`${r}h`:`${Math.floor(r/24)}d`}function wi(t){let e=Date.parse(t);return Number.isFinite(e)?bl(Date.now()-e):"unknown age"}function bt(t){if(t==="operator")return t;try{let e=Je(t);return`${LB(e.teamfile)}:${e.alias}`}catch{return t}}function o2(t){if(t===void 0)return{iso:new Date(Date.now()-PB).toISOString()};let e=/^(\d+)([smhd])$/.exec(t);if(e!==null){let r=Number(e[1]),s=e[2],i=s==="s"?r:s==="m"?r*60:s==="h"?r*3600:r*86400;return{iso:new Date(Date.now()-i*1e3).toISOString()}}let n=Date.parse(t);return Number.isFinite(n)?{iso:new Date(n).toISOString()}:{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`}}var DB,jB,vl,PB,QS,eb,kl=E(()=>{"use strict";pt();Ie();wl();He();yi();en();Uc();St();DB=`usage: lmctl status [--json] [--since <duration|ISO8601>]
2338
2338
 
@@ -2541,6 +2541,10 @@ Safe input (no shell involved) \u2014 use for anything non-trivial:
2541
2541
  under 1000 is refused outright since no real provider call finishes that
2542
2542
  fast. Default is a generous 8 hours; do not lower it to "fail fast" on a
2543
2543
  slow member, that kills one still making real progress.
2544
+ A dispatch that dies mid-turn, repeatedly, at roughly the same point, is
2545
+ usually a timeout YOU set, not a broken member: a shell \`timeout\` SIGTERMs
2546
+ the process regardless of --idle-timeout, killing real progress. Use
2547
+ --idle-timeout (above) instead of wrapping this command in one.
2544
2548
  Managed-team --json synchronous sends emit an early {"status":"accepted",
2545
2549
  "message_id":"msg_..."} line after durable creation, then a final result line
2546
2550
  with the same message_id. A busy outcome emits one error line.
@@ -3140,7 +3144,7 @@ CREATE TABLE IF NOT EXISTS build_lock (
3140
3144
  small. Re-read after the next turn before concluding a compaction failed or gating on the value.
3141
3145
  `),y.length>0){t.stdout.write(`Session limits:
3142
3146
  `);for(let w of y)t.stdout.write(` ${w.reportPath}: LIMITED resets_at=${qA(w.sessionLimit)}
3143
- `)}return 0}function UA(t,e,n,r){let s=be(t,e);if(n.has(s))return[];n.add(s);let i=rt(s,e);if(i.parseErrors.length>0)throw new Error(`${s}: ${i.parseErrors.join("; ")}`);let o=[];for(let a of i.members){if(a.teamfile!==void 0){o.push(...UA(BV(FA(s),a.teamfile),e,n,[...r,a.alias]));continue}a.session===void 0||a.session.length===0||o.push({teamfile:s,alias:a.alias,reportPath:[...r,a.alias].join("/"),provider:a.provider,sessionid:a.session})}return o}async function QV(t,e,n){let r=await WA(t,[{teamfile:e.teamfile,alias:e.alias}]),s=HA(e.teamfile),i=s.kind==="repo"?s:null;return{teamfile:e.teamfile,reportPath:e.alias,lastContext:n.lastInputTokens??null,liveness:r.get(Lp(e.teamfile,e.alias))??Cp(),...i!==null?{activitySinceLastCommit:{messageCount:BA(n,i.since),tokens:null},cumulativeTokens:XA(n)??"n/a"}:{}}}async function WA(t,e){try{let n=await C(t,r=>e.map(s=>{let i=kr(r,s.teamfile,s.alias);return[Lp(s.teamfile,s.alias),eY(i)]}));return new Map(n)}catch{return new Map}}function Lp(t,e){return`${t}\0${e.toLowerCase()}`}function eY(t){return t.busy?t.reason==="terminal-held"?t.source==="terminal-invocation"?{state:"busy",reason:"terminal-held",inFlight:null,terminalLock:null,terminalInvocation:{id:t.terminalInvocation.id,startedAt:t.terminalInvocation.started_at,lastHeartbeat:t.terminalInvocation.last_heartbeat_at,holderPid:t.terminalInvocation.holder_pid,holderHost:t.terminalInvocation.holder_host},reclaimable:null}:{state:"busy",reason:"terminal-held",inFlight:null,terminalLock:{startedAt:t.terminalLock.started_at,lastHeartbeat:t.terminalLock.last_heartbeat,holderPid:t.terminalLock.holder_pid,holderHost:t.terminalLock.holder_host},terminalInvocation:null,reclaimable:null}:{state:"busy",reason:"in-flight",inFlight:{senderTeamfile:t.inFlight.sender_teamfile,senderAlias:t.inFlight.sender_alias,startedAt:t.inFlight.started_at,activeCount:t.inFlight.active_count,holderPid:t.inFlight.holder_pid},terminalLock:null,terminalInvocation:null,reclaimable:null}:Cp(t.reclaimable===void 0?null:{source:t.reclaimable.source,holderPid:t.reclaimable.holder_pid,holderHost:t.reclaimable.holder_host,reason:t.reclaimable.reason})}function Cp(t=null){return{state:"idle",reason:null,inFlight:null,terminalLock:null,terminalInvocation:null,reclaimable:t}}function Rp(t){if(t.state!=="idle")return`busy (${t.reason})`;if(t.reclaimable!==null){let{holderPid:e,holderHost:n,reason:r}=t.reclaimable;return`idle (reclaimable lock: ${e!==null?`pid ${e}${n!==null?` on ${n}`:""}`:"holder"} ${r==="dead-pid"?"appears dead":"stale"})`}return"idle"}function qA(t){return t.resets_at!==null?t.resets_at:t.timezone!==null?`${t.reset_time} (${t.timezone})`:t.reset_time}function Ut(t){return t==null?"unknown":String(t)}function tY(t){return t==="n/a"?t:Ut(t)}function nY(t,e,n=String){return t!==void 0?n(t):e?"n/a":"unknown"}function HA(t){let e=FA(t),n;try{xp("git",["-C",e,"rev-parse","--is-inside-work-tree"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{kind:"unavailable",reason:"no-repo",teamDir:e}}try{n=xp("git",["-C",e,"log","-2","--format=%ct"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{kind:"unavailable",reason:"no-commits",teamDir:e}}let r=n.split(/\r?\n/).map(i=>Number.parseInt(i.trim(),10)).filter(i=>Number.isFinite(i)&&i>0);if(r.length===0)return{kind:"unavailable",reason:"no-commits",teamDir:e};let s=r.slice(0,2).map((i,o)=>({ref:o===0?"HEAD":`HEAD~${o}`,timestamp:new Date(i*1e3)}));return{kind:"repo",teamDir:e,since:s[0].timestamp,commits:s,working:rY(e)}}function rY(t){let e;try{e=xp("git",["-C",t,"status","--porcelain"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{uncommittedTracked:null,untracked:null}}let n=0,r=0;for(let s of e.split(/\r?\n/))s.trim().length!==0&&(s.startsWith("??")?r+=1:n+=1);return{uncommittedTracked:n,untracked:r}}function BA(t,e){let n=e.getTime();return t.messages.filter(r=>(r.role==="user"||r.role==="assistant")&&Number.isFinite(r.timestamp.getTime())&&r.timestamp.getTime()>n).length}function XA(t){if(t===null)return null;let e=[t.totalInputTokens,t.totalCachedInputTokens,t.totalCacheWriteInputTokens,t.totalOutputTokens,t.totalReasoningOutputTokens].filter(n=>typeof n=="number"&&Number.isFinite(n));return e.length===0?null:e.reduce((n,r)=>n+r,0)}var XV,Op,JV,GA=E(()=>{"use strict";St();Ie();dt();en();pt();un();PA();XV={name:"health",allowsBareTeamfile:!0,supportsRaw:!0},Op=2,JV=`usage: lmctl health [target] [alias]
3147
+ `)}return 0}function UA(t,e,n,r){let s=be(t,e);if(n.has(s))return[];n.add(s);let i=rt(s,e);if(i.parseErrors.length>0)throw new Error(`${s}: ${i.parseErrors.join("; ")}`);let o=[];for(let a of i.members){if(a.teamfile!==void 0){o.push(...UA(BV(FA(s),a.teamfile),e,n,[...r,a.alias]));continue}a.session===void 0||a.session.length===0||o.push({teamfile:s,alias:a.alias,reportPath:[...r,a.alias].join("/"),provider:a.provider,sessionid:a.session})}return o}async function QV(t,e,n){let r=await WA(t,[{teamfile:e.teamfile,alias:e.alias}]),s=HA(e.teamfile),i=s.kind==="repo"?s:null;return{teamfile:e.teamfile,reportPath:e.alias,lastContext:n.lastInputTokens??null,liveness:r.get(Lp(e.teamfile,e.alias))??Cp(),...i!==null?{activitySinceLastCommit:{messageCount:BA(n,i.since),tokens:null},cumulativeTokens:XA(n)??"n/a"}:{}}}async function WA(t,e){try{let n=await C(t,r=>e.map(s=>{let i=kr(r,s.teamfile,s.alias);return[Lp(s.teamfile,s.alias),eY(i)]}));return new Map(n)}catch{return new Map}}function Lp(t,e){return`${t}\0${e.toLowerCase()}`}function eY(t){return t.busy?t.reason==="terminal-held"?t.source==="terminal-invocation"?{state:"busy",reason:"terminal-held",inFlight:null,terminalLock:null,terminalInvocation:{id:t.terminalInvocation.id,startedAt:t.terminalInvocation.started_at,lastHeartbeat:t.terminalInvocation.last_heartbeat_at,holderPid:t.terminalInvocation.holder_pid,holderHost:t.terminalInvocation.holder_host},reclaimable:null}:{state:"busy",reason:"terminal-held",inFlight:null,terminalLock:{startedAt:t.terminalLock.started_at,lastHeartbeat:t.terminalLock.last_heartbeat,holderPid:t.terminalLock.holder_pid,holderHost:t.terminalLock.holder_host},terminalInvocation:null,reclaimable:null}:{state:"busy",reason:"in-flight",inFlight:{senderTeamfile:t.inFlight.sender_teamfile,senderAlias:t.inFlight.sender_alias,startedAt:t.inFlight.started_at,activeCount:t.inFlight.active_count,holderPid:t.inFlight.holder_pid},terminalLock:null,terminalInvocation:null,reclaimable:null}:Cp(t.reclaimable===void 0?null:{source:t.reclaimable.source,holderPid:t.reclaimable.holder_pid,holderHost:t.reclaimable.holder_host,reason:t.reclaimable.reason})}function Cp(t=null){return{state:"idle",reason:null,inFlight:null,terminalLock:null,terminalInvocation:null,reclaimable:t}}function Rp(t){if(t.state!=="idle")return`busy (${t.reason})`;if(t.reclaimable!==null){let{holderPid:e,holderHost:n,reason:r}=t.reclaimable;return`idle (reclaimable lock: ${e!==null?`pid ${e}${n!==null?` on ${n}`:""}`:"holder"} ${r==="dead-pid"?"appears dead -- usually a mid-turn kill, most often a shell `timeout` wrapper; use --idle-timeout instead":"stale"})`}return"idle"}function qA(t){return t.resets_at!==null?t.resets_at:t.timezone!==null?`${t.reset_time} (${t.timezone})`:t.reset_time}function Ut(t){return t==null?"unknown":String(t)}function tY(t){return t==="n/a"?t:Ut(t)}function nY(t,e,n=String){return t!==void 0?n(t):e?"n/a":"unknown"}function HA(t){let e=FA(t),n;try{xp("git",["-C",e,"rev-parse","--is-inside-work-tree"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{kind:"unavailable",reason:"no-repo",teamDir:e}}try{n=xp("git",["-C",e,"log","-2","--format=%ct"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{kind:"unavailable",reason:"no-commits",teamDir:e}}let r=n.split(/\r?\n/).map(i=>Number.parseInt(i.trim(),10)).filter(i=>Number.isFinite(i)&&i>0);if(r.length===0)return{kind:"unavailable",reason:"no-commits",teamDir:e};let s=r.slice(0,2).map((i,o)=>({ref:o===0?"HEAD":`HEAD~${o}`,timestamp:new Date(i*1e3)}));return{kind:"repo",teamDir:e,since:s[0].timestamp,commits:s,working:rY(e)}}function rY(t){let e;try{e=xp("git",["-C",t,"status","--porcelain"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{uncommittedTracked:null,untracked:null}}let n=0,r=0;for(let s of e.split(/\r?\n/))s.trim().length!==0&&(s.startsWith("??")?r+=1:n+=1);return{uncommittedTracked:n,untracked:r}}function BA(t,e){let n=e.getTime();return t.messages.filter(r=>(r.role==="user"||r.role==="assistant")&&Number.isFinite(r.timestamp.getTime())&&r.timestamp.getTime()>n).length}function XA(t){if(t===null)return null;let e=[t.totalInputTokens,t.totalCachedInputTokens,t.totalCacheWriteInputTokens,t.totalOutputTokens,t.totalReasoningOutputTokens].filter(n=>typeof n=="number"&&Number.isFinite(n));return e.length===0?null:e.reduce((n,r)=>n+r,0)}var XV,Op,JV,GA=E(()=>{"use strict";St();Ie();dt();en();pt();un();PA();XV={name:"health",allowsBareTeamfile:!0,supportsRaw:!0},Op=2,JV=`usage: lmctl health [target] [alias]
3144
3148
  lmctl health <teamfile> # team rollup
3145
3149
  lmctl health <sessionid> [--provider <name>]
3146
3150
  lmctl health --run <id> # run state, step rollup, and token totals
@@ -3325,6 +3329,11 @@ Existing files are never overwritten unless --force is supplied.
3325
3329
  `),0}function T8(t){return Bx(t)?t:`${t}.lmctl`}function v8(t){let e=Bx(t);return e?Hx(t,e):t}function S8(t){let{teamName:e,leadProvider:n}=t;return`# ${e}
3326
3330
 
3327
3331
  # Lead operating guide: https://lmctl.com/skills/lmctl-lead.md
3332
+ #
3333
+ # A dispatch that dies mid-turn, repeatedly, at roughly the same point, is usually a
3334
+ # timeout YOU set, not a broken member: a shell \`timeout\` SIGTERMs mid-turn. Long turns
3335
+ # (minutes, even an hour) are normal. Use \`--idle-timeout 0\` to disable, or an explicit
3336
+ # unit like \`300s\`/\`2h\` -- a bare integer is milliseconds.
3328
3337
 
3329
3338
  _MEMBER_ alias=Lead provider=${n}
3330
3339
 
@@ -3475,6 +3484,9 @@ Global flags:
3475
3484
  --debug Verbose diagnostics to ~/.lmctl/debug-*.log; on error,
3476
3485
  write full stack + cause chain and context to that file.
3477
3486
 
3487
+ A dispatch that dies mid-turn is usually a timeout YOU set, not a broken member --
3488
+ see 'lmctl help chat' for --idle-timeout instead of a shell \`timeout\` wrapper.
3489
+
3478
3490
  Run 'lmctl help <command>' for command-specific help.
3479
3491
  `,S0=new Set(["api","chat","serve","mcp","device","mail","team","terminal","tail","session","session-index","health","cost","restore","ls","lint","seed","hire","refresh","clone","restore-teamfile","plan","diagnose","diagnose-prompt","status","running","db"]);function b0(t,e){return t.stderr.write(`error: ${e}
3480
3492
  ${Es}Run 'lmctl help' for usage.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lmctl-ai/lmctl",
3
- "version": "0.1.336",
3
+ "version": "0.1.337",
4
4
  "description": "A provider-agnostic control plane for teams of AI coding agents — across providers, with independent review and durable memory.",
5
5
  "type": "module",
6
6
  "homepage": "https://lmctl.com",