@lmctl-ai/lmctl 0.1.51 → 0.1.52

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 +14 -26
  2. package/package.json +1 -1
package/dist/cli/index.js CHANGED
@@ -862,10 +862,8 @@ var PT=Object.defineProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>{f
862
862
  AND agent_inflight.sender_teamfile = @reclaim_observed_sender_teamfile
863
863
  AND agent_inflight.sender_alias = @reclaim_observed_sender_alias
864
864
  AND agent_inflight.started_at = @reclaim_observed_started_at
865
- AND (
866
- (@reclaim_observed_holder_is_null = 1 AND agent_inflight.holder_pid IS NULL)
867
- OR (@reclaim_observed_holder_pid IS NOT NULL AND agent_inflight.holder_pid = @reclaim_observed_holder_pid)
868
- )
865
+ AND @reclaim_observed_holder_pid IS NOT NULL
866
+ AND agent_inflight.holder_pid = @reclaim_observed_holder_pid
869
867
  )
870
868
  THEN excluded.sender_teamfile
871
869
  ELSE agent_inflight.sender_teamfile
@@ -878,10 +876,8 @@ var PT=Object.defineProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>{f
878
876
  AND agent_inflight.sender_teamfile = @reclaim_observed_sender_teamfile
879
877
  AND agent_inflight.sender_alias = @reclaim_observed_sender_alias
880
878
  AND agent_inflight.started_at = @reclaim_observed_started_at
881
- AND (
882
- (@reclaim_observed_holder_is_null = 1 AND agent_inflight.holder_pid IS NULL)
883
- OR (@reclaim_observed_holder_pid IS NOT NULL AND agent_inflight.holder_pid = @reclaim_observed_holder_pid)
884
- )
879
+ AND @reclaim_observed_holder_pid IS NOT NULL
880
+ AND agent_inflight.holder_pid = @reclaim_observed_holder_pid
885
881
  )
886
882
  THEN excluded.sender_alias
887
883
  ELSE agent_inflight.sender_alias
@@ -894,10 +890,8 @@ var PT=Object.defineProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>{f
894
890
  AND agent_inflight.sender_teamfile = @reclaim_observed_sender_teamfile
895
891
  AND agent_inflight.sender_alias = @reclaim_observed_sender_alias
896
892
  AND agent_inflight.started_at = @reclaim_observed_started_at
897
- AND (
898
- (@reclaim_observed_holder_is_null = 1 AND agent_inflight.holder_pid IS NULL)
899
- OR (@reclaim_observed_holder_pid IS NOT NULL AND agent_inflight.holder_pid = @reclaim_observed_holder_pid)
900
- )
893
+ AND @reclaim_observed_holder_pid IS NOT NULL
894
+ AND agent_inflight.holder_pid = @reclaim_observed_holder_pid
901
895
  )
902
896
  THEN excluded.started_at
903
897
  ELSE agent_inflight.started_at
@@ -910,10 +904,8 @@ var PT=Object.defineProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>{f
910
904
  AND agent_inflight.sender_teamfile = @reclaim_observed_sender_teamfile
911
905
  AND agent_inflight.sender_alias = @reclaim_observed_sender_alias
912
906
  AND agent_inflight.started_at = @reclaim_observed_started_at
913
- AND (
914
- (@reclaim_observed_holder_is_null = 1 AND agent_inflight.holder_pid IS NULL)
915
- OR (@reclaim_observed_holder_pid IS NOT NULL AND agent_inflight.holder_pid = @reclaim_observed_holder_pid)
916
- )
907
+ AND @reclaim_observed_holder_pid IS NOT NULL
908
+ AND agent_inflight.holder_pid = @reclaim_observed_holder_pid
917
909
  )
918
910
  THEN 1
919
911
  ELSE agent_inflight.active_count
@@ -926,10 +918,8 @@ var PT=Object.defineProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>{f
926
918
  AND agent_inflight.sender_teamfile = @reclaim_observed_sender_teamfile
927
919
  AND agent_inflight.sender_alias = @reclaim_observed_sender_alias
928
920
  AND agent_inflight.started_at = @reclaim_observed_started_at
929
- AND (
930
- (@reclaim_observed_holder_is_null = 1 AND agent_inflight.holder_pid IS NULL)
931
- OR (@reclaim_observed_holder_pid IS NOT NULL AND agent_inflight.holder_pid = @reclaim_observed_holder_pid)
932
- )
921
+ AND @reclaim_observed_holder_pid IS NOT NULL
922
+ AND agent_inflight.holder_pid = @reclaim_observed_holder_pid
933
923
  )
934
924
  THEN excluded.holder_pid
935
925
  ELSE agent_inflight.holder_pid
@@ -941,10 +931,8 @@ var PT=Object.defineProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>{f
941
931
  AND agent_inflight.sender_teamfile = @reclaim_observed_sender_teamfile
942
932
  AND agent_inflight.sender_alias = @reclaim_observed_sender_alias
943
933
  AND agent_inflight.started_at = @reclaim_observed_started_at
944
- AND (
945
- (@reclaim_observed_holder_is_null = 1 AND agent_inflight.holder_pid IS NULL)
946
- OR (@reclaim_observed_holder_pid IS NOT NULL AND agent_inflight.holder_pid = @reclaim_observed_holder_pid)
947
- )
934
+ AND @reclaim_observed_holder_pid IS NOT NULL
935
+ AND agent_inflight.holder_pid = @reclaim_observed_holder_pid
948
936
  )
949
937
  RETURNING *
950
938
  `),clearAgentInflight:t.prepare("DELETE FROM agent_inflight WHERE receiver_teamfile = ? AND receiver_alias = ?"),clearAgentInflightIfSender:t.prepare(`
@@ -961,7 +949,7 @@ var PT=Object.defineProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>{f
961
949
  AND sender_teamfile = ?
962
950
  AND sender_alias = ?
963
951
  AND active_count > 1
964
- `),clearAgentInflightOlderThan:t.prepare("DELETE FROM agent_inflight WHERE started_at < ?")}}function uv(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var dl,Pe=b(()=>{"use strict";cl();Pn();dl=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=cv(e),this.claimTxn=e.transaction((r,n,s)=>{let o=this.stmts.selectClaimableJob.get(s,s,s);return o===void 0||this.stmts.claimJob.run(r,n,s,o.id,s,s,s).changes!==1?null:this.getJob(o.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,o)=>{let i=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of i){let l=this.getJob(a.id);if(l===null)continue;let c=o(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(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,o,i)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=o)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=o,u=a.status==="running"&&a.locked_until!==null&&a.locked_until<o;if(!c&&!u)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let d=i(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,o,a.id)?.count??0)>=Math.max(1,d.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,o,a.id,o,o,o).changes!==1){let p=this.getJob(a.id);return{claimed:!1,reason:p?.locked_until!==null&&p?.locked_until!==void 0&&p.locked_until>=o?"locked":"not_claimable",job_id:r,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:r}:{claimed:!0,job:m}}),this.resumeRunTxn=e.transaction((r,n,s)=>uv("state_not_found")),this.resumeInteractiveTxn=e.transaction((r,n,s,o)=>{let i=this.getInteractiveSessionByStepId(r);if(i===null)return{resumed:!1,reason:"not_found"};if(i.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(i.run_id);if(a===null)return{resumed:!1,reason:"run_not_found"};let l=s?"done":"waiting_agent";return this.stmts.updateInteractiveSession.run(l,n,Date.now(),i.id),this.stmts.resumeRunState.run(i.state_name,a.id),this.stmts.requeuePausedJob.run(o,a.job_id),{resumed:!0,session:this.getInteractiveSessionByStepId(r),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((r,n,s)=>{let o=this.stmts.getAttention.get(r);if(o===void 0)return{resumed:!1,reason:"not_found"};if(o.kind!==Qs)return{resumed:!1,reason:"wrong_kind"};if(o.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(o.run_id===null)return{resumed:!1,reason:"run_not_found"};let i=null,a=[];if(o.payload!==null)try{let u=JSON.parse(o.payload);u.step!==void 0&&typeof u.step.id=="string"&&u.step.id.length>0&&(i=u.step.id),Array.isArray(u.declared_outcomes)&&(a=u.declared_outcomes.filter(d=>typeof d=="string"))}catch{}if(i===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(o.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==Dn&&!a.includes(n))return{resumed:!1,reason:em};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[i]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(i,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,r),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(r,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=n.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...r,holder_pid:process.pid,stale_before:n.stale_before??null,force:n.force===!0?1:0,reclaim_observed_sender_teamfile:s?.sender_teamfile??null,reclaim_observed_sender_alias:s?.sender_alias??null,reclaim_observed_started_at:s?.started_at??null,reclaim_observed_holder_is_null:s?.holder_pid===null?1:0,reclaim_observed_holder_pid:typeof s?.holder_pid=="number"?s.holder_pid:null}),i=o!==void 0?{acquired:!0,current:o}:{acquired:!1,current:this.getAgentInflight(r.receiver_teamfile,r.receiver_alias)??(()=>{throw new Error("agent_inflight conflict row disappeared during acquire")})()};return this.db.exec("COMMIT"),i}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}}close(){this.db.close()}query(e,...r){let n=e.trim().toLowerCase();if(!n.startsWith("select")&&!n.startsWith("with")&&!n.startsWith("pragma"))throw new Error("Dal.query only allows read-only SELECT/WITH/PRAGMA statements");return this.db.prepare(e).all(...r)}insertWorkflow(e){rm(e.name,e.definition,i=>this.getWorkflowByName(i));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,P()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,P());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,n.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,n.id);let o=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),o}upsertWorkflow(e){rm(e.name,e.definition,i=>this.getWorkflowByName(i));let r=this.getWorkflowByName(e.name);if(r===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(r.id)?.version??r.version)+1,o=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,P());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(o.lastInsertRowid),e.definition,e.definition_schema_version??r.definition_schema_version,s,r.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,r.id),this.syncWorkflowTriggers(r.id,e.definition),this.getWorkflow(r.id)}insertCompositionUnit(e){this.stmts.insertCompositionUnit.run(e.name,e.version,e.lang,e.source,e.source_sha,e.compiled_workflow_version_id,P())}getWorkflow(e){return this.stmts.getWorkflow.get(e)??null}getWorkflowByName(e,r){return(r===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,r))??null}findWorkflowByName(e,r){return this.getWorkflowByName(e,r)}insertWorkflowVersion(e,r,n){let o=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,i=this.stmts.insertWorkflowVersion.run(e,o,r,n??null,P());return this.stmts.getWorkflowVersion.get(i.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let o=JSON.parse(n.definition);typeof o.definition_schema_version=="number"&&(s=o.definition_schema_version)}catch{}return this.stmts.updateWorkflowActiveVersionAndDefinition.run(r,n.definition,s,e),this.syncWorkflowTriggers(e,n.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,P()),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,r){return this.stmts.setTriggerCursor.run(r,P(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(P(),r,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,r){let n;try{n=JSON.parse(r)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;let s=n.triggers;if(Array.isArray(s))for(let o of s){if(o===null||typeof o!="object"||Array.isArray(o))continue;let i=o;typeof i.id!="string"||i.id.length===0||typeof i.type!="string"||i.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:i.id,trigger_type:i.type,parameters:JSON.stringify(i.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,P());return this.stmts.getTeam.get(r.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 r=this.stmts.insertTeamMember.run(e.team_id,e.alias,e.role??"agent",e.provider,e.model??null,e.sessionid??null,e.sessiondir,P());return this.stmts.getTeamMember.get(r.lastInsertRowid)}listTeamMembers(e){return this.stmts.listTeamMembers.all(e)}findTeamMemberByAlias(e,r){return this.stmts.findTeamMemberByAlias.get(e,r)??null}updateTeamMemberSession(e,r){return this.stmts.updateTeamMemberSession.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberState(e,r,n){return this.stmts.setMemberState.run(r,n??null,P(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,r){return this.stmts.setMemberPromptSnapshot.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,r){return this.stmts.setMemberProviderResolved.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,r){return this.stmts.setMemberRolePrompt.run(r,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,r){let n=this.stmts.getTeamMember.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"role_prompt"),o=Object.prototype.hasOwnProperty.call(r,"model"),i=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,o?r.model??null:n.model,i?r.provider??n.provider:n.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let r=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,P());return this.stmts.getTeamMemberCompanion.get(r.lastInsertRowid)}insertProject(e){let r=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",P());return this.stmts.getProject.get(r.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,r){return this.stmts.setProjectIntakeConfig.run(r,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,r){let n=this.stmts.getProject.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"local_path"),o=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),i=Object.prototype.hasOwnProperty.call(r,"default_branch"),a=Object.prototype.hasOwnProperty.call(r,"intake_config");return this.stmts.updateProjectSettings.run(s?r.local_path:n.local_path,o?r.durable_memory_mode:n.durable_memory_mode,i?r.default_branch??null:n.default_branch,a?r.intake_config??null:n.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 r=JSON.parse(e.intake_config);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let r=e.condition??null,n=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,r,e.parameters_override??null,e.enabled===!1?0:1,e.priority??100,P());return s.changes===1?this.stmts.getProjectWorkflow.get(s.lastInsertRowid):this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r)}getProjectWorkflow(e){return this.stmts.getProjectWorkflow.get(e)??null}listProjectWorkflows(e,r={}){return r.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,r){return this.stmts.setProjectWorkflowEnabled.run(r?1:0,e),this.getProjectWorkflow(e)}createIssue(e){let r=P(),n=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,r,r);return this.stmts.getIssue.get(n.lastInsertRowid)}getIssue(e){return this.stmts.getIssue.get(e)??null}listIssues(e,r={}){return this.stmts.listIssuesForProject.all(e).filter(n=>!(r.status!==void 0&&!r.status.includes(n.status)||r.severity!==void 0&&!r.severity.includes(n.severity)||r.ai_test_path!==void 0&&n.ai_test_path!==r.ai_test_path))}claimNextIssue(e,r){return this.stmts.claimNextIssue.get(r,P(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,P(),e)??null}closeIssue(e,r,n){let s=P(),o=this.stmts.closeIssue.get(r,n??null,s,s,e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,P(),e);if(n===void 0)throw this.getIssue(e)===null?new Error(`issue not found: ${e}`):new Error(`issue ${e} is not closed`);return n}updateIssue(e,r){let n=this.getIssue(e);if(n===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(r,"labels"),o=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),i=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,o?r.ai_test_path??null:n.ai_test_path,P(),e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=P();return this.stmts.insertWebuiSession.run(e,r,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,r,n,s,o){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,o,P(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}setWebuiSessionChatbot(e,r){if(this.stmts.setWebuiSessionChatbot.run(r,P(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=iv(),s=P();return this.stmts.insertChatbotSession.run(n,e,r??null,s,s,"active"),this.stmts.getChatbotSession.get(n)}getChatbotSession(e){return this.stmts.getChatbotSession.get(e)??null}listChatbotSessions(e){return this.stmts.listChatbotSessionsForUser.all(e)}appendChatbotMessage(e,r,n,s){let o=P(),i=this.stmts.insertChatbotMessage.run(e,r,n,s??null,o);return this.stmts.touchChatbotSession.run(o,e),this.stmts.getChatbotMessage.get(i.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,r){this.stmts.upsertConfig.run(e,r,P())}getConfigAll(){let e=this.stmts.listConfig.all(),r={};for(let n of e)r[n.key]=n.value;return r}enqueueJob(e){let r=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??P(),e.dedupe_key??null,e.concurrency_key??null,P());if(r.changes===1)return this.stmts.getJob.get(r.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 r=P(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=P(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=P(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimByIdWithConcurrencyTxn(e.job_id,e.worker_id,n,r,e.evaluator)}releaseJob(e,r,n){let s=r==="queued"||r==="running"?null:P();return this.stmts.releaseJob.run(r,n??null,s,e),this.getJob(e)}getJob(e){return this.stmts.getJob.get(e)??null}findJobBySourceAndDedupe(e,r){return this.stmts.findJobByDedupe.get(e,r)??null}insertRun(e){let r=this.getWorkflow(e.workflow_id);if(r===null)throw new Error(`workflow not found: ${e.workflow_id}`);let n=this.stmts.insertRun.run(e.job_id,e.workflow_id,e.team_id,e.current_state??null,r.active_version_id,e.parent_run_id??null,P()),s=this.stmts.getRun.get(n.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,r){return this.stmts.setJobRun.run(r,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,P()),this.stmts.getPromptDispatch.get(e.prompt_id)}getPromptDispatch(e){return this.stmts.getPromptDispatch.get(e)??null}setPromptDispatchCompleted(e,r){return this.stmts.setPromptDispatchCompleted.run(r??P(),e),this.getPromptDispatch(e)}getWorkspace(e){return this.stmts.getWorkspace.get(e)??null}ensureWorkspace(e={}){let r=e.id??"default";this.stmts.ensureWorkspace.run(r,e.name??"Default workspace",e.idleThresholdMs??6e5,P());let n=this.getWorkspace(r);if(n===null)throw new Error(`workspace ${r} missing after upsert`);return n}listWebProjectsActive(e){return this.stmts.listWebProjectsActive.all(e)}getWebProject(e){return this.stmts.getWebProject.get(e)??null}insertWebProject(e){let r=P(),n=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,r,r),s=Number(n.lastInsertRowid),o=this.getWebProject(s);if(o===null)throw new Error(`web_project ${s} missing after insert`);return o}updateWebProject(e){let r=this.getWebProject(e.id);return r===null||r.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??r.name,e.config_json===void 0?r.config_json:e.config_json,P(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(P(),e).changes===1}loadMailboxCursor(e,r){return this.stmts.loadMailboxCursor.get(e,r)??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,r,n){return this.stmts.loadUsage.get(e,r,n)??null}sumUsageForPeriod(e,r){let n=this.stmts.sumUsageForPeriod.get(e,r);return{put:n?.put??0,get:n?.get??0,list:n?.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){let r=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.status,e.error_detail,e.truncated,e.created_at);return Number(r.lastInsertRowid)}listTeamChatLog(e){return this.stmts.listTeamChatLog.all(e)}listTeamChatLogSinceId(e,r=500){return this.stmts.listTeamChatLogSinceId.all(e,Math.max(1,Math.trunc(r)))}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)}updateTeamChatLogResponse(e,r){this.stmts.updateTeamChatLogResponse.run(r.response,r.status,r.error_detail,r.truncated,e)}getAgentInflight(e,r){return this.stmts.getAgentInflight.get(e,r)??null}listAgentInflight(){return this.stmts.listAgentInflight.all()}tryAcquireAgentInflight(e,r){return this.tryAcquireAgentInflightTxn(e,r)}clearAgentInflight(e,r){this.stmts.clearAgentInflight.run(e,r)}releaseAgentInflight(e){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(r.active_count<=1)return this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias),this.db.exec("COMMIT"),!0;let n=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),n.changes===1}catch(r){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),r}}clearAgentInflightOlderThan(e){return this.stmts.clearAgentInflightOlderThan.run(e).changes}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,r){return this.stmts.setRunCurrentState.run(r,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,r,n){return this.stmts.setRunPausedState.run(r,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,r){return this.stmts.setRunPendingEscalationDecision.run(r,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,r){return this.stmts.setRunTerminalState.run(r,P(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,r){return this.resumeRunTxn(e,r,P())}insertStep(e){let r=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,P());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,P(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let r=this.stmts.listLatestStepOutcomesByState.all(e),n={};for(let s of r)n[s.state_name]=s.outcome;return n}insertSubmittedPr(e){let r=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??P(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(r.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 r=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,P());return this.stmts.getStepArtifact.get(r.lastInsertRowid)}insertExternalObject(e){let n=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,P()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:n}}insertExternalSignal(e){let r=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,P()),n=r.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(r.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:n}}raiseAttention(e){let r=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,P());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(P(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=P();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,r,r),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,r){return this.stmts.getDurableMemoryByName.get(e,r)??null}deleteDurableMemory(e,r){return this.stmts.deleteDurableMemory.run(e,r).changes>0}listDurableMemory(e,r){return r!==void 0?this.stmts.listDurableMemoryByType.all(e,r):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,r){return r!==void 0&&r.length>0?this.stmts.listDurableMemory.all(e).filter(s=>r.includes(s.type)).map(({name:s,description:o,type:i,updated_at:a})=>({name:s,description:o,type:i,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:o,updated_at:i})=>({name:n,description:s,type:o,updated_at:i}))}recordSessionSize(e){let r=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??P());return this.stmts.getSessionSize.get(r.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,r,n=20){return this.stmts.sessionSizeHistory.all(e,r,n)}insertSessionEvent(e){let r=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(r.lastInsertRowid)}listSessionEvents(e,r){return r!==void 0?this.stmts.listSessionEventsSince.all(e,r):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,r=1e3){return this.stmts.listAllEventsSince.all(e,r)}latestAgentCall(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(r===void 0)return null;try{let n=JSON.parse(r.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,o=0;for(let i of r)try{let a=JSON.parse(i.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),o+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:o}}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 r=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(r.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,r,n){return this.stmts.findUnackedDrift.get(e,r??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let r=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,r,r),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,r){return this.stmts.getInteractiveSessionByRunAndState.get(e,r)??null}setInteractiveAgentOutput(e,r,n){this.stmts.setInteractiveAgentOutput.run(r,n,Date.now(),e)}resumeInteractive(e,r,n){return this.resumeInteractiveTxn(e,r,n,P())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,P())}}});import{realpathSync as dv}from"node:fs";import{resolve as fv}from"node:path";function ml(t){let e=fv(t);try{return dv(e)}catch{return e}}var sm=b(()=>{"use strict"});import{platform as om}from"node:os";function _t(t){let e=new Fn;for(let r of t)e.registerAdapter(r);return e}var Fn,pl=b(()=>{"use strict";sm();Fn=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let r=[],n=e?.provider?this.providers.filter(i=>i.name===e.provider):this.providers,s=await Promise.all(n.map(i=>i.discoverSessions()));for(let i of s)r.push(...i);let o=r;if(e?.workspace){let i=ml(e.workspace);o=o.filter(a=>ml(a.cwd)===i)}if(e?.from){let i=e.from.getTime();o=o.filter(a=>a.modifiedAt.getTime()>=i)}if(e?.to){let i=e.to.getTime();o=o.filter(a=>a.modifiedAt.getTime()<=i)}return o.sort((i,a)=>a.modifiedAt.getTime()-i.modifiedAt.getTime()),e?.limit&&(o=o.slice(0,e.limit)),o}async getSession(e,r){let n=r?this.providers.filter(s=>s.name===r):this.providers;for(let s of n){let o=await s.loadSession(e);if(o)return o}return null}async resolveSession(e,r){let n=await this.resolveSessions(e,r);return n.length===1?n[0]:null}async resolveSessions(e,r){let n=r?this.providers.filter(o=>o.name===r):this.providers,s=[];for(let o of n){let i=await o.resolveSessionPath(e);i&&s.push({provider:o,filePath:i})}return s}getWatchTargets(){let e=om()==="darwin"||om()==="win32",r=[];for(let n of this.providers)if(typeof n.getWatchPaths=="function")for(let s of n.getWatchPaths())r.push({provider:n.name,directory:s.directory,recursive:e,filePattern:s.filePattern});return r}async deleteSession(e,r){let n=await this.resolveSession(e,r);return n?n.provider.deleteSession(e):!1}registerAdapter(e){this.adapters.set(e.name,e),this.providers.push({name:e.name,discoverSessions:()=>e.discover(),loadSession:r=>e.load(r),resolveSessionPath:r=>e.resolvePath(r),deleteSession:r=>e.delete(r),getWatchPaths:()=>e.getWatchPaths?.()??[]})}getAdapter(e){return this.adapters.get(e)}getAllAdapters(){return[...this.adapters.values()]}}});import{createReadStream as im}from"node:fs";import{createInterface as am}from"node:readline";import{stat as mv}from"node:fs/promises";import{homedir as pv}from"node:os";async function*Fe(t){let e=im(t,{encoding:"utf-8"}),r=am({input:e,crlfDelay:1/0});try{for await(let n of r){let s=n.trim();if(s)try{yield JSON.parse(s)}catch{}}}finally{e.destroy()}}async function Le(t,e){let r=[],n=im(t,{encoding:"utf-8"}),s=am({input:n,crlfDelay:1/0});try{for await(let o of s){let i=o.trim();if(i){try{r.push(JSON.parse(i))}catch{}if(r.length>=e)break}}}finally{s.close(),n.destroy()}return r}async function Ne(t){let e=await mv(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function de(t){return t.replace(/\\n/g,`
952
+ `),clearAgentInflightOlderThan:t.prepare("DELETE FROM agent_inflight WHERE started_at < ?")}}function uv(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var dl,Pe=b(()=>{"use strict";cl();Pn();dl=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=cv(e),this.claimTxn=e.transaction((r,n,s)=>{let o=this.stmts.selectClaimableJob.get(s,s,s);return o===void 0||this.stmts.claimJob.run(r,n,s,o.id,s,s,s).changes!==1?null:this.getJob(o.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,o)=>{let i=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of i){let l=this.getJob(a.id);if(l===null)continue;let c=o(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(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,o,i)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=o)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=o,u=a.status==="running"&&a.locked_until!==null&&a.locked_until<o;if(!c&&!u)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let d=i(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,o,a.id)?.count??0)>=Math.max(1,d.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,o,a.id,o,o,o).changes!==1){let p=this.getJob(a.id);return{claimed:!1,reason:p?.locked_until!==null&&p?.locked_until!==void 0&&p.locked_until>=o?"locked":"not_claimable",job_id:r,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:r}:{claimed:!0,job:m}}),this.resumeRunTxn=e.transaction((r,n,s)=>uv("state_not_found")),this.resumeInteractiveTxn=e.transaction((r,n,s,o)=>{let i=this.getInteractiveSessionByStepId(r);if(i===null)return{resumed:!1,reason:"not_found"};if(i.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(i.run_id);if(a===null)return{resumed:!1,reason:"run_not_found"};let l=s?"done":"waiting_agent";return this.stmts.updateInteractiveSession.run(l,n,Date.now(),i.id),this.stmts.resumeRunState.run(i.state_name,a.id),this.stmts.requeuePausedJob.run(o,a.job_id),{resumed:!0,session:this.getInteractiveSessionByStepId(r),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((r,n,s)=>{let o=this.stmts.getAttention.get(r);if(o===void 0)return{resumed:!1,reason:"not_found"};if(o.kind!==Qs)return{resumed:!1,reason:"wrong_kind"};if(o.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(o.run_id===null)return{resumed:!1,reason:"run_not_found"};let i=null,a=[];if(o.payload!==null)try{let u=JSON.parse(o.payload);u.step!==void 0&&typeof u.step.id=="string"&&u.step.id.length>0&&(i=u.step.id),Array.isArray(u.declared_outcomes)&&(a=u.declared_outcomes.filter(d=>typeof d=="string"))}catch{}if(i===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(o.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==Dn&&!a.includes(n))return{resumed:!1,reason:em};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[i]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(i,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,r),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(r,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=n.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...r,holder_pid:process.pid,stale_before:n.stale_before??null,force:n.force===!0?1:0,reclaim_observed_sender_teamfile:s?.sender_teamfile??null,reclaim_observed_sender_alias:s?.sender_alias??null,reclaim_observed_started_at:s?.started_at??null,reclaim_observed_holder_pid:typeof s?.holder_pid=="number"?s.holder_pid:null}),i=o!==void 0?{acquired:!0,current:o}:{acquired:!1,current:this.getAgentInflight(r.receiver_teamfile,r.receiver_alias)??(()=>{throw new Error("agent_inflight conflict row disappeared during acquire")})()};return this.db.exec("COMMIT"),i}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}}close(){this.db.close()}query(e,...r){let n=e.trim().toLowerCase();if(!n.startsWith("select")&&!n.startsWith("with")&&!n.startsWith("pragma"))throw new Error("Dal.query only allows read-only SELECT/WITH/PRAGMA statements");return this.db.prepare(e).all(...r)}insertWorkflow(e){rm(e.name,e.definition,i=>this.getWorkflowByName(i));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,P()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,P());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,n.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,n.id);let o=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),o}upsertWorkflow(e){rm(e.name,e.definition,i=>this.getWorkflowByName(i));let r=this.getWorkflowByName(e.name);if(r===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(r.id)?.version??r.version)+1,o=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,P());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(o.lastInsertRowid),e.definition,e.definition_schema_version??r.definition_schema_version,s,r.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,r.id),this.syncWorkflowTriggers(r.id,e.definition),this.getWorkflow(r.id)}insertCompositionUnit(e){this.stmts.insertCompositionUnit.run(e.name,e.version,e.lang,e.source,e.source_sha,e.compiled_workflow_version_id,P())}getWorkflow(e){return this.stmts.getWorkflow.get(e)??null}getWorkflowByName(e,r){return(r===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,r))??null}findWorkflowByName(e,r){return this.getWorkflowByName(e,r)}insertWorkflowVersion(e,r,n){let o=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,i=this.stmts.insertWorkflowVersion.run(e,o,r,n??null,P());return this.stmts.getWorkflowVersion.get(i.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let o=JSON.parse(n.definition);typeof o.definition_schema_version=="number"&&(s=o.definition_schema_version)}catch{}return this.stmts.updateWorkflowActiveVersionAndDefinition.run(r,n.definition,s,e),this.syncWorkflowTriggers(e,n.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,P()),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,r){return this.stmts.setTriggerCursor.run(r,P(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(P(),r,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,r){let n;try{n=JSON.parse(r)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;let s=n.triggers;if(Array.isArray(s))for(let o of s){if(o===null||typeof o!="object"||Array.isArray(o))continue;let i=o;typeof i.id!="string"||i.id.length===0||typeof i.type!="string"||i.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:i.id,trigger_type:i.type,parameters:JSON.stringify(i.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,P());return this.stmts.getTeam.get(r.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 r=this.stmts.insertTeamMember.run(e.team_id,e.alias,e.role??"agent",e.provider,e.model??null,e.sessionid??null,e.sessiondir,P());return this.stmts.getTeamMember.get(r.lastInsertRowid)}listTeamMembers(e){return this.stmts.listTeamMembers.all(e)}findTeamMemberByAlias(e,r){return this.stmts.findTeamMemberByAlias.get(e,r)??null}updateTeamMemberSession(e,r){return this.stmts.updateTeamMemberSession.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberState(e,r,n){return this.stmts.setMemberState.run(r,n??null,P(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,r){return this.stmts.setMemberPromptSnapshot.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,r){return this.stmts.setMemberProviderResolved.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,r){return this.stmts.setMemberRolePrompt.run(r,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,r){let n=this.stmts.getTeamMember.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"role_prompt"),o=Object.prototype.hasOwnProperty.call(r,"model"),i=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,o?r.model??null:n.model,i?r.provider??n.provider:n.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let r=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,P());return this.stmts.getTeamMemberCompanion.get(r.lastInsertRowid)}insertProject(e){let r=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",P());return this.stmts.getProject.get(r.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,r){return this.stmts.setProjectIntakeConfig.run(r,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,r){let n=this.stmts.getProject.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"local_path"),o=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),i=Object.prototype.hasOwnProperty.call(r,"default_branch"),a=Object.prototype.hasOwnProperty.call(r,"intake_config");return this.stmts.updateProjectSettings.run(s?r.local_path:n.local_path,o?r.durable_memory_mode:n.durable_memory_mode,i?r.default_branch??null:n.default_branch,a?r.intake_config??null:n.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 r=JSON.parse(e.intake_config);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let r=e.condition??null,n=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,r,e.parameters_override??null,e.enabled===!1?0:1,e.priority??100,P());return s.changes===1?this.stmts.getProjectWorkflow.get(s.lastInsertRowid):this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r)}getProjectWorkflow(e){return this.stmts.getProjectWorkflow.get(e)??null}listProjectWorkflows(e,r={}){return r.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,r){return this.stmts.setProjectWorkflowEnabled.run(r?1:0,e),this.getProjectWorkflow(e)}createIssue(e){let r=P(),n=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,r,r);return this.stmts.getIssue.get(n.lastInsertRowid)}getIssue(e){return this.stmts.getIssue.get(e)??null}listIssues(e,r={}){return this.stmts.listIssuesForProject.all(e).filter(n=>!(r.status!==void 0&&!r.status.includes(n.status)||r.severity!==void 0&&!r.severity.includes(n.severity)||r.ai_test_path!==void 0&&n.ai_test_path!==r.ai_test_path))}claimNextIssue(e,r){return this.stmts.claimNextIssue.get(r,P(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,P(),e)??null}closeIssue(e,r,n){let s=P(),o=this.stmts.closeIssue.get(r,n??null,s,s,e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,P(),e);if(n===void 0)throw this.getIssue(e)===null?new Error(`issue not found: ${e}`):new Error(`issue ${e} is not closed`);return n}updateIssue(e,r){let n=this.getIssue(e);if(n===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(r,"labels"),o=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),i=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,o?r.ai_test_path??null:n.ai_test_path,P(),e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=P();return this.stmts.insertWebuiSession.run(e,r,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,r,n,s,o){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,o,P(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}setWebuiSessionChatbot(e,r){if(this.stmts.setWebuiSessionChatbot.run(r,P(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=iv(),s=P();return this.stmts.insertChatbotSession.run(n,e,r??null,s,s,"active"),this.stmts.getChatbotSession.get(n)}getChatbotSession(e){return this.stmts.getChatbotSession.get(e)??null}listChatbotSessions(e){return this.stmts.listChatbotSessionsForUser.all(e)}appendChatbotMessage(e,r,n,s){let o=P(),i=this.stmts.insertChatbotMessage.run(e,r,n,s??null,o);return this.stmts.touchChatbotSession.run(o,e),this.stmts.getChatbotMessage.get(i.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,r){this.stmts.upsertConfig.run(e,r,P())}getConfigAll(){let e=this.stmts.listConfig.all(),r={};for(let n of e)r[n.key]=n.value;return r}enqueueJob(e){let r=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??P(),e.dedupe_key??null,e.concurrency_key??null,P());if(r.changes===1)return this.stmts.getJob.get(r.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 r=P(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=P(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=P(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimByIdWithConcurrencyTxn(e.job_id,e.worker_id,n,r,e.evaluator)}releaseJob(e,r,n){let s=r==="queued"||r==="running"?null:P();return this.stmts.releaseJob.run(r,n??null,s,e),this.getJob(e)}getJob(e){return this.stmts.getJob.get(e)??null}findJobBySourceAndDedupe(e,r){return this.stmts.findJobByDedupe.get(e,r)??null}insertRun(e){let r=this.getWorkflow(e.workflow_id);if(r===null)throw new Error(`workflow not found: ${e.workflow_id}`);let n=this.stmts.insertRun.run(e.job_id,e.workflow_id,e.team_id,e.current_state??null,r.active_version_id,e.parent_run_id??null,P()),s=this.stmts.getRun.get(n.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,r){return this.stmts.setJobRun.run(r,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,P()),this.stmts.getPromptDispatch.get(e.prompt_id)}getPromptDispatch(e){return this.stmts.getPromptDispatch.get(e)??null}setPromptDispatchCompleted(e,r){return this.stmts.setPromptDispatchCompleted.run(r??P(),e),this.getPromptDispatch(e)}getWorkspace(e){return this.stmts.getWorkspace.get(e)??null}ensureWorkspace(e={}){let r=e.id??"default";this.stmts.ensureWorkspace.run(r,e.name??"Default workspace",e.idleThresholdMs??6e5,P());let n=this.getWorkspace(r);if(n===null)throw new Error(`workspace ${r} missing after upsert`);return n}listWebProjectsActive(e){return this.stmts.listWebProjectsActive.all(e)}getWebProject(e){return this.stmts.getWebProject.get(e)??null}insertWebProject(e){let r=P(),n=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,r,r),s=Number(n.lastInsertRowid),o=this.getWebProject(s);if(o===null)throw new Error(`web_project ${s} missing after insert`);return o}updateWebProject(e){let r=this.getWebProject(e.id);return r===null||r.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??r.name,e.config_json===void 0?r.config_json:e.config_json,P(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(P(),e).changes===1}loadMailboxCursor(e,r){return this.stmts.loadMailboxCursor.get(e,r)??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,r,n){return this.stmts.loadUsage.get(e,r,n)??null}sumUsageForPeriod(e,r){let n=this.stmts.sumUsageForPeriod.get(e,r);return{put:n?.put??0,get:n?.get??0,list:n?.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){let r=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.status,e.error_detail,e.truncated,e.created_at);return Number(r.lastInsertRowid)}listTeamChatLog(e){return this.stmts.listTeamChatLog.all(e)}listTeamChatLogSinceId(e,r=500){return this.stmts.listTeamChatLogSinceId.all(e,Math.max(1,Math.trunc(r)))}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)}updateTeamChatLogResponse(e,r){this.stmts.updateTeamChatLogResponse.run(r.response,r.status,r.error_detail,r.truncated,e)}getAgentInflight(e,r){return this.stmts.getAgentInflight.get(e,r)??null}listAgentInflight(){return this.stmts.listAgentInflight.all()}tryAcquireAgentInflight(e,r){return this.tryAcquireAgentInflightTxn(e,r)}clearAgentInflight(e,r){this.stmts.clearAgentInflight.run(e,r)}releaseAgentInflight(e){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(r.active_count<=1)return this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias),this.db.exec("COMMIT"),!0;let n=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),n.changes===1}catch(r){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),r}}clearAgentInflightOlderThan(e){return this.stmts.clearAgentInflightOlderThan.run(e).changes}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,r){return this.stmts.setRunCurrentState.run(r,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,r,n){return this.stmts.setRunPausedState.run(r,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,r){return this.stmts.setRunPendingEscalationDecision.run(r,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,r){return this.stmts.setRunTerminalState.run(r,P(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,r){return this.resumeRunTxn(e,r,P())}insertStep(e){let r=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,P());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,P(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let r=this.stmts.listLatestStepOutcomesByState.all(e),n={};for(let s of r)n[s.state_name]=s.outcome;return n}insertSubmittedPr(e){let r=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??P(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(r.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 r=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,P());return this.stmts.getStepArtifact.get(r.lastInsertRowid)}insertExternalObject(e){let n=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,P()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:n}}insertExternalSignal(e){let r=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,P()),n=r.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(r.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:n}}raiseAttention(e){let r=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,P());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(P(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=P();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,r,r),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,r){return this.stmts.getDurableMemoryByName.get(e,r)??null}deleteDurableMemory(e,r){return this.stmts.deleteDurableMemory.run(e,r).changes>0}listDurableMemory(e,r){return r!==void 0?this.stmts.listDurableMemoryByType.all(e,r):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,r){return r!==void 0&&r.length>0?this.stmts.listDurableMemory.all(e).filter(s=>r.includes(s.type)).map(({name:s,description:o,type:i,updated_at:a})=>({name:s,description:o,type:i,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:o,updated_at:i})=>({name:n,description:s,type:o,updated_at:i}))}recordSessionSize(e){let r=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??P());return this.stmts.getSessionSize.get(r.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,r,n=20){return this.stmts.sessionSizeHistory.all(e,r,n)}insertSessionEvent(e){let r=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(r.lastInsertRowid)}listSessionEvents(e,r){return r!==void 0?this.stmts.listSessionEventsSince.all(e,r):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,r=1e3){return this.stmts.listAllEventsSince.all(e,r)}latestAgentCall(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(r===void 0)return null;try{let n=JSON.parse(r.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,o=0;for(let i of r)try{let a=JSON.parse(i.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),o+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:o}}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 r=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(r.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,r,n){return this.stmts.findUnackedDrift.get(e,r??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let r=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,r,r),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,r){return this.stmts.getInteractiveSessionByRunAndState.get(e,r)??null}setInteractiveAgentOutput(e,r,n){this.stmts.setInteractiveAgentOutput.run(r,n,Date.now(),e)}resumeInteractive(e,r,n){return this.resumeInteractiveTxn(e,r,n,P())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,P())}}});import{realpathSync as dv}from"node:fs";import{resolve as fv}from"node:path";function ml(t){let e=fv(t);try{return dv(e)}catch{return e}}var sm=b(()=>{"use strict"});import{platform as om}from"node:os";function _t(t){let e=new Fn;for(let r of t)e.registerAdapter(r);return e}var Fn,pl=b(()=>{"use strict";sm();Fn=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let r=[],n=e?.provider?this.providers.filter(i=>i.name===e.provider):this.providers,s=await Promise.all(n.map(i=>i.discoverSessions()));for(let i of s)r.push(...i);let o=r;if(e?.workspace){let i=ml(e.workspace);o=o.filter(a=>ml(a.cwd)===i)}if(e?.from){let i=e.from.getTime();o=o.filter(a=>a.modifiedAt.getTime()>=i)}if(e?.to){let i=e.to.getTime();o=o.filter(a=>a.modifiedAt.getTime()<=i)}return o.sort((i,a)=>a.modifiedAt.getTime()-i.modifiedAt.getTime()),e?.limit&&(o=o.slice(0,e.limit)),o}async getSession(e,r){let n=r?this.providers.filter(s=>s.name===r):this.providers;for(let s of n){let o=await s.loadSession(e);if(o)return o}return null}async resolveSession(e,r){let n=await this.resolveSessions(e,r);return n.length===1?n[0]:null}async resolveSessions(e,r){let n=r?this.providers.filter(o=>o.name===r):this.providers,s=[];for(let o of n){let i=await o.resolveSessionPath(e);i&&s.push({provider:o,filePath:i})}return s}getWatchTargets(){let e=om()==="darwin"||om()==="win32",r=[];for(let n of this.providers)if(typeof n.getWatchPaths=="function")for(let s of n.getWatchPaths())r.push({provider:n.name,directory:s.directory,recursive:e,filePattern:s.filePattern});return r}async deleteSession(e,r){let n=await this.resolveSession(e,r);return n?n.provider.deleteSession(e):!1}registerAdapter(e){this.adapters.set(e.name,e),this.providers.push({name:e.name,discoverSessions:()=>e.discover(),loadSession:r=>e.load(r),resolveSessionPath:r=>e.resolvePath(r),deleteSession:r=>e.delete(r),getWatchPaths:()=>e.getWatchPaths?.()??[]})}getAdapter(e){return this.adapters.get(e)}getAllAdapters(){return[...this.adapters.values()]}}});import{createReadStream as im}from"node:fs";import{createInterface as am}from"node:readline";import{stat as mv}from"node:fs/promises";import{homedir as pv}from"node:os";async function*Fe(t){let e=im(t,{encoding:"utf-8"}),r=am({input:e,crlfDelay:1/0});try{for await(let n of r){let s=n.trim();if(s)try{yield JSON.parse(s)}catch{}}}finally{e.destroy()}}async function Le(t,e){let r=[],n=im(t,{encoding:"utf-8"}),s=am({input:n,crlfDelay:1/0});try{for await(let o of s){let i=o.trim();if(i){try{r.push(JSON.parse(i))}catch{}if(r.length>=e)break}}}finally{s.close(),n.destroy()}return r}async function Ne(t){let e=await mv(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function de(t){return t.replace(/\\n/g,`
965
953
  `).replace(/\\t/g," ").replace(/\\r/g,"\r")}function V(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}var Te,Jt=b(()=>{"use strict";Te=pv()});import{readdir as eo,stat as lm,unlink as hv}from"node:fs/promises";import{join as Wr,basename as cm}from"node:path";function _v(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function gv(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return de(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 um(t){let e=0,r=0,n=0,s=0,o=0,i=0,a;for await(let l of Fe(t))if(!l.isSidechain){if(l.type==="user"&&!l.isMeta&&l.message){let c=l.message.content;if(typeof c=="string"){if(c.includes("<command-name>")||c.includes("<local-command-"))continue;e++}}else if(l.type==="assistant"&&l.message){let c=l.message.content;if(Array.isArray(c))for(let d of c)d.type==="text"&&e++;let u=l.message.usage;if(u){let d=u.input_tokens||0,f=u.cache_creation_input_tokens||0,m=u.cache_read_input_tokens||0,p=u.output_tokens||0;r+=d+f+m,n+=m,s+=f,o+=p;let h=d+f+m;h&&(i=h),a={inputTokens:d,cacheWriteInputTokens:f,cachedInputTokens:m,outputTokens:p}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:o,lastInputTokens:i,lastTokenUsage:a}}var to,dm=b(()=>{"use strict";Jt();to=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||Wr(Te,".claude"),this.projectsDir=Wr(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await eo(this.projectsDir)}catch{return e}for(let n of r){let s=Wr(this.projectsDir,n);if(!(await lm(s).catch(()=>null))?.isDirectory())continue;let i;try{i=await eo(s)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let l=cm(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=Wr(s,a);try{let u=await this.extractSummary(c,l);u&&e.push(u)}catch{}}}return e}async extractSummary(e,r){let n=await Le(e,50),s=await Ne(e),o="",i,a,l,c,u,d;for(let m of n)if(!_v(m.type)&&(!o&&m.cwd&&(o=m.cwd),!i&&m.slug&&(i=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=V(p.trim(),80)),u=V(p.trim(),80)}}if(!o)return null;let f=await um(e);return{provider:"claude",sessionId:r,slug:i,cwd:o,createdAt:d||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,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 r=await this.resolveSessionFile(e);if(!r)return null;let n=await Ne(r),s=[],o="",i,a,l,c,u,d,f,m=e;for await(let h of Fe(r))if(h.type!=="file-history-snapshot"&&!h.isSidechain){if(!o&&h.cwd&&(o=h.cwd),!i&&h.slug&&(i=h.slug),!a&&h.version&&(a=h.version),!c&&h.gitBranch&&(c=h.gitBranch),!f&&h.timestamp&&(f=new Date(h.timestamp)),h.sessionId&&(m=h.sessionId),h.type==="system"||h.type==="progress"||h.type==="queue-operation"){s.push({role:"system",timestamp:new Date(h.timestamp||0),content:gv(h)});continue}if(h.type==="user"&&h.message){if(h.isMeta)continue;let g=new Date(h.timestamp||0),_=h.message.content;if(typeof _=="string"){if(_.includes("<command-name>")||_.includes("<local-command-"))continue;u||(u=V(_.trim(),80)),d=V(_.trim(),80),s.push({role:"user",timestamp:g,content:de(_.trim())})}else if(Array.isArray(_)){for(let T of _)if(T.type==="tool_result"){let E=typeof T.content=="string"?de(T.content):JSON.stringify(T.content);s.push({role:"tool_result",timestamp:g,content:E,toolCallId:T.tool_use_id})}}}if(h.type==="assistant"&&h.message){h.message.model&&(l=h.message.model);let g=new Date(h.timestamp||0),_=h.message.content;if(Array.isArray(_))for(let T of _)T.type==="text"&&T.text?s.push({role:"assistant",timestamp:g,content:de(T.text),model:h.message.model}):T.type==="tool_use"?s.push({role:"tool_use",timestamp:g,content:T.name||"unknown tool",toolName:T.name,toolInput:JSON.stringify(T.input,null,2),toolCallId:T.id,model:h.message.model}):T.type==="thinking"&&T.thinking&&s.push({role:"thinking",timestamp:g,content:T.thinking})}}if(!o)return null;let p=await um(r);return{provider:"claude",sessionId:m,slug:i,cwd:o,createdAt:f||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,firstUserMessage:u,lastUserMessage:d,messageCount:p.messageCount,filePath:r,totalInputTokens:p.totalInputTokens||void 0,totalCachedInputTokens:p.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:p.totalCacheWriteInputTokens||void 0,totalOutputTokens:p.totalOutputTokens||void 0,lastInputTokens:p.lastInputTokens||void 0,lastTokenUsage:p.lastTokenUsage,messages:s}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await hv(r),!0):!1}async resolveSessionFile(e){let r;try{r=await eo(this.projectsDir)}catch{return null}let n=[];for(let i of r){let a=Wr(this.projectsDir,i);if(!(await lm(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await eo(a)}catch{continue}for(let u of c){if(!u.endsWith(".jsonl"))continue;let d=cm(u,".jsonl");/^[0-9a-f]{8}-/.test(d)&&n.push({filePath:Wr(a,u),fileSessionId:d})}}let s=n.find(i=>i.fileSessionId===e);if(s)return s.filePath;let o=n.filter(i=>i.fileSessionId.startsWith(e));if(o.length===1)return o[0].filePath;for(let i of n){let a=await Le(i.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return i.filePath}return null}}});function ro(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function yv(t,e,r){if(!r)return"";let n=t.tools[e]??hl[e],s=n?.profiles?.[r]?.flags??hl[e]?.profiles?.[r]?.flags;if(s!==void 0)return s.trim();if(n?.profile_flag)return n.profile_flag.replace(/\{\{profile\}\}/g,r).trim();throw new Error(`Profile "${r}" is not configured for tool "${e}"`)}function fm(t,e){return!!t.tools[e]}function mm(t,e,r,n,s){let o=t.tools[e]??hl[e],i;if(o?.agent){let l=ro(n);i=o.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=wv[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(u=>u.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,n));if(l.mode==="stdin"){let u=c.map(ro).join(" ");i=`printf '%s\\n' ${ro(n)} | ${u}`}else i=c.map(ro).join(" ")}let a=yv(t,e,s);return a&&(i+=" "+a),i}var hl,wv,pm=b(()=>{"use strict";hl={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:""}}}},wv={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"]}}});function hm(t=process.env){let e=t.LMCTL_ONE_SHOT_TIMEOUT_MS;if(!e)return 6e5;let r=Number(e);return!Number.isFinite(r)||r<=0?6e5:r}var _m=b(()=>{"use strict"});var Ev,xe,no,Nt=b(()=>{"use strict";Ev="ACK: waiting for explicit lmctl task.",xe=`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: ${Ev}`,no=`send this exact lmctl seed instruction: "${xe}"`});function Ke(t,e){return e===void 0||e.length===0?t:{...t??process.env,[_l]:e}}var _l,Xt=b(()=>{"use strict";_l="LMCTL_SELF_SESSIONID"});import{spawn as gm}from"node:child_process";import{mkdirSync as bv}from"node:fs";var gl,Oe,Gt=b(()=>{"use strict";pm();_m();Nt();Xt();gl=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},Oe=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 r=e?.prompt;return r===void 0?this.seedArgs:this.seedArgs.map(n=>n===xe?r:n)}seed(e,r){return bv(e,{recursive:!0}),new Promise(n=>{let s;try{s=gm(this.binary,this.seedArgsFor(r),{cwd:e,stdio:["pipe","pipe","pipe"],timeout:6e4})}catch(a){return n({success:!1,error:a instanceof Error?a.message:String(a)})}let o="";s.stderr?.on("data",a=>{o+=a.toString()});let i=r?.prompt!==void 0&&this.seedStdin!==void 0?`${r.prompt}
966
954
  `:this.seedStdin;i&&s.stdin?.write(i),s.stdin?.end(),s.on("exit",a=>{n(a===0||a===null?{success:!0}:{success:!1,error:o.trim().slice(0,200)||`exit code ${a}`})}),s.on("error",a=>{n({success:!1,error:a.message})})})}resumeCommand(e,r){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,e)}startCommand(e){return this.startTemplate}manualSeedHint(e){return{launchCommand:`cd ${e} && ${this.binary}`,postLaunchNote:no,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,r){if(r.userConfig&&fm(r.userConfig,this.name)){let s=r.userConfig.tools[this.name];if(s?.agent)return this.runOneShotAgent(e,r,s.agent)}let n=r.timeoutMs??t.DEFAULT_IDLE_TIMEOUT_MS;return n<=0&&!r.signal?this.transportFn(e,{...r,binary:this.binary}):this.withTimeouts(n,e,r)}withTimeouts(e,r,n){let s=new AbortController,o,i,a="",l,c=()=>{e<=0||(clearTimeout(o),o=setTimeout(()=>{n.onIdleWarning?.(e),u(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},u=()=>{clearTimeout(o)};n.signal&&(n.signal.aborted?(i="external",s.abort()):n.signal.addEventListener("abort",()=>{i="external",s.abort()},{once:!0})),c();let d={...n,binary:this.binary,signal:s.signal,onDelta:p=>{a+=p,c(),n.onDelta?.(p)},onProgress:p=>{p.kind!=="api_retry"&&c(),n.onProgress?.(p)}},f=this.transportFn(r,d).then(p=>(u(),{...p,status:"ok"})).catch(p=>{throw u(),i==="external"?new gl("Turn cancelled","external"):p}),m=new Promise(p=>{l=p});return Promise.race([f,m])}runOneShotAgent(e,r,n){let s=mm(r.userConfig,this.name,r.sessionId,e,r.profile),o=Date.now();return new Promise((i,a)=>{let l=hm(r.env),c=gm(s,{shell:!0,cwd:r.cwd,env:Ke(r.env,r.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 g=h.toString();m+=g,r.onDelta?.(g)}),c.stderr?.on("data",h=>{p+=h.toString()}),r.signal){if(r.signal.aborted)return clearTimeout(f),c.kill(),a(new Error("Aborted"));r.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",h=>{if(u)return;u=!0,clearTimeout(f);let g=Date.now()-o;d?a(new Error(`Agent command timed out after ${l}ms`)):h===0||h===null?i({text:m.trim(),sessionId:r.sessionId,durationMs:g}):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 oo(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new $t(t,r,e)}var Ye,ye,xt,so,$t,Br=b(()=>{"use strict";Ye=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},ye=class extends Ye{},xt=class extends Ye{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},so=class extends Ye{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},$t=class extends Ye{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as yl from"node:child_process";function Tv(t){if(typeof yl.spawnSync=="function")try{yl.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function wm(t){return t.exitCode!==null||t.signalCode!==null}function wl(t,e){return wm(t)?Promise.resolve(!0):new Promise(r=>{let n=!1,s=()=>{n||(n=!0,clearTimeout(o),r(!0))},o=setTimeout(()=>{n||(n=!0,t.removeListener("exit",s),r(!1))},e);t.once("exit",s)})}async function it(t,e={}){let r=Date.now(),n=e.stdinEnd!==!1,s=e.softDelayMs??5e3,o=e.killDelayMs??5e3,i=e.platform??process.platform,a=e.runTaskkill??Tv;if(wm(t))return{signal:"natural",elapsedMs:Date.now()-r};if(n&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await wl(t,s))return{signal:"stdin",elapsedMs:Date.now()-r};if(i==="win32"&&typeof t.pid=="number")a(t.pid);else try{t.kill("SIGTERM")}catch{}if(await wl(t,o))return{signal:"SIGTERM",elapsedMs:Date.now()-r};if(i!=="win32")try{t.kill("SIGKILL")}catch{}return await wl(t,Sv)?{signal:"SIGKILL",elapsedMs:Date.now()-r}:{signal:"abandoned",elapsedMs:Date.now()-r}}var Sv,io=b(()=>{"use strict";Sv=1e3});function ym(t){Se()&&process.stderr.write(`[debug] ${t}
967
955
  `)}function qr(t,e){let r=vv[t];if(r)return r[e]??r.yolo}function Nv(t,e){if(e.length===0)return!0;for(let r=0;r+e.length<=t.length;r++){let n=!0;for(let s=0;s<e.length;s++)if(t[r+s]!==e[s]){n=!1;break}if(n)return!0}return!1}function Vt(t,e,r="yolo"){if(Iv.has(t)){ym(`YOLO ${t} [mode=${r}]: ${t==="codex"?`JSON-RPC params (approvalPolicy=never, sandbox=${r==="plan"?"read-only":"danger-full-access"})`:t==="opencode"?".opencode/opencode.json (permission=allow)":"protocol/config (out-of-band)"} \u2014 no argv flag`);return}let n=r==="plan"?qr(t,"plan"):kv[t];if(!n){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 Z({event:"yolo_assert_failed",provider:t,reason:"unconfigured_provider",args:e.join(" "),message:s}),new ye(s)}if(!Nv(e,n)){let s=n.join(" "),o=`${t} spawn missing YOLO flag '${s}' \u2014 YOLO is mandatory for every provider; see src/providers/yolo-contract.ts. Got argv: [${e.map(i=>JSON.stringify(i)).join(", ")}]`;throw Z({event:"yolo_assert_failed",provider:t,reason:"flag_missing",required_flag:s,mode:r,args:e.join(" "),message:o}),new ye(o)}ym(`YOLO ${t} [mode=${r}]: argv flag '${n.join(" ")}'`)}var kv,vv,Iv,Un=b(()=>{"use strict";Br();je();kv={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"]},vv={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"]}};Iv=new Set(["codex","opencode"])});import{spawn as xv}from"node:child_process";import{existsSync as $v}from"node:fs";function Av(t){if(t.length===0)return"";if(t.length===1)return t[0];let e=[];for(let r=0;r<t.length;r++)r===0?e.push(t[r]):e.push(`
@@ -1766,7 +1754,7 @@ ${wb}
1766
1754
  `):e.stdout.write(`${m.text}${m.text.endsWith(`
1767
1755
  `)?"":`
1768
1756
  `}`),m.status==="stalled"?1:0}catch(f){let m=f instanceof Error?f.message:String(f);return o!==null&&await $a(e,{...o,message:r.prompt,response:null,status:o.policy?.outOfPolicy===!0?"out_of_policy":"error",error_detail:o.policy?.outOfPolicy===!0?`${o.policy.reason}; provider error: ${m}`:m}),e.stderr.write(`error: ${m}
1769
- `),1}finally{i!==null&&await r1(e,i)}}function XP(t,e){return t.slice(-e)}function GP(t){let e=[],r="yolo",n,s,o,i,a,l=!1,c,u=!1;for(let h=0;h<t.length;h+=1){let g=t[h];if(g==="--permission-mode"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --permission-mode";if(_!=="plan"&&_!=="yolo")return`--permission-mode must be one of plan|yolo (got "${_}")`;r=_;continue}if(g==="--idle-timeout"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --idle-timeout";let T=Eb(_);if(typeof T=="string")return T;n=T;continue}if(g==="--session"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --session";s=_;continue}if(g==="--provider"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --provider";o=_;continue}if(g==="--from"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --from";i=_;continue}if(g==="--root"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --root";a=_;continue}if(g==="--force"){l=!0;continue}if(g==="--run"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --run";c=_;continue}if(g==="--done"){u=!0;continue}if(g.startsWith("--"))return`unknown flag: ${g}`;e.push(g)}if(c!==void 0)return s!==void 0?"--run is mutually exclusive with --session":o!==void 0?"--run is mutually exclusive with --provider":i!==void 0?"--run is mutually exclusive with --from":a!==void 0?"--run is mutually exclusive with --root":l?"--run is mutually exclusive with --force":e.length===0?"a prompt (answer) is required with --run":e.length>1?`--run takes exactly one positional (the answer); got ${e.length}`:{prompt:e[0],permissionMode:r,runFlag:c,done:u};let d,f,m;if(e.length===0)return"a prompt is required";if(e.length===1){if(s===void 0)return'expected <teamfile>:<alias> "<prompt>" | <teamfile> <alias> "<prompt>" | <sessionid> "<prompt>" | --session <id> "<prompt>"';m=e[0]}else if(e.length===2)d=e[0],m=e[1];else if(e.length===3)d=e[0],f=e[1],m=e[2];else return`too many positionals (${e.length}); expected at most <teamfile> <alias> <prompt>`;if(u)return"--done requires --run";let p={prompt:m,permissionMode:r};return d!==void 0&&(p.target=d),f!==void 0&&(p.alias=f),n!==void 0&&(p.idleTimeoutMs=n),s!==void 0&&(p.sessionFlag=s),o!==void 0&&(p.providerFlag=o),i!==void 0&&(p.fromFlag=i),a!==void 0&&(p.rootFlag=a),l&&(p.force=!0),p}function VP(t,e,r){if(t===void 0)return{teamfile:e,alias:"operator"};let n=js(t);if(n===null)throw new ge("--from must be <teamfile.lmctl>:<alias>");let s=Cr(n.teamfile),o=$s(s,r);if(o.parseErrors.length>0)throw new ge(`--from ${n.teamfile}: ${o.parseErrors.join("; ")}`);let i=_a(o,n.alias);if(i===void 0)throw new ge(`--from alias "${n.alias}" not found in ${n.teamfile}`);return{teamfile:s,alias:i.alias}}async function KP(t,e){return e.explicitRoot!==void 0?Cr(e.explicitRoot):e.operatorOrigin?e.receiverTeamfile:await G(t,r=>fb(r,{sender:e.sender,now:new Date})??e.receiverTeamfile)}async function YP(t,e){return await G(t,r=>ab({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:zP(r,e.sender.teamfile,e.receiverTeamfile)}))}function zP(t,e,r){return{teams:[e,r].map(s=>ZP(s,t))}}function ZP(t,e){let r=$s(t,e),n=St(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function QP(t,e){let r=new Date().toISOString(),n=new Date(Date.now()-Na()).toISOString(),s={receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,started_at:r};return await G(t,o=>{let i=Se(),a=i?o.getAgentInflight(e.receiver_teamfile,e.receiver_alias):null,l=o.tryAcquireAgentInflight(s,{stale_before:n,force:e.force});if(l.acquired){if(i){let c=a===null?null:e.force?"force":a.started_at<n?"stale":null;ot(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:c===null?"acquired":"reclaimed",...c===null?{}:{reclaim_reason:c,holder:xa(a)}}))}return{acquired:!0,lease:l.current??s}}if(!l.acquired&&e1(l.current)){let c=o.tryAcquireAgentInflight(s,{stale_before:n,reclaim_observed:{sender_teamfile:l.current.sender_teamfile,sender_alias:l.current.sender_alias,started_at:l.current.started_at,holder_pid:l.current.holder_pid}});return c.acquired?(i&&ot(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"reclaimed",reclaim_reason:l.current.holder_pid===null?"null-holder":"dead-pid",holder:xa(l.current)})),{acquired:!0,lease:c.current??s}):(i&&ot(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:xa(c.current)})),{acquired:!1,current:c.current})}return i&&ot(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:xa(l.current)})),{acquired:!1,current:l.current}})}function xa(t){return t===null?null:{sender_teamfile:t.sender_teamfile,sender_alias:t.sender_alias,holder_pid:t.holder_pid,started_at:t.started_at}}function e1(t){return t.holder_pid===null?!0:!t1(t.holder_pid)}function t1(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}async function r1(t,e){try{await G(t,r=>{r.releaseAgentInflight(e)})}catch(r){t.stderr.write(`warning: failed to release chat in-flight slot: ${r instanceof Error?r.message:String(r)}
1757
+ `),1}finally{i!==null&&await r1(e,i)}}function XP(t,e){return t.slice(-e)}function GP(t){let e=[],r="yolo",n,s,o,i,a,l=!1,c,u=!1;for(let h=0;h<t.length;h+=1){let g=t[h];if(g==="--permission-mode"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --permission-mode";if(_!=="plan"&&_!=="yolo")return`--permission-mode must be one of plan|yolo (got "${_}")`;r=_;continue}if(g==="--idle-timeout"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --idle-timeout";let T=Eb(_);if(typeof T=="string")return T;n=T;continue}if(g==="--session"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --session";s=_;continue}if(g==="--provider"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --provider";o=_;continue}if(g==="--from"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --from";i=_;continue}if(g==="--root"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --root";a=_;continue}if(g==="--force"){l=!0;continue}if(g==="--run"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --run";c=_;continue}if(g==="--done"){u=!0;continue}if(g.startsWith("--"))return`unknown flag: ${g}`;e.push(g)}if(c!==void 0)return s!==void 0?"--run is mutually exclusive with --session":o!==void 0?"--run is mutually exclusive with --provider":i!==void 0?"--run is mutually exclusive with --from":a!==void 0?"--run is mutually exclusive with --root":l?"--run is mutually exclusive with --force":e.length===0?"a prompt (answer) is required with --run":e.length>1?`--run takes exactly one positional (the answer); got ${e.length}`:{prompt:e[0],permissionMode:r,runFlag:c,done:u};let d,f,m;if(e.length===0)return"a prompt is required";if(e.length===1){if(s===void 0)return'expected <teamfile>:<alias> "<prompt>" | <teamfile> <alias> "<prompt>" | <sessionid> "<prompt>" | --session <id> "<prompt>"';m=e[0]}else if(e.length===2)d=e[0],m=e[1];else if(e.length===3)d=e[0],f=e[1],m=e[2];else return`too many positionals (${e.length}); expected at most <teamfile> <alias> <prompt>`;if(u)return"--done requires --run";let p={prompt:m,permissionMode:r};return d!==void 0&&(p.target=d),f!==void 0&&(p.alias=f),n!==void 0&&(p.idleTimeoutMs=n),s!==void 0&&(p.sessionFlag=s),o!==void 0&&(p.providerFlag=o),i!==void 0&&(p.fromFlag=i),a!==void 0&&(p.rootFlag=a),l&&(p.force=!0),p}function VP(t,e,r){if(t===void 0)return{teamfile:e,alias:"operator"};let n=js(t);if(n===null)throw new ge("--from must be <teamfile.lmctl>:<alias>");let s=Cr(n.teamfile),o=$s(s,r);if(o.parseErrors.length>0)throw new ge(`--from ${n.teamfile}: ${o.parseErrors.join("; ")}`);let i=_a(o,n.alias);if(i===void 0)throw new ge(`--from alias "${n.alias}" not found in ${n.teamfile}`);return{teamfile:s,alias:i.alias}}async function KP(t,e){return e.explicitRoot!==void 0?Cr(e.explicitRoot):e.operatorOrigin?e.receiverTeamfile:await G(t,r=>fb(r,{sender:e.sender,now:new Date})??e.receiverTeamfile)}async function YP(t,e){return await G(t,r=>ab({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:zP(r,e.sender.teamfile,e.receiverTeamfile)}))}function zP(t,e,r){return{teams:[e,r].map(s=>ZP(s,t))}}function ZP(t,e){let r=$s(t,e),n=St(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function QP(t,e){let r=new Date().toISOString(),n=new Date(Date.now()-Na()).toISOString(),s={receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,started_at:r};return await G(t,o=>{let i=Se(),a=i?o.getAgentInflight(e.receiver_teamfile,e.receiver_alias):null,l=o.tryAcquireAgentInflight(s,{stale_before:n,force:e.force});if(l.acquired){if(i){let c=a===null?null:e.force?"force":a.started_at<n?"stale":null;ot(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:c===null?"acquired":"reclaimed",...c===null?{}:{reclaim_reason:c,holder:xa(a)}}))}return{acquired:!0,lease:l.current??s}}if(!l.acquired&&e1(l.current,n)){let c=o.tryAcquireAgentInflight(s,{stale_before:n,reclaim_observed:{sender_teamfile:l.current.sender_teamfile,sender_alias:l.current.sender_alias,started_at:l.current.started_at,holder_pid:l.current.holder_pid}});return c.acquired?(i&&ot(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"reclaimed",reclaim_reason:l.current.holder_pid===null?"null-holder":"dead-pid",holder:xa(l.current)})),{acquired:!0,lease:c.current??s}):(i&&ot(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:xa(c.current)})),{acquired:!1,current:c.current})}return i&&ot(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:xa(l.current)})),{acquired:!1,current:l.current}})}function xa(t){return t===null?null:{sender_teamfile:t.sender_teamfile,sender_alias:t.sender_alias,holder_pid:t.holder_pid,started_at:t.started_at}}function e1(t,e){return t.holder_pid===null?t.started_at<e:!t1(t.holder_pid)}function t1(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}async function r1(t,e){try{await G(t,r=>{r.releaseAgentInflight(e)})}catch(r){t.stderr.write(`warning: failed to release chat in-flight slot: ${r instanceof Error?r.message:String(r)}
1770
1758
  `)}}function n1(t,e){return`${t} is servicing ${e.sender_alias} (${e.sender_teamfile}) since ${e.started_at}`}async function $a(t,e){let r=yb(e.message),n=e.response===null?null:yb(e.response);try{await G(t,s=>{s.insertTeamChatLog({root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,message:r.text,response:n?.text??null,status:e.status,error_detail:e.error_detail,truncated:r.truncated||n?.truncated?1:0,created_at:new Date().toISOString()})})}catch(s){t.stderr.write(`warning: failed to record chat log: ${s instanceof Error?s.message:String(s)}
1771
1759
  `)}}function yb(t){return t.length<=gb?{text:t,truncated:!1}:{text:t.slice(0,gb),truncated:!0}}function Eb(t){if(t==="0")return 0;let e=/^(\d+)([smhd])$/.exec(t);if(e===null)return`invalid --idle-timeout "${t}" (expected <n>(s|m|h|d) or 0)`;let r=Number(e[1]),n=e[2];return r*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function s1(t,e,r){r.kind==="tool_use"?t.stderr.write(`[${e}] tool_use ${r.tool??"tool"}${r.summary?`: ${r.summary}`:""}
1772
1760
  `):r.kind==="tool_result"?t.stderr.write(`[${e}] tool_result${r.status?` ${r.status}`:""}${r.summary?`: ${r.summary}`:""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lmctl-ai/lmctl",
3
- "version": "0.1.51",
3
+ "version": "0.1.52",
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",