@lmctl-ai/lmctl 0.1.202 → 0.1.203
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +6 -5
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1526,7 +1526,8 @@ var bk=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var he=(t,e)=>{f
|
|
|
1526
1526
|
error_detail = ?,
|
|
1527
1527
|
truncated = ?
|
|
1528
1528
|
WHERE id = ?
|
|
1529
|
-
`),...sp(t),...tp(t)}}function aA(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var Ul,ct=E(()=>{"use strict";kl();rp();ip();Nl();dp();nn();me();Ei();Op();us();Ul=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;recvMailboxMessagesTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=oA(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let d=i(l);if(d.concurrency_key!==null&&(l.concurrency_key_resolved!==d.concurrency_key&&this.stmts.setJobConcurrencyKey.run(d.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(d.concurrency_key,s,l.id)?.count??0)>=Math.max(1,d.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,i,o)=>{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>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let d=a.status==="queued"&&a.available_at<=i,c=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!d&&!c)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let u=o(a);if(u.concurrency_key!==null&&(a.concurrency_key_resolved!==u.concurrency_key&&this.stmts.setJobConcurrencyKey.run(u.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(u.concurrency_key,i,a.id)?.count??0)>=Math.max(1,u.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,i,a.id,i,i,i).changes!==1){let p=this.getJob(a.id);return{claimed:!1,reason:p?.locked_until!==null&&p?.locked_until!==void 0&&p.locked_until>=i?"locked":"not_claimable",job_id: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)=>aA("state_not_found")),this.resumeInteractiveTxn=e.transaction((r,n,s,i)=>{let o=this.getInteractiveSessionByStepId(r);if(o===null)return{resumed:!1,reason:"not_found"};if(o.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(o.run_id);if(a===null)return{resumed:!1,reason:"run_not_found"};let l=s?"done":"waiting_agent";return this.stmts.updateInteractiveSession.run(l,n,Date.now(),o.id),this.stmts.resumeRunState.run(o.state_name,a.id),this.stmts.requeuePausedJob.run(i,a.job_id),{resumed:!0,session:this.getInteractiveSessionByStepId(r),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((r,n,s)=>{let i=this.stmts.getAttention.get(r);if(i===void 0)return{resumed:!1,reason:"not_found"};if(i.kind!==Ti)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let c=JSON.parse(i.payload);c.step!==void 0&&typeof c.step.id=="string"&&c.step.id.length>0&&(o=c.step.id),Array.isArray(c.declared_outcomes)&&(a=c.declared_outcomes.filter(u=>typeof u=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==cs&&!a.includes(n))return{resumed:!1,reason:Cp};let d={};if(l.pending_escalation_decision!==null)try{let c=JSON.parse(l.pending_escalation_decision);c!==null&&typeof c=="object"&&!Array.isArray(c)&&(d=c)}catch{d={}}return d[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(d),l.id),this.stmts.resumeRunState.run(o,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=this.getAgentInflight(r.receiver_teamfile,r.receiver_alias),i=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:i?.sender_teamfile??null,reclaim_observed_sender_alias:i?.sender_alias??null,reclaim_observed_started_at:i?.started_at??null,reclaim_observed_holder_pid:typeof i?.holder_pid=="number"?i.holder_pid:null}),a;if(o!==void 0){let l=s===null?null:n.reclaim_reason??(n.force===!0?"force":n.reclaim_observed!==void 0?"dead-pid":"stale"),d=wp(this.db,o,s,l,n.stale_before??null,n.force===!0);a={acquired:!0,current:o,lease_id:d}}else a={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"),a}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}},this.recvMailboxMessagesTxn=e.transaction((r,n)=>{let s=this.stmts.listAllMailboxMessagesForReceiver.all(r,n);for(let i of s)ls(this.db,i,"",$()),this.stmts.deleteMailboxMessage.run(i.id);return 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){jp(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,$()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,$());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 i=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),i}upsertWorkflow(e){jp(e.name,e.definition,o=>this.getWorkflowByName(o));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,i=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,$());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.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,$())}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 i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,r,n??null,$());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let i=JSON.parse(n.definition);typeof i.definition_schema_version=="number"&&(s=i.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,$()),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,$(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run($(),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 i of s){if(i===null||typeof i!="object"||Array.isArray(i))continue;let o=i;typeof o.id!="string"||o.id.length===0||typeof o.type!="string"||o.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,$());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,$());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,$(),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"),i=Object.prototype.hasOwnProperty.call(r,"model"),o=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,i?r.model??null:n.model,o?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,$());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",$());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"),i=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),o=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,i?r.durable_memory_mode:n.durable_memory_mode,o?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,$());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=$(),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,$(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,$(),e)??null}closeIssue(e,r,n){let s=$(),i=this.stmts.closeIssue.get(r,n??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,$(),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"),i=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),o=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,i?r.ai_test_path??null:n.ai_test_path,$(),e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=$();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,i){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,i,$(),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,$(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=Dp(),s=$();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 i=$(),o=this.stmts.insertChatbotMessage.run(e,r,n,s??null,i);return this.stmts.touchChatbotSession.run(i,e),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,r){this.stmts.upsertConfig.run(e,r,$())}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??$(),e.dedupe_key??null,e.concurrency_key??null,$());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=$(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=$(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=$(),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:$();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,$()),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,$()),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??$(),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,$());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=$(),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),i=this.getWebProject(s);if(i===null)throw new Error(`web_project ${s} missing after insert`);return i}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,$(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run($(),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){return this.db.transaction(()=>{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.origin,e.status,e.error_detail,e.truncated,e.created_at),n=Number(r.lastInsertRowid);return gp(this.db,n,e),n})()}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)}startTrackedInvocation(e){return this.db.transaction(()=>this.startTrackedInvocationInner(e))()}startTrackedInvocationInner(e){let r=e.started_at??$(),n=e.holder_host??ms(),s=e.last_heartbeat_at??r,i=this.stmts.insertTrackedInvocation.run(e.kind,e.origin,e.scope_teamfile??null,e.from_identity,e.target_teamfile??null,e.target_alias??null,e.root_teamfile??null,e.cwd??null,Ut(e.command),r,e.holder_pid??null,n,s,Ut(e.meta),e.launch_source??e.kind,e.request_payload??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return Ap(this.db,o),o}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}finishTrackedInvocation(e,r){return this.db.transaction(()=>{let n=r.ended_at??$();if(this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Ut(r.result_summary),Ut(r.error),r.team_chat_log_id??null,Ut(r.meta),n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return Pl(this.db,i),i})()}reclaimTrackedInvocationIfUnchanged(e,r,n){return this.db.transaction(()=>{let s=n.ended_at??$();if(this.stmts.reclaimTrackedInvocationIfUnchanged.run(n.status,s,n.exit_code??null,n.signal??null,Ut(n.result_summary),Ut(n.error),n.team_chat_log_id??null,Ut(n.meta),s,e,r.holder_pid,r.holder_host,r.started_at,r.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return Pl(this.db,o),o})()}heartbeatTrackedInvocation(e,r=$()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(r,e).changes!==1)return null;let s=this.getTrackedInvocation(e);return Rp(this.db,s,r),s})()}updateTrackedInvocationRequestPayload(e,r){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(r,e).changes!==1?null:(Lp(this.db,e,r),this.getTrackedInvocation(e)))()}listClaimableTerminalTrackedInvocations(e){let r=["status IN ('done', 'error', 'busy', 'cancelled')","ended_at IS NOT NULL","notified_by IS NULL"],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));return n.push(s),this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${r.join(" AND ")} ORDER BY ended_at ASC, id ASC LIMIT ?`).all(...n)}claimTrackedInvocationNotification(e,r,n=$()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(r,n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return xp(this.db,i,r,n),i})()}listTrackedInvocations(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile)),e.status!==void 0&&(r.push("status = ?"),n.push(e.status)),e.kind!==void 0&&(r.push("kind = ?"),n.push(e.kind)),e.origin!==void 0&&(r.push("origin = ?"),n.push(e.origin));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));n.push(s);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${i} ORDER BY started_at DESC, id DESC LIMIT ?`).all(...n)}maxTrackedInvocationId(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=r.length===0?"":` WHERE ${r.join(" AND ")}`,i=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...n);return Number(i?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}enqueueMail(e){return this.sendMailboxMessage(e)}sendMailboxMessage(e){return this.db.transaction(()=>{let n=this.stmts.insertMailboxMessage.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile??null,e.sender_alias??null,e.root_teamfile??null,ss(e.payload),e.created_at??$(),e.remote_transport??null,e.remote_message_id??null,e.remote_thread_id??null,e.meta??null,e.message_type??"request",e.reply_mode??"pull",e.request_mailbox_id??null),s=this.getMailboxMessage(Number(n.lastInsertRowid));return Cl(this.db,s,{provider:e.receiver_provider,sessionId:e.receiver_session_id},{provider:e.sender_provider,sessionId:e.sender_session_id}),s})()}listEnqueuedRequestMailFromSender(e,r,n,s){return this.stmts.listEnqueuedRequestMailFromSender.all(e,r,n,s)}listEnqueuedResponseMailFromSender(e,r,n,s){return this.stmts.listEnqueuedResponseMailFromSender.all(e,r,n,s)}listRelayMailboxLanes(e){return this.stmts.listRelayMailboxLanes.all(Math.max(1,Math.trunc(e)))}markMailDelivered(e,r,n){let s=[...new Set(e.map(a=>Math.trunc(a)).filter(a=>Number.isInteger(a)&&a>0))];if(s.length===0)return 0;let i=ss(r),o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0;for(let l of s){let d=this.getMailboxMessage(l),c=this.stmts.markMailboxMessageDelivered.run(n,i,l);a+=c.changes,c.changes===1&&d!==null&&(ls(this.db,d,i,n),o.push(d))}this.db.exec("COMMIT");for(let l of o)dr("mailbox_delivery_delivered",l,{transition:l.delivering_at===null?"pending->delivered":"delivering->delivered",delivered_at:n});return a}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}markRelayRequestDelivered(e,r,n){let s=ss(r),i=[],o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0;for(let l of e){if(this.stmts.markMailboxMessageDeliveredIfUnchanged.run(n,s,l.id,l.delivering_at,l.delivery_holder_pid,l.delivery_holder_host).changes!==1){o.push(l);continue}ls(this.db,l,s,n),a+=1,i.push(l)}this.db.exec("COMMIT");for(let l of i)dr("mailbox_delivery_delivered",l,{transition:"delivering->delivered",delivered_at:n,finalizer:"lease-cas"});for(let l of o)dr("mailbox_delivery_finalize_skipped",l,{delivered_at:n,finalizer:"lease-cas",reason:"observed delivery lease changed before finalization"});return a}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}markRelayRequestDeliveredAndEnqueueResponses(e,r,n){let s=ss(r),i=[],o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0,l=0;for(let m of e){if(this.stmts.markMailboxMessageDeliveredIfUnchanged.run(n,s,m.id,m.delivering_at,m.delivery_holder_pid,m.delivery_holder_host).changes!==1){o.push(m);continue}a+=1,i.push(m)}let d=[...i].sort((m,p)=>m.created_at.localeCompare(p.created_at)||m.id-p.id),c=d.at(-1)??null,u=null;if(c!==null&&c.sender_teamfile!==null&&c.sender_alias!==null){let m=this.stmts.insertMailboxResponseIfAbsent.run(c.sender_teamfile,c.sender_alias,c.receiver_teamfile,c.receiver_alias,c.root_teamfile,s,n,null,null,null,null,c.reply_mode,c.id);if(l=m.changes,m.changes===1&&(u=this.getMailboxMessage(Number(m.lastInsertRowid)),u===null))throw new Error("mailbox response disappeared during event append")}let f=u===null?null:kt(u.id);for(let m of i)ls(this.db,m,s,n,c!==null&&m.id!==c.id?f:null);u!==null&&Cl(this.db,u,{},{},d.map(m=>kt(m.id))),this.db.exec("COMMIT");for(let m of i)dr("mailbox_delivery_delivered",m,{transition:"delivering->delivered",delivered_at:n,finalizer:"lease-cas-with-response"});for(let m of o)dr("mailbox_delivery_finalize_skipped",m,{delivered_at:n,finalizer:"lease-cas-with-response",reason:"observed delivery lease changed before finalization"});return{marked:a,responses:l}}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}claimMailForDelivery(e,r,n=process.pid,s=ms()){let i=[...new Set(e.map(o=>Math.trunc(o)).filter(o=>Number.isInteger(o)&&o>0))];if(i.length===0)return[];this.db.exec("BEGIN IMMEDIATE");try{let o=[];for(let l of i)if(this.stmts.claimMailboxMessageDelivery.run(r,n,s,l).changes===1){let c=this.getMailboxMessage(l);c!==null&&(yp(this.db,c,r,n,s),o.push(c))}this.db.exec("COMMIT");let a=o.map(l=>l.id);for(let l of o)dr("mailbox_delivery_claimed",l,{transition:"pending->delivering",batch_ids:a,delivering_at:r,delivery_holder_pid:n,delivery_holder_host:s});return o}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearMailDelivery(e){let r=[...new Set(e.map(s=>Math.trunc(s)).filter(s=>Number.isInteger(s)&&s>0))];if(r.length===0)return 0;let n=[];this.db.exec("BEGIN IMMEDIATE");try{let s=0;for(let i of r){let o=this.getMailboxMessage(i),a=this.stmts.clearMailboxMessageDelivery.run(i);s+=a.changes,a.changes===1&&o!==null&&o.delivering_at!==null&&(Ml(this.db,o,"explicit-clear"),n.push(o))}this.db.exec("COMMIT");for(let i of n)dr("mailbox_delivery_cleared",i,{transition:"delivering->pending",reason:"explicit non-CAS clear"});return s}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}reclaimMailboxDeliveryIfUnchanged(e,r="delivery-failure"){return this.db.transaction(()=>{let s=this.getMailboxMessage(e.id);if(this.stmts.clearMailboxMessageDeliveryIfUnchanged.run(e.id,e.delivering_at,e.delivery_holder_pid,e.delivery_holder_host).changes!==1)return null;if(s===null)throw new Error("mailbox row disappeared during claim release");return s.delivering_at!==null&&Ml(this.db,s,r),this.getMailboxMessage(e.id)})()}reclaimStaleMailboxDeliveries(e){let r=this.stmts.listInFlightMailboxDeliveries.all(),n=[],s=[];this.db.exec("BEGIN IMMEDIATE");try{for(let i of r){let o=sA(i,e);if(!o.reclaim){s.push({row:i,decision:o,reclaimed:!1});continue}let a=this.reclaimMailboxDeliveryIfUnchanged(i,o.reason),l=a!==null;s.push({row:i,decision:o,reclaimed:l}),l&&n.push(a)}this.db.exec("COMMIT");for(let i of s)dr(i.decision.reclaim?i.reclaimed?"mailbox_delivery_reclaimed":"mailbox_delivery_reclaim_raced":"mailbox_delivery_reclaim_deferred",i.row,{transition:i.reclaimed?"delivering->pending":"delivering->delivering",stale_before:e,reclaim_reason:i.decision.reason,holder_pid_alive:i.decision.holderPidAlive});return n}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}listDeliveredReceiptsForSender(e,r){return this.stmts.listDeliveredReceiptsForSender.all(e,r)}listOutboundPendingForSender(e,r){return this.stmts.listOutboundPendingForSender.all(e,r)}getMailboxMessage(e){return this.stmts.getMailboxMessage.get(e)??null}peekMailboxMessages(e,r=1e3){return this.stmts.listMailboxMessagesForReceiver.all(e.receiver_teamfile,e.receiver_alias,Math.max(1,Math.min(1e3,Math.trunc(r))))}recvMailboxMessages(e){return this.recvMailboxMessagesTxn(e.receiver_teamfile,e.receiver_alias)}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)}heartbeatAgentInflight(e,r,n=$()){return this.db.transaction(()=>{let s=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);return s===null||s.sender_teamfile!==e.sender_teamfile||s.sender_alias!==e.sender_alias||s.started_at!==e.started_at?!1:Tp(this.db,s,r,n)})()}clearAgentInflight(e,r){this.db.transaction(()=>{let s=this.getAgentInflight(e,r);if(s===null)return;this.stmts.clearAgentInflight.run(e,r).changes===1&&ds(this.db,s,"INFLIGHT_RECLAIM","stale")})()}clearObservedTerminalAgentInflight(e,r,n){return this.db.transaction(()=>{let i=this.getAgentInflight(e,r),o=this.stmts.clearObservedTerminalAgentInflight.run({receiver_teamfile:e,receiver_alias:r,observed_sender_teamfile:n.sender_teamfile,observed_sender_alias:n.sender_alias,observed_started_at:n.started_at,observed_holder_pid:n.holder_pid});return o.changes===1&&i!==null&&ds(this.db,i,"INFLIGHT_RELEASE"),o.changes===1})()}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){let s=this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return s.changes===1&&ds(this.db,r,"INFLIGHT_RELEASE"),this.db.exec("COMMIT"),s.changes===1}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.db.transaction(()=>{let n=this.listAgentInflight().filter(i=>i.started_at<e),s=0;for(let i of n)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(ds(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(is,as(e,r),os);return n===void 0?null:lp(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&Dl(this.db,n,!0),this.stmts.upsertRuntimeState.run(is,as(e.teamfile,e.alias),os,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&vp(this.db,e)})()}heartbeatTerminalLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,r);if(i===null||i.lock_id!==n)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(is,as(e,r),os,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,r,n){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,r);if(s===null||s.lock_id!==n)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(is,as(e,r),os);return i.changes===1&&Dl(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,r,n){let s=this.stmts.getRuntimeState.get(e,r,n);return s===void 0?null:rA(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=$()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!nA(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Dp(),holder_pid:process.pid,holder_host:ms(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,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,$(),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,$())}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,$());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,$(),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??$(),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,$());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,$()).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,$()),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,$());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run($(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=$();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:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}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??$());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,i=0;for(let o of r)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let 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,$())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,$())}}});import{realpathSync as lA}from"node:fs";import{resolve as dA}from"node:path";function Wl(t){let e=dA(t);try{return lA(e)}catch{return e}}var Fp=E(()=>{"use strict"});import{platform as Up}from"node:os";function Nt(t){let e=new fs;for(let r of t)e.registerAdapter(r);return e}var fs,ql=E(()=>{"use strict";Fp();fs=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let r=[],n=e?.provider?this.providers.filter(o=>o.name===e.provider):this.providers,s=await Promise.all(n.map(o=>o.discoverSessions()));for(let o of s)r.push(...o);let i=r;if(e?.workspace){let o=Wl(e.workspace);i=i.filter(a=>Wl(a.cwd)===o)}if(e?.from){let o=e.from.getTime();i=i.filter(a=>a.modifiedAt.getTime()>=o)}if(e?.to){let o=e.to.getTime();i=i.filter(a=>a.modifiedAt.getTime()<=o)}return i.sort((o,a)=>a.modifiedAt.getTime()-o.modifiedAt.getTime()),e?.limit&&(i=i.slice(0,e.limit)),i}async getSession(e,r){let n=r?this.providers.filter(s=>s.name===r):this.providers;for(let s of n){let i=await s.loadSession(e);if(i)return i}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(i=>i.name===r):this.providers,s=[];for(let i of n){let o=await i.resolveSessionPath(e);o&&s.push({provider:i,filePath:o})}return s}getWatchTargets(){let e=Up()==="darwin"||Up()==="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 Wp}from"node:fs";import{createInterface as qp}from"node:readline";import{stat as cA}from"node:fs/promises";import{homedir as uA}from"node:os";async function*Ge(t){let e=Wp(t,{encoding:"utf-8"}),r=qp({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 Pe(t,e){let r=[],n=Wp(t,{encoding:"utf-8"}),s=qp({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(o){try{r.push(JSON.parse(o))}catch{}if(r.length>=e)break}}}finally{s.close(),n.destroy()}return r}async function Re(t){let e=await cA(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function pe(t){return t.replace(/\\n/g,`
|
|
1529
|
+
`),...sp(t),...tp(t)}}function aA(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var Ul,ct=E(()=>{"use strict";kl();rp();ip();Nl();dp();nn();me();Ei();Op();us();Ul=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;recvMailboxMessagesTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=oA(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let d=i(l);if(d.concurrency_key!==null&&(l.concurrency_key_resolved!==d.concurrency_key&&this.stmts.setJobConcurrencyKey.run(d.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(d.concurrency_key,s,l.id)?.count??0)>=Math.max(1,d.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,i,o)=>{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>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let d=a.status==="queued"&&a.available_at<=i,c=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!d&&!c)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let u=o(a);if(u.concurrency_key!==null&&(a.concurrency_key_resolved!==u.concurrency_key&&this.stmts.setJobConcurrencyKey.run(u.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(u.concurrency_key,i,a.id)?.count??0)>=Math.max(1,u.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,i,a.id,i,i,i).changes!==1){let p=this.getJob(a.id);return{claimed:!1,reason:p?.locked_until!==null&&p?.locked_until!==void 0&&p.locked_until>=i?"locked":"not_claimable",job_id: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)=>aA("state_not_found")),this.resumeInteractiveTxn=e.transaction((r,n,s,i)=>{let o=this.getInteractiveSessionByStepId(r);if(o===null)return{resumed:!1,reason:"not_found"};if(o.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(o.run_id);if(a===null)return{resumed:!1,reason:"run_not_found"};let l=s?"done":"waiting_agent";return this.stmts.updateInteractiveSession.run(l,n,Date.now(),o.id),this.stmts.resumeRunState.run(o.state_name,a.id),this.stmts.requeuePausedJob.run(i,a.job_id),{resumed:!0,session:this.getInteractiveSessionByStepId(r),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((r,n,s)=>{let i=this.stmts.getAttention.get(r);if(i===void 0)return{resumed:!1,reason:"not_found"};if(i.kind!==Ti)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let c=JSON.parse(i.payload);c.step!==void 0&&typeof c.step.id=="string"&&c.step.id.length>0&&(o=c.step.id),Array.isArray(c.declared_outcomes)&&(a=c.declared_outcomes.filter(u=>typeof u=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==cs&&!a.includes(n))return{resumed:!1,reason:Cp};let d={};if(l.pending_escalation_decision!==null)try{let c=JSON.parse(l.pending_escalation_decision);c!==null&&typeof c=="object"&&!Array.isArray(c)&&(d=c)}catch{d={}}return d[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(d),l.id),this.stmts.resumeRunState.run(o,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=this.getAgentInflight(r.receiver_teamfile,r.receiver_alias),i=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:i?.sender_teamfile??null,reclaim_observed_sender_alias:i?.sender_alias??null,reclaim_observed_started_at:i?.started_at??null,reclaim_observed_holder_pid:typeof i?.holder_pid=="number"?i.holder_pid:null}),a;if(o!==void 0){let l=s===null?null:n.reclaim_reason??(n.force===!0?"force":n.reclaim_observed!==void 0?"dead-pid":"stale"),d=wp(this.db,o,s,l,n.stale_before??null,n.force===!0);a={acquired:!0,current:o,lease_id:d}}else a={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"),a}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}},this.recvMailboxMessagesTxn=e.transaction((r,n)=>{let s=this.stmts.listAllMailboxMessagesForReceiver.all(r,n);for(let i of s)ls(this.db,i,"",$()),this.stmts.deleteMailboxMessage.run(i.id);return 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){jp(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,$()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,$());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 i=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),i}upsertWorkflow(e){jp(e.name,e.definition,o=>this.getWorkflowByName(o));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,i=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,$());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.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,$())}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 i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,r,n??null,$());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let i=JSON.parse(n.definition);typeof i.definition_schema_version=="number"&&(s=i.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,$()),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,$(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run($(),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 i of s){if(i===null||typeof i!="object"||Array.isArray(i))continue;let o=i;typeof o.id!="string"||o.id.length===0||typeof o.type!="string"||o.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,$());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,$());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,$(),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"),i=Object.prototype.hasOwnProperty.call(r,"model"),o=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,i?r.model??null:n.model,o?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,$());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",$());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"),i=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),o=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,i?r.durable_memory_mode:n.durable_memory_mode,o?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,$());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=$(),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,$(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,$(),e)??null}closeIssue(e,r,n){let s=$(),i=this.stmts.closeIssue.get(r,n??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,$(),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"),i=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),o=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,i?r.ai_test_path??null:n.ai_test_path,$(),e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=$();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,i){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,i,$(),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,$(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=Dp(),s=$();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 i=$(),o=this.stmts.insertChatbotMessage.run(e,r,n,s??null,i);return this.stmts.touchChatbotSession.run(i,e),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,r){this.stmts.upsertConfig.run(e,r,$())}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??$(),e.dedupe_key??null,e.concurrency_key??null,$());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=$(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=$(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=$(),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:$();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,$()),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,$()),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??$(),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,$());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=$(),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),i=this.getWebProject(s);if(i===null)throw new Error(`web_project ${s} missing after insert`);return i}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,$(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run($(),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){return this.db.transaction(()=>{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.origin,e.status,e.error_detail,e.truncated,e.created_at),n=Number(r.lastInsertRowid);return gp(this.db,n,e),n})()}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)}startTrackedInvocation(e){return this.db.transaction(()=>this.startTrackedInvocationInner(e))()}startTrackedInvocationInner(e){let r=e.started_at??$(),n=e.holder_host??ms(),s=e.last_heartbeat_at??r,i=this.stmts.insertTrackedInvocation.run(e.kind,e.origin,e.scope_teamfile??null,e.from_identity,e.target_teamfile??null,e.target_alias??null,e.root_teamfile??null,e.cwd??null,Ut(e.command),r,e.holder_pid??null,n,s,Ut(e.meta),e.launch_source??e.kind,e.request_payload??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return Ap(this.db,o),o}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}finishTrackedInvocation(e,r){return this.db.transaction(()=>{let n=r.ended_at??$();if(this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Ut(r.result_summary),Ut(r.error),r.team_chat_log_id??null,Ut(r.meta),n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return Pl(this.db,i),i})()}reclaimTrackedInvocationIfUnchanged(e,r,n){return this.db.transaction(()=>{let s=n.ended_at??$();if(this.stmts.reclaimTrackedInvocationIfUnchanged.run(n.status,s,n.exit_code??null,n.signal??null,Ut(n.result_summary),Ut(n.error),n.team_chat_log_id??null,Ut(n.meta),s,e,r.holder_pid,r.holder_host,r.started_at,r.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return Pl(this.db,o),o})()}heartbeatTrackedInvocation(e,r=$()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(r,e).changes!==1)return null;let s=this.getTrackedInvocation(e);return Rp(this.db,s,r),s})()}updateTrackedInvocationRequestPayload(e,r){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(r,e).changes!==1?null:(Lp(this.db,e,r),this.getTrackedInvocation(e)))()}listClaimableTerminalTrackedInvocations(e){let r=["status IN ('done', 'error', 'busy', 'cancelled')","ended_at IS NOT NULL","notified_by IS NULL"],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));return n.push(s),this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${r.join(" AND ")} ORDER BY ended_at ASC, id ASC LIMIT ?`).all(...n)}claimTrackedInvocationNotification(e,r,n=$()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(r,n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return xp(this.db,i,r,n),i})()}listTrackedInvocations(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile)),e.status!==void 0&&(r.push("status = ?"),n.push(e.status)),e.kind!==void 0&&(r.push("kind = ?"),n.push(e.kind)),e.origin!==void 0&&(r.push("origin = ?"),n.push(e.origin));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));n.push(s);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${i} ORDER BY started_at DESC, id DESC LIMIT ?`).all(...n)}maxTrackedInvocationId(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=r.length===0?"":` WHERE ${r.join(" AND ")}`,i=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...n);return Number(i?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}enqueueMail(e){return this.sendMailboxMessage(e)}sendMailboxMessage(e){return this.db.transaction(()=>{let n=this.stmts.insertMailboxMessage.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile??null,e.sender_alias??null,e.root_teamfile??null,ss(e.payload),e.created_at??$(),e.remote_transport??null,e.remote_message_id??null,e.remote_thread_id??null,e.meta??null,e.message_type??"request",e.reply_mode??"pull",e.request_mailbox_id??null),s=this.getMailboxMessage(Number(n.lastInsertRowid));return Cl(this.db,s,{provider:e.receiver_provider,sessionId:e.receiver_session_id},{provider:e.sender_provider,sessionId:e.sender_session_id}),s})()}listEnqueuedRequestMailFromSender(e,r,n,s){return this.stmts.listEnqueuedRequestMailFromSender.all(e,r,n,s)}listEnqueuedResponseMailFromSender(e,r,n,s){return this.stmts.listEnqueuedResponseMailFromSender.all(e,r,n,s)}listRelayMailboxLanes(e){return this.stmts.listRelayMailboxLanes.all(Math.max(1,Math.trunc(e)))}markMailDelivered(e,r,n){let s=[...new Set(e.map(a=>Math.trunc(a)).filter(a=>Number.isInteger(a)&&a>0))];if(s.length===0)return 0;let i=ss(r),o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0;for(let l of s){let d=this.getMailboxMessage(l),c=this.stmts.markMailboxMessageDelivered.run(n,i,l);a+=c.changes,c.changes===1&&d!==null&&(ls(this.db,d,i,n),o.push(d))}this.db.exec("COMMIT");for(let l of o)dr("mailbox_delivery_delivered",l,{transition:l.delivering_at===null?"pending->delivered":"delivering->delivered",delivered_at:n});return a}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}markRelayRequestDelivered(e,r,n){let s=ss(r),i=[],o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0;for(let l of e){if(this.stmts.markMailboxMessageDeliveredIfUnchanged.run(n,s,l.id,l.delivering_at,l.delivery_holder_pid,l.delivery_holder_host).changes!==1){o.push(l);continue}ls(this.db,l,s,n),a+=1,i.push(l)}this.db.exec("COMMIT");for(let l of i)dr("mailbox_delivery_delivered",l,{transition:"delivering->delivered",delivered_at:n,finalizer:"lease-cas"});for(let l of o)dr("mailbox_delivery_finalize_skipped",l,{delivered_at:n,finalizer:"lease-cas",reason:"observed delivery lease changed before finalization"});return a}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}markRelayRequestDeliveredAndEnqueueResponses(e,r,n){let s=ss(r),i=[],o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0,l=0;for(let m of e){if(this.stmts.markMailboxMessageDeliveredIfUnchanged.run(n,s,m.id,m.delivering_at,m.delivery_holder_pid,m.delivery_holder_host).changes!==1){o.push(m);continue}a+=1,i.push(m)}let d=[...i].sort((m,p)=>m.created_at.localeCompare(p.created_at)||m.id-p.id),c=d.at(-1)??null,u=null;if(c!==null&&c.sender_teamfile!==null&&c.sender_alias!==null){let m=this.stmts.insertMailboxResponseIfAbsent.run(c.sender_teamfile,c.sender_alias,c.receiver_teamfile,c.receiver_alias,c.root_teamfile,s,n,null,null,null,null,c.reply_mode,c.id);if(l=m.changes,m.changes===1&&(u=this.getMailboxMessage(Number(m.lastInsertRowid)),u===null))throw new Error("mailbox response disappeared during event append")}let f=u===null?null:kt(u.id);for(let m of i)ls(this.db,m,s,n,c!==null&&m.id!==c.id?f:null);u!==null&&Cl(this.db,u,{},{},d.map(m=>kt(m.id))),this.db.exec("COMMIT");for(let m of i)dr("mailbox_delivery_delivered",m,{transition:"delivering->delivered",delivered_at:n,finalizer:"lease-cas-with-response"});for(let m of o)dr("mailbox_delivery_finalize_skipped",m,{delivered_at:n,finalizer:"lease-cas-with-response",reason:"observed delivery lease changed before finalization"});return{marked:a,responses:l}}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}claimMailForDelivery(e,r,n=process.pid,s=ms()){let i=[...new Set(e.map(o=>Math.trunc(o)).filter(o=>Number.isInteger(o)&&o>0))];if(i.length===0)return[];this.db.exec("BEGIN IMMEDIATE");try{let o=[];for(let l of i)if(this.stmts.claimMailboxMessageDelivery.run(r,n,s,l).changes===1){let c=this.getMailboxMessage(l);c!==null&&(yp(this.db,c,r,n,s),o.push(c))}this.db.exec("COMMIT");let a=o.map(l=>l.id);for(let l of o)dr("mailbox_delivery_claimed",l,{transition:"pending->delivering",batch_ids:a,delivering_at:r,delivery_holder_pid:n,delivery_holder_host:s});return o}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearMailDelivery(e){let r=[...new Set(e.map(s=>Math.trunc(s)).filter(s=>Number.isInteger(s)&&s>0))];if(r.length===0)return 0;let n=[];this.db.exec("BEGIN IMMEDIATE");try{let s=0;for(let i of r){let o=this.getMailboxMessage(i),a=this.stmts.clearMailboxMessageDelivery.run(i);s+=a.changes,a.changes===1&&o!==null&&o.delivering_at!==null&&(Ml(this.db,o,"explicit-clear"),n.push(o))}this.db.exec("COMMIT");for(let i of n)dr("mailbox_delivery_cleared",i,{transition:"delivering->pending",reason:"explicit non-CAS clear"});return s}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}reclaimMailboxDeliveryIfUnchanged(e,r="delivery-failure"){return this.db.transaction(()=>{let s=this.getMailboxMessage(e.id);if(this.stmts.clearMailboxMessageDeliveryIfUnchanged.run(e.id,e.delivering_at,e.delivery_holder_pid,e.delivery_holder_host).changes!==1)return null;if(s===null)throw new Error("mailbox row disappeared during claim release");return s.delivering_at!==null&&Ml(this.db,s,r),this.getMailboxMessage(e.id)})()}reclaimStaleMailboxDeliveries(e){let r=this.stmts.listInFlightMailboxDeliveries.all(),n=[],s=[];this.db.exec("BEGIN IMMEDIATE");try{for(let i of r){let o=sA(i,e);if(!o.reclaim){s.push({row:i,decision:o,reclaimed:!1});continue}let a=this.reclaimMailboxDeliveryIfUnchanged(i,o.reason),l=a!==null;s.push({row:i,decision:o,reclaimed:l}),l&&n.push(a)}this.db.exec("COMMIT");for(let i of s)dr(i.decision.reclaim?i.reclaimed?"mailbox_delivery_reclaimed":"mailbox_delivery_reclaim_raced":"mailbox_delivery_reclaim_deferred",i.row,{transition:i.reclaimed?"delivering->pending":"delivering->delivering",stale_before:e,reclaim_reason:i.decision.reason,holder_pid_alive:i.decision.holderPidAlive});return n}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}listDeliveredReceiptsForSender(e,r){return this.stmts.listDeliveredReceiptsForSender.all(e,r)}listOutboundPendingForSender(e,r){return this.stmts.listOutboundPendingForSender.all(e,r)}getMailboxMessage(e){return this.stmts.getMailboxMessage.get(e)??null}peekMailboxMessages(e,r=1e3){return this.stmts.listMailboxMessagesForReceiver.all(e.receiver_teamfile,e.receiver_alias,Math.max(1,Math.min(1e3,Math.trunc(r))))}recvMailboxMessages(e){return this.recvMailboxMessagesTxn(e.receiver_teamfile,e.receiver_alias)}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)}heartbeatAgentInflight(e,r,n=$()){return this.db.transaction(()=>{let s=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);return s===null||s.sender_teamfile!==e.sender_teamfile||s.sender_alias!==e.sender_alias||s.started_at!==e.started_at?!1:Tp(this.db,s,r,n)})()}clearAgentInflight(e,r){this.db.transaction(()=>{let s=this.getAgentInflight(e,r);if(s===null)return;this.stmts.clearAgentInflight.run(e,r).changes===1&&ds(this.db,s,"INFLIGHT_RECLAIM","stale")})()}clearObservedTerminalAgentInflight(e,r,n){return this.db.transaction(()=>{let i=this.getAgentInflight(e,r),o=this.stmts.clearObservedTerminalAgentInflight.run({receiver_teamfile:e,receiver_alias:r,observed_sender_teamfile:n.sender_teamfile,observed_sender_alias:n.sender_alias,observed_started_at:n.started_at,observed_holder_pid:n.holder_pid});return o.changes===1&&i!==null&&ds(this.db,i,"INFLIGHT_RELEASE"),o.changes===1})()}releaseAgentInflight(e,r){this.db.exec("BEGIN IMMEDIATE");try{let n=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);if(n===null||n.sender_teamfile!==e.sender_teamfile||n.sender_alias!==e.sender_alias)return this.db.exec("COMMIT"),!1;if(r!==void 0&&this.db.prepare(`SELECT lease_id FROM agent_state
|
|
1530
|
+
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e.receiver_teamfile,e.receiver_alias)?.lease_id!==r)return this.db.exec("COMMIT"),!1;if(n.active_count<=1){let i=this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return i.changes===1&&ds(this.db,n,"INFLIGHT_RELEASE"),this.db.exec("COMMIT"),i.changes===1}let s=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),s.changes===1}catch(n){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),n}}clearAgentInflightOlderThan(e){return this.db.transaction(()=>{let n=this.listAgentInflight().filter(i=>i.started_at<e),s=0;for(let i of n)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(ds(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(is,as(e,r),os);return n===void 0?null:lp(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&Dl(this.db,n,!0),this.stmts.upsertRuntimeState.run(is,as(e.teamfile,e.alias),os,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&vp(this.db,e)})()}heartbeatTerminalLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,r);if(i===null||i.lock_id!==n)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(is,as(e,r),os,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,r,n){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,r);if(s===null||s.lock_id!==n)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(is,as(e,r),os);return i.changes===1&&Dl(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,r,n){let s=this.stmts.getRuntimeState.get(e,r,n);return s===void 0?null:rA(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=$()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!nA(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Dp(),holder_pid:process.pid,holder_host:ms(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,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,$(),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,$())}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,$());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,$(),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??$(),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,$());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,$()).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,$()),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,$());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run($(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=$();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:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}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??$());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,i=0;for(let o of r)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let 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,$())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,$())}}});import{realpathSync as lA}from"node:fs";import{resolve as dA}from"node:path";function Wl(t){let e=dA(t);try{return lA(e)}catch{return e}}var Fp=E(()=>{"use strict"});import{platform as Up}from"node:os";function Nt(t){let e=new fs;for(let r of t)e.registerAdapter(r);return e}var fs,ql=E(()=>{"use strict";Fp();fs=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let r=[],n=e?.provider?this.providers.filter(o=>o.name===e.provider):this.providers,s=await Promise.all(n.map(o=>o.discoverSessions()));for(let o of s)r.push(...o);let i=r;if(e?.workspace){let o=Wl(e.workspace);i=i.filter(a=>Wl(a.cwd)===o)}if(e?.from){let o=e.from.getTime();i=i.filter(a=>a.modifiedAt.getTime()>=o)}if(e?.to){let o=e.to.getTime();i=i.filter(a=>a.modifiedAt.getTime()<=o)}return i.sort((o,a)=>a.modifiedAt.getTime()-o.modifiedAt.getTime()),e?.limit&&(i=i.slice(0,e.limit)),i}async getSession(e,r){let n=r?this.providers.filter(s=>s.name===r):this.providers;for(let s of n){let i=await s.loadSession(e);if(i)return i}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(i=>i.name===r):this.providers,s=[];for(let i of n){let o=await i.resolveSessionPath(e);o&&s.push({provider:i,filePath:o})}return s}getWatchTargets(){let e=Up()==="darwin"||Up()==="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 Wp}from"node:fs";import{createInterface as qp}from"node:readline";import{stat as cA}from"node:fs/promises";import{homedir as uA}from"node:os";async function*Ge(t){let e=Wp(t,{encoding:"utf-8"}),r=qp({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 Pe(t,e){let r=[],n=Wp(t,{encoding:"utf-8"}),s=qp({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(o){try{r.push(JSON.parse(o))}catch{}if(r.length>=e)break}}}finally{s.close(),n.destroy()}return r}async function Re(t){let e=await cA(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function pe(t){return t.replace(/\\n/g,`
|
|
1530
1531
|
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function X(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}var ke,cr=E(()=>{"use strict";ke=uA()});import{readdir as Si,stat as Bp,unlink as mA}from"node:fs/promises";import{join as cn,basename as Hp}from"node:path";function fA(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function pA(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return pe(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 Xp(t){let e=0,r=0,n=0,s=0,i=0,o=0,a;for await(let l of Ge(t))if(!l.isSidechain){if(l.type==="user"&&!l.isMeta&&l.message){let d=l.message.content;if(typeof d=="string"){if(d.includes("<command-name>")||d.includes("<local-command-"))continue;e++}}else if(l.type==="assistant"&&l.message){let d=l.message.content;if(Array.isArray(d))for(let u of d)u.type==="text"&&e++;let c=l.message.usage;if(c){let u=c.input_tokens||0,f=c.cache_creation_input_tokens||0,m=c.cache_read_input_tokens||0,p=c.output_tokens||0;r+=u+f+m,n+=m,s+=f,i+=p;let h=u+f+m;h&&(o=h),a={inputTokens:u,cacheWriteInputTokens:f,cachedInputTokens:m,outputTokens:p}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a}}var bi,Jp=E(()=>{"use strict";cr();bi=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||cn(ke,".claude"),this.projectsDir=cn(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await Si(this.projectsDir)}catch{return e}for(let n of r){let s=cn(this.projectsDir,n);if(!(await Bp(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Si(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=Hp(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let d=cn(s,a);try{let c=await this.extractSummary(d,l);c&&e.push(c)}catch{}}}return e}async extractSummary(e,r){let n=await Pe(e,50),s=await Re(e),i="",o,a,l,d,c,u;for(let m of n)if(!fA(m.type)&&(!i&&m.cwd&&(i=m.cwd),!o&&m.slug&&(o=m.slug),!a&&m.version&&(a=m.version),!u&&m.timestamp&&(u=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;d||(d=X(p.trim(),80)),c=X(p.trim(),80)}}if(!i)return null;let f=await Xp(e);return{provider:"claude",sessionId:r,slug:o,cwd:i,createdAt:u||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:d,lastUserMessage:c,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 Re(r),s=[],i="",o,a,l,d,c,u,f,m=e;for await(let h of Ge(r))if(h.type!=="file-history-snapshot"&&!h.isSidechain){if(!i&&h.cwd&&(i=h.cwd),!o&&h.slug&&(o=h.slug),!a&&h.version&&(a=h.version),!d&&h.gitBranch&&(d=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:pA(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;c||(c=X(_.trim(),80)),u=X(_.trim(),80),s.push({role:"user",timestamp:g,content:pe(_.trim())})}else if(Array.isArray(_)){for(let y of _)if(y.type==="tool_result"){let T=typeof y.content=="string"?pe(y.content):JSON.stringify(y.content);s.push({role:"tool_result",timestamp:g,content:T,toolCallId:y.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 y of _)y.type==="text"&&y.text?s.push({role:"assistant",timestamp:g,content:pe(y.text),model:h.message.model}):y.type==="tool_use"?s.push({role:"tool_use",timestamp:g,content:y.name||"unknown tool",toolName:y.name,toolInput:JSON.stringify(y.input,null,2),toolCallId:y.id,model:h.message.model}):y.type==="thinking"&&y.thinking&&s.push({role:"thinking",timestamp:g,content:y.thinking})}}if(!i)return null;let p=await Xp(r);return{provider:"claude",sessionId:m,slug:o,cwd:i,createdAt:f||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:d,firstUserMessage:c,lastUserMessage:u,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 mA(r),!0):!1}async resolveSessionFile(e){let r;try{r=await Si(this.projectsDir)}catch{return null}let n=[];for(let o of r){let a=cn(this.projectsDir,o);if(!(await Bp(a).catch(()=>null))?.isDirectory())continue;let d;try{d=await Si(a)}catch{continue}for(let c of d){if(!c.endsWith(".jsonl"))continue;let u=Hp(c,".jsonl");/^[0-9a-f]{8}-/.test(u)&&n.push({filePath:cn(a,c),fileSessionId:u})}}let s=n.find(o=>o.fileSessionId===e);if(s)return s.filePath;let i=n.filter(o=>o.fileSessionId.startsWith(e));if(i.length===1)return i[0].filePath;for(let o of n){let a=await Pe(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});import{readFileSync as _A,writeFileSync as _4,mkdirSync as h4}from"node:fs";import{join as hA,dirname as y4}from"node:path";import{homedir as gA}from"node:os";function EA(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function wA(t){let e=t.indexOf("=");if(e===-1)return null;let r=t.slice(0,e).trim(),n=EA(t.slice(e+1).trim());return r?{key:r,value:n}:null}function TA(t){let e=t.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function Ii(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function vA(){return hA(gA(),".lmctl","config.toml")}function Vp(t){let e=t??vA(),r;try{r=_A(e,"utf-8")}catch{return{tools:{}}}return SA(r)}function Gp(t){if(typeof t=="number")return Number.isFinite(t)?t:null;let e=String(t).trim();if(!e)return null;let r=e.match(/^(\d+(?:\.\d+)?)\s*([KkMm]?)$/);if(!r)return null;let n=parseFloat(r[1]);if(!Number.isFinite(n))return null;switch(r[2]){case"K":case"k":return Math.round(n*1e3);case"M":case"m":return Math.round(n*1e6);default:return Math.round(n)}}function SA(t){let e={},r={},n=t.split(`
|
|
1531
1532
|
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let u=e[s.tool]??{};if(s.profile){let f=u.profiles?.[s.profile]??{};i.description&&(f.description=i.description),i.flags!==void 0&&(f.flags=i.flags),u.profiles||(u.profiles={}),u.profiles[s.profile]=f}else i.start&&(u.start=i.start),i.resume&&(u.resume=i.resume),i.agent&&(u.agent=i.agent),i.profile_flag!==void 0&&(u.profile_flag=i.profile_flag);e[s.tool]=u}else if(s.kind==="compact"){let u=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let f=Gp(i.min);f!==null&&(u.min=f)}if(i.max!==void 0){let f=Gp(i.max);f!==null&&(u.max=f)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=u):r.global=u}i={}}for(let u of n){let f=u.trim();if(!f||f.startsWith("#"))continue;let m=TA(f);if(m!==null){if(o=!0,l(),m.startsWith("tool.")){let h=".profile.",g=m.indexOf(h);g!==-1?s={kind:"tool",tool:m.slice(5,g),profile:m.slice(g+h.length)}:s={kind:"tool",tool:m.slice(5),profile:null}}else m==="compact"?s={kind:"compact",provider:null}:m.startsWith("compact.")?s={kind:"compact",provider:m.slice(8)}:s={kind:"none"};continue}let p=wA(f);p&&s.kind!=="none"?i[p.key]=p.value:p&&!o&&(a[p.key]=p.value)}l();let d={tools:e};(r.global||r.providers)&&(d.compact=r);let c=a.site_name;return c!==void 0&&c.length>0&&(d.site_name=c),d}function Kp(t){return t.site_name??null}function bA(t,e,r){if(!r)return"";let n=t.tools[e]??Bl[e],s=n?.profiles?.[r]?.flags??Bl[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 Yp(t,e){return!!t.tools[e]}function zp(t,e,r,n,s){let i=t.tools[e]??Bl[e],o;if(i?.agent){let l=Ii(n);o=i.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=yA[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let d=l.argv.map(c=>c.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,n));if(l.mode==="stdin"){let c=d.map(Ii).join(" ");o=`printf '%s\\n' ${Ii(n)} | ${c}`}else o=d.map(Ii).join(" ")}let a=bA(t,e,s);return a&&(o+=" "+a),o}var Bl,yA,Hl=E(()=>{"use strict";Bl={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:""}}}},yA={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 Zp(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 Qp=E(()=>{"use strict"});var IA,Ee,ki,At=E(()=>{"use strict";IA="ACK: waiting for explicit lmctl task.",Ee=`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: ${IA}`,ki=`send this exact lmctl seed instruction: "${Ee}"`});function ur(t,e){let r={...t??process.env,PWD:e};return delete r.OLDPWD,r}function NA(t,e){return e===void 0||e.length===0?t:{...t??process.env,[ps]:e}}function Fe(t,e,r,n="chat"){return{...NA(ur(t,e),r),[kA]:n}}var ps,kA,ut=E(()=>{"use strict";ps="LMCTL_SELF_SESSIONID",kA="LMCTL_LAUNCH_SOURCE"});import{spawn as e_}from"node:child_process";import{mkdirSync as AA}from"node:fs";var Xl,Le,Ht=E(()=>{"use strict";Hl();Qp();At();ut();Xl=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},Le=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===Ee?r:n)}seed(e,r){return AA(e,{recursive:!0}),new Promise(n=>{let s;try{s=e_(this.binary,this.seedArgsFor(r),{cwd:e,env:ur(void 0,e),stdio:["pipe","pipe","pipe"],timeout:6e4})}catch(a){return n({success:!1,error:a instanceof Error?a.message:String(a)})}let i="";s.stderr?.on("data",a=>{i+=a.toString()});let o=r?.prompt!==void 0&&this.seedStdin!==void 0?`${r.prompt}
|
|
1532
1533
|
`:this.seedStdin;o&&s.stdin?.write(o),s.stdin?.end(),s.on("exit",a=>{n(a===0||a===null?{success:!0}:{success:!1,error:i.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:ki,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,r){if(r.userConfig&&Yp(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,i,o,a="",l,d=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{n.onIdleWarning?.(e),c(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},c=()=>{clearTimeout(i)};n.signal&&(n.signal.aborted?(o="external",s.abort()):n.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),d();let u={...n,binary:this.binary,signal:s.signal,onDelta:p=>{a+=p,d(),n.onDelta?.(p)},onProgress:p=>{p.kind!=="api_retry"&&d(),n.onProgress?.(p)}},f=this.transportFn(r,u).then(p=>(c(),{...p,status:"ok"})).catch(p=>{throw c(),o==="external"?new Xl("Turn cancelled","external"):p}),m=new Promise(p=>{l=p});return Promise.race([f,m])}runOneShotAgent(e,r,n){let s=zp(r.userConfig,this.name,r.sessionId,e,r.profile),i=Date.now();return new Promise((o,a)=>{let l=Zp(r.env),d=e_(s,{shell:!0,cwd:r.cwd,env:Fe(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),c=!1,u=!1,f=setTimeout(()=>{u=!0,d.kill()},l),m="",p="";if(d.stdout?.on("data",h=>{let g=h.toString();m+=g,r.onDelta?.(g)}),d.stderr?.on("data",h=>{p+=h.toString()}),r.signal){if(r.signal.aborted)return clearTimeout(f),d.kill(),a(new Error("Aborted"));r.signal.addEventListener("abort",()=>d.kill(),{once:!0})}d.on("exit",h=>{if(c)return;c=!0,clearTimeout(f);let g=Date.now()-i;u?a(new Error(`Agent command timed out after ${l}ms`)):h===0||h===null?o({text:m.trim(),sessionId:r.sessionId,durationMs:g}):a(new Error(p.trim().slice(0,200)||`Agent command exited with code ${h}`))}),d.on("error",h=>{c||(c=!0,clearTimeout(f),a(h))})})}}});function Ai(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new Jt(t,r,e)}var st,we,Xt,Ni,Jt,un=E(()=>{"use strict";st=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},we=class extends st{},Xt=class extends st{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},Ni=class extends st{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},Jt=class extends st{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as Gl from"node:child_process";function RA(t){if(typeof Gl.spawnSync=="function")try{Gl.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function t_(t){return t.exitCode!==null||t.signalCode!==null}function Jl(t,e){return t_(t)?Promise.resolve(!0):new Promise(r=>{let n=!1,s=()=>{n||(n=!0,clearTimeout(i),r(!0))},i=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,i=e.killDelayMs??5e3,o=e.platform??process.platform,a=e.runTaskkill??RA;if(t_(t))return{signal:"natural",elapsedMs:Date.now()-r};if(n&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await Jl(t,s))return{signal:"stdin",elapsedMs:Date.now()-r};if(o==="win32"&&typeof t.pid=="number")a(t.pid);else try{t.kill("SIGTERM")}catch{}if(await Jl(t,i))return{signal:"SIGTERM",elapsedMs:Date.now()-r};if(o!=="win32")try{t.kill("SIGKILL")}catch{}return await Jl(t,xA)?{signal:"SIGKILL",elapsedMs:Date.now()-r}:{signal:"abandoned",elapsedMs:Date.now()-r}}var xA,xi=E(()=>{"use strict";xA=1e3});function r_(t){ce()&&Oe({event:"legacy",msg:`[debug] ${t}`},{always:!0})}function mr(t,e){let r=OA[t];if(r)return r[e]??r.yolo}function CA(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 mt(t,e,r="yolo"){if($A.has(t)){r_(`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"?mr(t,"plan"):LA[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 C({event:"yolo_assert_failed",provider:t,reason:"unconfigured_provider",args:e.join(" "),message:s}),new we(s)}if(!CA(e,n)){let s=n.join(" "),i=`${t} spawn missing YOLO flag '${s}' \u2014 YOLO is mandatory for every provider; see src/providers/yolo-contract.ts. Got argv: [${e.map(o=>JSON.stringify(o)).join(", ")}]`;throw C({event:"yolo_assert_failed",provider:t,reason:"flag_missing",required_flag:s,mode:r,args:e.join(" "),message:i}),new we(i)}r_(`YOLO ${t} [mode=${r}]: argv flag '${n.join(" ")}'`)}var LA,OA,$A,mn=E(()=>{"use strict";un();me();LA={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},OA={claude:{yolo:["--dangerously-skip-permissions"],plan:["--permission-mode","plan"]},qwen:{yolo:["--approval-mode","yolo"],plan:["--approval-mode","plan"]},gemini:{yolo:["-y"],plan:["--approval-mode","plan"]},copilot:{yolo:["--yolo"],plan:["--yolo"]},agy:{yolo:["--dangerously-skip-permissions"],plan:["--dangerously-skip-permissions"]},lmplayer:{yolo:["--dangerously-skip-permissions"],plan:["--dangerously-skip-permissions"]}};$A=new Set(["codex","opencode"])});function n_(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(`
|
|
@@ -2316,8 +2317,8 @@ ${i.text}`;return er("mailbox_delivery_attempt_stalled",r,{stalled_after_ms:i.st
|
|
|
2316
2317
|
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(sF(r)){if(n!==void 0)return{mode:"error",message:`lmctl ${t.name}: got a second positional "${n}" but "${r}" is not a teamfile path.`};if(!t.supportsRaw)return{mode:"error",message:`lmctl ${t.name}: "${r}" is a bare sessionid, but ${t.name} is teamfile-only (a sessionid carries no provider resume incantation).`};let a={mode:"ai-team-raw",sessionid:r};return s.provider!==void 0&&(a.provider=s.provider),a}return n!==void 0?{mode:"error",message:`lmctl ${t.name}: got a second positional "${n}" but "${r}" is not a teamfile path.
|
|
2317
2318
|
Either drop the second arg, or pass <teamfile>.lmctl as the first arg.`}:{mode:"error",message:`lmctl ${t.name}: can't infer target type from "${r}".
|
|
2318
2319
|
Expected one of: <path>.lmctl, <path>.lmctl:<alias>, <sessionid>.`}}if(s.session!==void 0){if(!t.supportsRaw)return{mode:"error",message:`lmctl ${t.name}: --session (raw mode) is not supported by ${t.name}.`};let o={mode:"ai-team-raw",sessionid:s.session};return s.provider!==void 0&&(o.provider=s.provider),o}return{mode:"error",message:`lmctl ${t.name}: a target is required.
|
|
2319
|
-
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var ve,rF,nF,Na,wt=E(()=>{"use strict";tr();rr();ve=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}},rF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,nF=/^ses_[A-Za-z0-9_-]+$/,Na=/^[A-Za-z][A-Za-z0-9_-]*$/});function Aa(t){return oF.has(t)}function Uu(){return Fu===null&&(Fu=Nt(xt())),Fu}function Wu(t,e,r={}){if(!Aa(t))return null;try{let n=Uu().getAdapter?.(t);if(n===void 0)return null;let s=n.resumeCommand(e).trim();if(s.length===0)return null;let i=s.split(/\s+/),o=t==="codex"&&r.isLead===!0?Ri({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?iF[t]?.(r.model):void 0;return r.model!==void 0&&r.model.trim().length>0&&a===void 0&&r.onModelIgnored?.({provider:t,model:r.model,reason:`${t} terminal resume does not implement per-session model selection`}),[...i,...a??[],...o,...TT[t]??[]]}catch{return null}}function xa(t,e,r={}){let n=Wu(t,e,r);return n===null?null:n.join(" ")}function Be(t,e){return Uu().getSession(t,e)}async function Pn(t){return(await Uu().resolveSessions(t)).map(r=>r.provider.name)}var TT,iF,oF,vT,Fu,nr=E(()=>{"use strict";Lt();Yl();TT={claude:["--dangerously-skip-permissions"],codex:["--dangerously-bypass-approvals-and-sandbox"],gemini:["-y"],copilot:["--yolo"],opencode:[],qwen:["--approval-mode","yolo"],agy:[],lmplayer:[]},iF={claude:t=>["--model",t],codex:t=>["--model",t],gemini:t=>["--model",t],opencode:t=>["--model",t],qwen:t=>["--model",t],agy:t=>["--model",t],lmplayer:t=>["--model",t]},oF=new Set(Object.keys(TT)),vT=/^[\w.:-]+$/;Fu=null});function aF(t=process.env){let e=t.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return ST;let r=Number(e);return!Number.isFinite(r)||r<=0?ST:r}async function lF(t,e,r){try{let n=De(e,r,t),s=n.sessionid;if(typeof s!="string"||s.trim()===""||s===".")return null;let i;if(typeof n.provider=="string"&&n.provider.trim()!=="")i=n.provider;else{let d=await Pn(s);if(d.length!==1)return null;i=d[0]}let o=await Be(s,i);if(o===null)return null;let a=o.modifiedAt;if(!(a instanceof Date))return null;let l=a.getTime();return Number.isFinite(l)?Date.now()-l:null}catch{return null}}async function Ra(t,e,r,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??aF(),o=await lF(t,r,n),a=o!==null&&o>=i;return a&&C({event:"session_idle_reclaim",receiver_teamfile:r,receiver_alias:n,idle_ms:o,idle_minutes:o===null?null:Math.round(o/6e4),threshold_ms:i,reason:"in-flight holder idle past session-idle threshold; lease will be force-reclaimed"}),a}var ST,qu=E(()=>{"use strict";me();nr();wt();ST=36e5});function dF(t=process.env){let e=t.LMCTL_DAEMON_MAILBOX_RELAY_MAX_BATCHES;if(e===void 0||e.trim()==="")return bT;let r=Number(e);return!Number.isFinite(r)||r<=0?bT:Math.max(1,Math.trunc(r))}async function kT(t){let e=t.env??process.env,r=t.maxBatches??dF(e),n=hF(t.dal),s={scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0};_F(t.dal,e);let i=new Set;for(;s.scanned<r;){let o=t.dal.listRelayMailboxLanes(r).find(l=>!i.has(IT(l)));if(o===void 0)break;i.add(IT(o)),s.scanned+=1;let a=await cF(t.dal,n,e,o);s.delivered+=a.delivered,s.skipped_busy+=a.skipped_busy,s.skipped_terminal+=a.skipped_terminal,s.errors+=a.errors}return s}function IT(t){return JSON.stringify([t.sender_teamfile,t.sender_alias,t.receiver_teamfile,t.receiver_alias])}async function cF(t,e,r,n){let s={scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0},i=Wt(t,n.receiver_teamfile,n.receiver_alias),o=!1;if(i.busy){if(!await Ra(t,i,n.receiver_teamfile,n.receiver_alias))return i.reason==="terminal-held"?{...s,skipped_terminal:1}:{...s,skipped_busy:1};o=!0}let a=null,l=null;try{let d=De(n.receiver_teamfile,n.receiver_alias,t),c=ar(t,{receiver_teamfile:n.receiver_teamfile,receiver_alias:n.receiver_alias,sender_teamfile:n.sender_teamfile,sender_alias:n.sender_alias,ttlMs:br(),...o?{force:!0}:{}});if(!c.acquired)return{...s,skipped_busy:1};if(a=c.lease,l=sn(f=>t.heartbeatAgentInflight(a,
|
|
2320
|
-
${t.receipt}`:`relay delivery error: ${t.error}`}function _F(t,e){t.reclaimStaleMailboxDeliveries(new Date(Date.now()-Au(e)).toISOString())}function hF(t){return{stdout:{write:()=>{}},stderr:{write:()=>{}},dal:t}}var bT,NT=E(()=>{"use strict";lr();xu();Ta();wt();qu();bT=10});function Bs(){let t=process.env.LMCTL_DAEMON_INTERVAL_MS;if(t===void 0||t.trim().length===0)return 5e3;let e=Number(t);return Number.isFinite(e)&&e>0?e:5e3}function yF(t=process.env){let e=t.LMCTL_DAEMON_FEATURES;if(e===void 0)return new Set(["mailbox-relay"]);if(e.trim()==="")return new Set;let r=new Set;for(let n of e.split(",")){let s=n.trim();if(s!==""){if(s==="all")return new Set(AT);gF.has(s)&&r.add(s)}}return r}function xT(t){let e=t.intervalMs??Bs(),r=t.runOnceFn??Br,n=new Set(t.features??yF()),s={running:t.autoStart!==!1,in_flight:!1,interval_ms:e,enabled_features:[...n].sort(),cycles:0,jobs_processed:0,last_jobs_processed:0,last_started_at:null,last_finished_at:null,last_error:null,last_session_sizes_recorded:0,last_session_size_failures:0,last_intake_scanned:0,last_intake_new_jobs:0,last_intake_failures:0,last_session_hung_detected:0,last_session_monitor_checked_at:null,last_session_monitor_error:null,last_mailbox_relay_scanned:0,last_mailbox_relay_delivered:0,last_mailbox_relay_errors:0},i=null,o=null,a=null,l=null,d=null;n.has("rollup-updater")&&t.startRollupUpdaterFn!==!1&&(d=(t.startRollupUpdaterFn??Kw)(t.dal));let c=m=>{s.running&&(i=setTimeout(()=>{f.runCycle().finally(()=>c(e))},m))},u=m=>{s.running&&(o=setTimeout(()=>{l===null&&(l=RT(t.dal,n,t.monitorSessionActivityFn??rc,e,s).finally(()=>{l=null})),l.finally(()=>u(nc(t.dal,e)))},m))},f={state:s,runCycle:async()=>(a!==null||(a=EF(t.dal,r,t.collectSessionSizesFn??yh,t.scanIntakeFn??xo,t.monitorSessionActivityFn??rc,t.mailboxRelayFn??kT,t.worker_id??"daemon",e,n,s).finally(()=>{a=null})),a),stop:async()=>{s.running=!1,i!==null&&clearTimeout(i),o!==null&&clearTimeout(o),d?.stop(),a!==null&&await a.catch(()=>{}),l!==null&&await l.catch(()=>{})}};if(s.running){let m=t.firstDelayMs??5e3;c(m),n.has("session-monitor")&&u(m)}return f}async function EF(t,e,r,n,s,i,o,a,l,d){d.in_flight=!0,d.last_started_at=new Date().toISOString(),d.last_error=null;let c=[],u=0,f=0,m=[],p=null,h=wF();try{if(l.has("durable-memory-policies")&&IE({dal:t}),l.has("drift-detectors")&&Zw({dal:t}),l.has("intake")&&(m=await n(t)),l.has("job-worker"))for(;;){let g=await e({dal:t,worker_id:o,lease_ms:6e5});if(g===null)break;c.push(g)}if(l.has("mailbox-relay")&&(h=await i({dal:t})),l.has("session-size")){let g=await r(t);u=g.recorded,f=g.failed}l.has("session-monitor")&&(p=await RT(t,l,s,a,d))}catch(g){d.last_error=g instanceof Error?g.message:String(g);try{t.raiseAttention({kind:"daemon_worker_failed",severity:"error",payload:JSON.stringify({error:d.last_error})})}catch{}}finally{d.in_flight=!1,d.cycles+=1,d.last_jobs_processed=c.length,d.last_session_sizes_recorded=u,d.last_session_size_failures=f,d.last_intake_scanned=m.reduce((g,_)=>g+_.scanned,0),d.last_intake_new_jobs=m.reduce((g,_)=>g+_.new_jobs,0),d.last_intake_failures=m.filter(g=>g.error!==void 0).length,d.last_session_hung_detected=p?.hung_detected??0,d.last_mailbox_relay_scanned=h.scanned,d.last_mailbox_relay_delivered=h.delivered,d.last_mailbox_relay_errors=h.errors,d.jobs_processed+=c.length,d.last_finished_at=new Date().toISOString()}return{jobs_processed:c.length,outcomes:c,session_sizes_recorded:u,session_size_failures:f,intake:m,session_monitor:p,mailbox_relay:h}}function wF(){return{scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0}}async function RT(t,e,r,n,s){if(!e.has("session-monitor"))return null;let i=nc(t,n),o=Date.now();if(s.last_session_monitor_checked_at!==null){let a=Date.parse(s.last_session_monitor_checked_at);if(Number.isFinite(a)&&o-a<i)return null}s.last_session_monitor_checked_at=new Date(o).toISOString(),s.last_session_monitor_error=null;try{return await r({dal:t,nowMs:o})}catch(a){s.last_session_monitor_error=a instanceof Error?a.message:String(a);try{t.raiseAttention({kind:"daemon_session_monitor_failed",severity:"error",payload:JSON.stringify({error:s.last_session_monitor_error})})}catch{}return null}}var AT,gF,Bu=E(()=>{"use strict";Nc();zo();su();to();Yw();Qw();sc();NT();AT=["durable-memory-policies","drift-detectors","intake","job-worker","mailbox-relay","session-size","session-monitor","rollup-updater"],gF=new Set(AT)});function LT(t){let e=t.listMembersInState("in_chat");for(let r of e)t.setMemberState(r.id,"attention_needed","daemon_restarted_mid_chat");return e.length}var OT=E(()=>{"use strict"});import{mkdirSync as TF,readFileSync as vF,readdirSync as SF,statSync as bF,writeFileSync as IF}from"node:fs";import{dirname as kF,join as CT,sep as $T}from"node:path";function La(t){return{s3:{async send(n){let s=n;switch(s._localfsTag){case MT:return NF(t,s.input);case DT:return AF(t,s.input);case jT:return xF(t,s.input);default:throw new Error("createLocalFsS3Client: unknown command")}}},commands:{ListObjectsV2Command:Ju,GetObjectCommand:Xu,PutObjectCommand:Hu}}}function NF(t,e){let r=PT(t,e.Key);return TF(kF(r),{recursive:!0}),IF(r,e.Body),{}}function AF(t,e){let r=PT(t,e.Key),n;try{n=vF(r)}catch(i){throw i.code==="ENOENT"?Object.assign(new Error("NoSuchKey"),{name:"NoSuchKey"}):i}let s=n.toString("utf-8");return{Body:{transformToString:async()=>s}}}function xF(t,e){let r=e.Prefix??"";FT(r);let s=RF(t).sort((c,u)=>c.key<u.key?-1:c.key>u.key?1:0).filter(c=>c.key.startsWith(r)),i=e.ContinuationToken;i!==void 0&&i!==""&&(s=s.filter(c=>c.key>i));let o=typeof e.MaxKeys=="number"&&Number.isFinite(e.MaxKeys)&&e.MaxKeys>0?Math.floor(e.MaxKeys):void 0,a=s,l=!1;o!==void 0&&s.length>o&&(a=s.slice(0,o),l=!0);let d={Contents:a.map(c=>({Key:c.key,LastModified:c.lastModified})),IsTruncated:l};return l&&(d.NextContinuationToken=a[a.length-1].key),d}function PT(t,e){return FT(e),CT(t,e)}function FT(t){if(t.split("/").includes(".."))throw new Error(`localfs-s3-client: refusing key/prefix with '..': ${t}`)}function RF(t){let e=[],r=(n,s)=>{let i;try{i=SF(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(let o of i){let a=s===""?o.name:`${s}/${o.name}`,l=CT(n,o.name);if(o.isDirectory())r(l,a);else if(o.isFile()){let d=$T==="/"?a:a.split($T).join("/");e.push({key:d,lastModified:bF(l).mtime})}}};return r(t,""),e}var MT,DT,jT,Hu,Xu,Ju,Gu=E(()=>{"use strict";MT="localfs-put",DT="localfs-get",jT="localfs-list",Hu=class{input;_localfsTag=MT;constructor(e){this.input=e}},Xu=class{input;_localfsTag=DT;constructor(e){this.input=e}},Ju=class{input;_localfsTag=jT;constructor(e){this.input=e}}});function UT(){return{put:0,get:0,list:0}}function Vu(t,e=LF){return t.put*e.putUsd+t.get*e.getUsd+t.list*e.listUsd}function Ku(t){let e=new Date(t),r=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0");return`${r}-${n}`}var LF,Oa,Yu=E(()=>{"use strict";LF={putUsd:5e-6,getUsd:40000000000000003e-23,listUsd:5e-6};Oa=class{counts=UT();record(e,r=1){this.counts[e]+=r}peek(){return{...this.counts}}drain(){let e={...this.counts};return this.counts=UT(),e}estimateCostUsd(e){return Vu(this.counts,e)}}});function WT(t){let e=t.now??Date.now,r=t.timers??OF,n=null,s=null;async function i(){let l=e(),d=Ku(l),c=t.meter.drain();(c.put>0||c.get>0||c.list>0)&&t.store.addUsage({user_id:t.userId,device_id:t.deviceId,period:d,put:c.put,get:c.get,list:c.list,updated_at:new Date(l).toISOString()});let u=t.store.loadUsage(t.userId,t.deviceId,d),f=u?{put:u.put_count,get:u.get_count,list:u.list_count}:{put:0,get:0,list:0};if(t.publishOwnRollup!==void 0)try{await t.publishOwnRollup(d,f)}catch(h){t.log?.(`[usage] publish rollup failed: ${h instanceof Error?h.message:String(h)}`)}let m=f;if(t.readUserTotal!==void 0)try{m=await t.readUserTotal(d)}catch(h){t.log?.(`[usage] read user total failed: ${h instanceof Error?h.message:String(h)}`),m=f}let p=Vu(m);if(n!==d&&p>=t.ceilingUsd){n=d,t.log?.(`[usage] quota exceeded period=${d} cost=$${p.toFixed(4)} >= ceiling $${t.ceilingUsd}`);try{t.onQuotaExceeded({period:d,costUsd:p,ceilingUsd:t.ceilingUsd})}catch(h){t.log?.(`[usage] onQuotaExceeded threw: ${h instanceof Error?h.message:String(h)}`)}}}function o(){return s=(s??Promise.resolve()).then(()=>i()).catch(()=>{}),s}let a=r.setInterval(()=>{o()},t.intervalMs);return{stop(){r.clearInterval(a)},flushNow(){return o()},isOverQuota(){return n!==null&&n===Ku(e())}}}var OF,qT=E(()=>{"use strict";Yu();OF={setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)}});var zu=E(()=>{"use strict";ra();sa();sa()});function $F(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;if(typeof e.message_id!="string"||e.message_id==="")return null;if(typeof e.reply_to=="string"&&e.reply_to!==""){let s=e.response;if(typeof s!="object"||s===null)return null;let i=s;return typeof i.status!="number"?null:{message_id:e.message_id,reply_to:e.reply_to,response:i}}let r=e.request;if(typeof r!="object"||r===null)return null;let n=r;return typeof n.method!="string"||n.method===""||typeof n.path!="string"||n.path===""?null:{message_id:e.message_id,request:n}}function CF(t){return t.reply_to!==void 0&&t.response!==void 0}function MF(t){if(typeof t!="object"||t===null)return;let e=t.conversation_id;return typeof e=="string"?e:void 0}function BT(t){let e=t.reason;if(e!==void 0)return e;try{return new DOMException("Aborted","AbortError")}catch{let r=new Error("Aborted");return r.name="AbortError",r}}var $a,Hs,HT=E(()=>{"use strict";zu();$a=class extends Error{name="MailboxFetchStoppedError";code="mailbox_fetch_stopped";constructor(e="MailboxFetchClient stopped before a response arrived"){super(e)}},Hs=class{client;log;now;random;pending=new Map;requestHandler=null;stopped=!1;constructor(e){this.client=e.client,this.log=e.log??(()=>{}),this.now=e.now??Date.now,this.random=e.random??Math.random}onRequest(e){if(this.requestHandler!==null)throw new Error("MailboxFetchClient: onRequest handler already registered");this.requestHandler=e}async fetch(e,r){if(this.stopped)throw new $a("MailboxFetchClient.fetch after stop()");if(typeof e.path!="string"||e.path==="")throw new Error("MailboxFetchClient.fetch: request.path is required");let n=e.method;if(typeof n!="string"||n==="")throw new Error("MailboxFetchClient.fetch: request.method is required");let s=Qt(this.now(),this.random);if(this.pending.has(s))throw new Error(`MailboxFetchClient.fetch: duplicate message_id=${s}`);let i=r?.conversationId??s,o={message_id:s,request:e};return new Promise((a,l)=>{let d=r?.abortSignal,c;if(d!==void 0){if(d.aborted){l(BT(d));return}c=()=>{this.pending.has(s)&&(this.pending.delete(s),l(BT(d)))},d.addEventListener("abort",c,{once:!0})}this.pending.set(s,{resolve:a,reject:l,...c!==void 0?{abortListener:c}:{},...d!==void 0?{abortSignal:d}:{}}),this.client.putMessage({conversation_id:i,payload:o}).catch(u=>{let f=this.pending.get(s);f!==void 0&&(this.pending.delete(s),f.abortListener!==void 0&&f.abortSignal!==void 0&&f.abortSignal.removeEventListener("abort",f.abortListener),f.reject(u))})})}async stop(){if(this.stopped)return;this.stopped=!0;let e=Array.from(this.pending.values());this.pending.clear();let r=new $a;for(let n of e){n.abortListener!==void 0&&n.abortSignal!==void 0&&n.abortSignal.removeEventListener("abort",n.abortListener);try{n.reject(r)}catch{}}}async handleIncoming(e,r){let n=$F(e);if(n===null){this.log("MailboxFetchClient: dropping non-envelope inbound payload");return}if(CF(n)){let l=this.pending.get(n.reply_to);if(l===void 0){this.log(`MailboxFetchClient: dropping response for unknown reply_to=${n.reply_to}`);return}this.pending.delete(n.reply_to),l.abortListener!==void 0&&l.abortSignal!==void 0&&l.abortSignal.removeEventListener("abort",l.abortListener),l.resolve(n.response);return}if(this.requestHandler===null){this.log(`MailboxFetchClient: no handler registered; dropping request message_id=${n.message_id}`);return}let s=r?.conversation_id??MF(e)??n.message_id,i;try{i=await this.requestHandler(n.request)}catch(l){let d=l instanceof Error?l.message:String(l),c=typeof l.code=="string"?l.code:"INTERNAL_ERROR";i={status:500,headers:{"content-type":"application/json"},body:{error:c,message:d}}}let a={message_id:Qt(this.now(),this.random),reply_to:n.message_id,response:i};try{await this.client.putMessage({conversation_id:s,payload:a})}catch(l){this.log(`MailboxFetchClient: response PUT failed for reply_to=${n.message_id}: ${l instanceof Error?l.message:String(l)}`)}}}});function Zu(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;return!(e.kind!=="terminal"||typeof e.session_id!="string"||e.session_id===""||e.direction!=="agent_to_user"&&e.direction!=="user_to_agent"||typeof e.data!="string"||typeof e.ts!="number")}var XT=E(()=>{"use strict"});function Qu(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;if(e.kind!=="provider"||typeof e.session_id!="string"||e.session_id===""||e.direction!=="agent_to_user"&&e.direction!=="user_to_agent"||typeof e.ts!="number")return!1;if(e.direction==="agent_to_user"){if(!Array.isArray(e.events))return!1;for(let r of e.events)if(typeof r!="object"||r===null||Array.isArray(r)||typeof r.event_type!="string")return!1}else if(typeof e.user_input!="string")return!1;return!0}var JT=E(()=>{"use strict"});function tm(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;if(e.kind!=="daemon_event"||typeof e.event!="string"||e.event===""||typeof e.ts!="number")return!1;if(e.event==="workflows"){if(!Array.isArray(e.workflows))return!1;for(let r of e.workflows){if(typeof r!="object"||r===null||Array.isArray(r))return!1;let n=r;if(typeof n.teamfile_path!="string"||n.teamfile_path===""||n.name!==null&&typeof n.name!="string"||typeof n.registered_at!="string"||n.registered_at===""||n.last_seeded_at!==null&&typeof n.last_seeded_at!="string")return!1}}else if(e.event==="chat_log"){if(typeof e.entry!="object"||e.entry===null||Array.isArray(e.entry))return!1;let r=e.entry;if(typeof r.id!="number"||typeof r.root_teamfile!="string"||r.root_teamfile===""||r.sender_teamfile!==null&&(typeof r.sender_teamfile!="string"||r.sender_teamfile==="")||r.sender_alias!==null&&(typeof r.sender_alias!="string"||r.sender_alias==="")||typeof r.receiver_teamfile!="string"||r.receiver_teamfile===""||typeof r.receiver_alias!="string"||r.receiver_alias===""||typeof r.message!="string"||r.response!==null&&typeof r.response!="string"||typeof r.status!="string"||r.status===""||typeof r.created_at!="string"||r.created_at==="")return!1}return!0}var em,GT=E(()=>{"use strict";em="daemon:events"});function KT(t){return{kind:"prompt",prompt_id:t.prompt_id??Qt(t.now?.()??Date.now(),t.random??Math.random),root_teamfile:t.root_teamfile,text:t.text}}function rm(t){if(t===null||typeof t!="object")return!1;let e=t;return e.kind==="prompt"&&typeof e.prompt_id=="string"&&e.prompt_id.length>0&&typeof e.root_teamfile=="string"&&e.root_teamfile.length>0&&typeof e.text=="string"}var VT,nm=E(()=>{"use strict";zu();VT="prompt:root"});function Xs(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(zT(e[1]));return typeof r.sub=="string"&&r.sub!==""?r.sub:null}catch{return null}}function DF(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(zT(e[1]));return typeof r.exp=="number"&&Number.isFinite(r.exp)?r.exp:null}catch{return null}}function YT(t,e=60){if(typeof t!="string"||t==="")return!0;let r=DF(t);return r===null?!0:Date.now()/1e3>=r-e}function zT(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"="),n=globalThis.Buffer;return n!==void 0?n.from(r,"base64").toString("utf8"):atob(r)}var sm=E(()=>{"use strict"});async function Ca(t){let e=t.fetchImpl??fetch,r=`https://cognito-idp.${t.region}.amazonaws.com/`,n=await e(r,{method:"POST",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":jF},body:JSON.stringify({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:t.clientId,AuthParameters:{REFRESH_TOKEN:t.refreshToken}})}),s=await n.text();if(!n.ok){let l=s;try{let d=JSON.parse(s);l=d.message??d.__type??s}catch{}throw new Error(`cognito_refresh_failed: ${n.status} ${l}`)}let o=JSON.parse(s).AuthenticationResult,a=o?.IdToken;if(typeof a!="string"||a==="")throw new Error("cognito_refresh_no_id_token: InitiateAuth returned no IdToken");return{idToken:a,...typeof o?.AccessToken=="string"&&o.AccessToken!==""?{accessToken:o.AccessToken}:{},...typeof o?.ExpiresIn=="number"&&Number.isFinite(o.ExpiresIn)?{expiresAt:Date.now()+o.ExpiresIn*1e3}:{}}}var jF,im=E(()=>{"use strict";jF="AWSCognitoIdentityProviderService.InitiateAuth"});import{chmodSync as ZT,mkdirSync as QT,readFileSync as ev,writeFileSync as tv}from"node:fs";import{homedir as rv}from"node:os";import{dirname as nv,join as sv}from"node:path";function Js(){return process.env.LMCTL_DEVICE_AUTH_PATH??sv(rv(),".lmctl","device-auth.json")}function iv(){return process.env.LMCTL_TOKEN_PATH??sv(rv(),".lmctl","cli-tokens.json")}function om(t=Js()){try{let e=JSON.parse(ev(t,"utf8"));return typeof e.userId!="string"||e.userId===""||typeof e.refreshToken!="string"||e.refreshToken===""?null:{userId:e.userId,refreshToken:e.refreshToken}}catch{return null}}function ov(t,e=Js()){QT(nv(e),{recursive:!0,mode:448}),tv(e,JSON.stringify(t,null,2));try{ZT(e,384)}catch{}}function am(t,e=iv()){let r={};try{r=JSON.parse(ev(e,"utf8"))}catch{}let n={...r.cognito??{}};n.idToken=t.idToken,t.accessToken!==void 0&&(n.accessToken=t.accessToken),t.refreshToken!==void 0&&(n.refreshToken=t.refreshToken),t.expiresAt!==void 0&&(n.expiresAt=t.expiresAt);let s={...r,cognito:n};QT(nv(e),{recursive:!0,mode:448}),tv(e,JSON.stringify(s,null,2));try{ZT(e,384)}catch{}}async function av(t){let e=t.deviceAuthPath??Js(),r=om(e);if(r===null)throw new Error("device_auth_not_found: no ~/.lmctl/device-auth.json; run `lmctl device login` first");let n=await Ca({region:t.region,clientId:t.clientId,refreshToken:r.refreshToken,...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}});return am({idToken:n.idToken,...n.accessToken!==void 0?{accessToken:n.accessToken}:{},refreshToken:r.refreshToken,...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{}},t.cliTokensPath??iv()),{idToken:n.idToken,userId:r.userId}}var lm=E(()=>{"use strict";im()});import{existsSync as PF,realpathSync as FF}from"node:fs";import{dirname as UF}from"node:path";function dm(t){WF(t).catch(e=>{t.log?.(`[mailbox] prompt trigger failed: ${e instanceof Error?e.message:String(e)}`)})}async function WF(t){let e=t.payload.root_teamfile;try{e=FF(t.payload.root_teamfile)}catch(i){let o=`prompt root missing/unreadable: ${t.payload.root_teamfile}: ${i instanceof Error?i.message:String(i)}`;return Fn({rootTeamfile:t.payload.root_teamfile,receiverTeamfile:t.payload.root_teamfile,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:o,reason:"root_unavailable"}),t.log?.(`[mailbox] ${o}`),{status:"error",response:null,error_detail:o}}if(t.store.getRootTeam(e)===null){let i=`prompt root is not registered: ${e}`;return Fn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:i,reason:"root_unregistered"}),t.log?.(`[mailbox] ${i}`),{status:"error",response:null,error_detail:i}}let r=BF(e);if("error"in r)return Fn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:r.error,reason:"root_invalid"}),t.log?.(`[mailbox] ${r.error}`),{status:"error",response:null,error_detail:r.error};let n=ar(t.store,{receiver_teamfile:e,receiver_alias:r.alias,sender_teamfile:`prompt:${t.payload.prompt_id}`,sender_alias:"operator",ttlMs:GF(t.env??process.env)});if(!n.acquired){let i=JF(r.alias,n.current);return Fn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:i,reason:"unavailable"}),t.log?.(`[mailbox] prompt rejected: ${i}`),{status:"error",response:null,error_detail:i}}let s=sn(i=>t.store.heartbeatAgentInflight(n.lease,n.leaseId,i),{intervalMs:_i(t.env??process.env)});try{let o=await(t.chat??Rt)({provider:r.provider,sessionId:r.sessionid,cwd:r.sessiondir,prompt:t.payload.text,env:t.env??process.env,alias:r.alias,permissionMode:"yolo",...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}}),a=o.status==="stalled",l=!a&&o.text.trim()==="",d=a?`provider stalled${o.stalledAfterMs!==void 0?` after ${o.stalledAfterMs}ms`:""}`:l?"provider returned empty response":null,c=a||l?"error":"ok";return c==="ok"?await HF(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,response:o.text,status:c,error_detail:null,log:t.log}):Fn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:d??"provider failed",reason:a?"stalled":"empty_response"}),{status:c,response:c==="error"?null:o.text,error_detail:d}}catch(i){let o=i instanceof Error?i.message:String(i);return Fn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:o,reason:"provider_error"}),t.log?.(`[mailbox] prompt provider error: ${o}`),{status:"error",response:null,error_detail:o}}finally{clearInterval(s);try{t.store.releaseAgentInflight(n.lease)}catch(i){t.log?.(`[mailbox] failed to release prompt in-flight slot: ${i instanceof Error?i.message:String(i)}`)}}}function Fn(t){C({event:"prompt_trigger_error",reason:t.reason,prompt_id:t.promptId,root_teamfile:t.rootTeamfile,sender_teamfile:t.rootTeamfile,sender_alias:"operator",receiver_teamfile:t.receiverTeamfile,receiver_alias:t.receiverAlias,error_detail:t.detail,message_preview:qF(t.message)})}function qF(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function BF(t){if(!PF(t))return{error:`prompt root missing/unreadable: ${t}`};let e=rt(t);if(e.parseErrors.length>0)return{error:`prompt root parse error: ${e.parseErrors.join("; ")}`};let r=Dt(e);return r===void 0?{error:`prompt root has no Lead: ${t}`}:r.session===void 0||r.session.trim()===""?{error:`prompt root Lead is unseeded: ${t}`}:{alias:r.alias,provider:r.provider,sessionid:r.session,sessiondir:r.sessiondir??UF(t)}}async function HF(t,e){let r=cv(e.message),n=e.response===null?null:cv(e.response);try{t.insertTeamChatLog({root_teamfile:e.rootTeamfile,sender_teamfile:e.rootTeamfile,sender_alias:"operator",receiver_teamfile:e.receiverTeamfile,receiver_alias:e.receiverAlias,message:r.text,response:n?.text??null,origin:"unknown",status:e.status,error_detail:e.error_detail,truncated:r.truncated||n?.truncated?1:0,created_at:new Date().toISOString()})}catch(s){e.log?.(`[mailbox] warning: failed to record prompt chat log: ${s instanceof Error?s.message:String(s)}`)}}function cv(t){return t.length<=lv?{text:t,truncated:!1}:{text:t.slice(0,lv),truncated:!0}}function XF(t,e){return`${t} is servicing ${e.sender_alias} (${e.sender_teamfile}) since ${e.started_at}`}function JF(t,e){return e.sender_teamfile.startsWith("prompt:")?`${t} is busy servicing another prompt since ${e.started_at}`:XF(t,e)}function GF(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return dv;let r=Number(e);return!Number.isFinite(r)||r<=0?dv:r}var lv,dv,uv=E(()=>{"use strict";Lt();tr();me();lr();lv=256*1024,dv=30*60*1e3});import{chmodSync as gv,existsSync as VF,mkdirSync as yv,readFileSync as Pa,writeFileSync as Ev}from"node:fs";import{dirname as cm,resolve as Ma,join as wv}from"node:path";import{fileURLToPath as KF}from"node:url";import{homedir as Tv}from"node:os";import{CognitoIdentityClient as YF,GetIdCommand as zF}from"@aws-sdk/client-cognito-identity";import{fromCognitoIdentity as mv}from"@aws-sdk/credential-provider-cognito-identity";import{GetObjectCommand as ZF,ListObjectsV2Command as QF,PutObjectCommand as e1,S3Client as fv}from"@aws-sdk/client-s3";function Vs(t={}){let e=t.env??process.env,r=t.tfstatePath!==void 0?[t.tfstatePath]:i1(t.selfUrl),n={},s;for(let A of r)if(VF(A)){n=s1(A),s=A;break}let i=(...A)=>{for(let N of A)if(typeof N=="string"&&N!=="")return N},o=i(e.LMCTL_NEXT_IDENTITY_POOL_ID,n.LMCTL_NEXT_IDENTITY_POOL_ID)??t1,a=i(e.LMCTL_NEXT_COGNITO_USER_POOL_ID,n.LMCTL_NEXT_COGNITO_USER_POOL_ID)??r1,l=i(e.LMCTL_NEXT_MAILBOX_BUCKET,e.LMCTL_NEXT_POLICY_BUCKET,n.LMCTL_NEXT_MAILBOX_BUCKET,n.LMCTL_NEXT_POLICY_BUCKET)??n1,d=i(e.AWS_REGION,e.AWS_DEFAULT_REGION)??"us-east-1",c=i(e.LMCTL_NEXT_COGNITO_CLIENT_ID,n.LMCTL_NEXT_COGNITO_CLIENT_ID)??Fa,u=[];o===void 0&&u.push("LMCTL_NEXT_IDENTITY_POOL_ID"),a===void 0&&u.push("LMCTL_NEXT_COGNITO_USER_POOL_ID"),l===void 0&&u.push("LMCTL_NEXT_MAILBOX_BUCKET");let f={missing:u,tfstateCandidatesChecked:r,...s!==void 0?{tfstatePathUsed:s}:{}};if(u.length>0)return f;let m=e.LMCTL_MAILBOX_POLL_MS,p=m!==void 0&&m.length>0?Number(m):void 0,h=ja(e.LMCTL_MAILBOX_READ_INTERVAL_SECONDS),g=ja(e.LMCTL_MAILBOX_HEARTBEAT_IDLE_SECONDS),_=ja(e.LMCTL_MAILBOX_BACKOFF_READ_INTERVAL_SECONDS),y=ja(e.LMCTL_MAILBOX_CHATLOG_POLL_SECONDS),T=i(e.LMCTL_MAILBOX_KEY),S=i(e.LMCTL_TOKEN_PATH);return f.config={identityPoolId:o,cognitoUserPoolId:a,cognitoClientId:c,region:d,mailboxBucket:l,...typeof p=="number"&&Number.isFinite(p)&&p>=100?{pollIntervalMs:p}:{},...h!==void 0?{readIntervalMs:h}:{},...g!==void 0?{heartbeatIdleMs:g}:{},..._!==void 0?{backoffReadIntervalMs:_}:{},...y!==void 0?{chatLogPollIntervalMs:y}:{},...T!==void 0?{mailboxKey:T}:{},...S!==void 0?{tokenPath:S}:{}},f}function s1(t){try{let e=Pa(t,"utf8"),n=JSON.parse(e).outputs??{},s={};for(let[i,o]of Object.entries(n))o!==null&&typeof o=="object"&&typeof o.value=="string"&&(s[i]=o.value);return s}catch{return{}}}function i1(t){let e=cm(KF(t??import.meta.url));return[Ma(e,"..","..","..","..","infra","terraform","terraform.tfstate"),Ma(e,"..","..","..","..","..","infra","terraform","terraform.tfstate"),Ma(e,"..","..","..","infra","terraform","terraform.tfstate"),Ma(e,"..","..","infra","terraform","terraform.tfstate")]}function ja(t){if(t===void 0||t==="")return;let e=Number(t);if(!(!Number.isFinite(e)||e<=0))return e*1e3}function o1(t){let e=a1(t.intervalMs)??vv,r=Math.max(1,Math.trunc(t.limit??500)),n=t.now??Date.now,s=t.cursorKey!==void 0&&t.store.loadTeamChatLogCursor!==void 0&&t.store.saveTeamChatLogCursor!==void 0?{key:t.cursorKey,load:t.store.loadTeamChatLogCursor.bind(t.store),save:t.store.saveTeamChatLogCursor.bind(t.store)}:null,i,o=!1,a=!1,l=()=>{try{if(s!==null){let u=s.load(s.key);if(u!==null)return i=u.last_pushed_id,!0}return i=t.store.getMaxTeamChatLogId(),s!==null&&s.save({cursor_key:s.key,last_pushed_id:i,updated_at:new Date(n()).toISOString()}),!0}catch(u){return t.log?.(`[mailbox] daemon_event chat_log seed failed: ${u instanceof Error?u.message:String(u)}`),!1}};l();let d=async()=>{if(!(a||o)){o=!0;try{if(i===void 0&&!l())return;let u=t.store.listTeamChatLogSinceId(i,r);for(let f of u){let m={kind:"daemon_event",event:"chat_log",ts:n(),entry:{id:f.id,root_teamfile:f.root_teamfile,sender_teamfile:f.sender_teamfile,sender_alias:f.sender_alias,receiver_teamfile:f.receiver_teamfile,receiver_alias:f.receiver_alias,message:f.message,response:f.response,status:f.status,created_at:f.created_at}};await t.publishDaemonEvent(m),s!==null&&s.save({cursor_key:s.key,last_pushed_id:f.id,updated_at:new Date(n()).toISOString()}),i=Math.max(i,f.id)}}catch(u){t.log?.(`[mailbox] daemon_event chat_log tail failed: ${u instanceof Error?u.message:String(u)}`)}finally{o=!1}}},c=setInterval(()=>{d()},e);return typeof c.unref=="function"&&c.unref(),{pollNow:d,stop(){a=!0,clearInterval(c)}}}function a1(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}async function Sv(t){let e=t.tokenPath??wv(Tv(),".lmctl","cli-tokens.json"),r=_v(t.tokenPath);if(YT(r.cognito?.idToken)&&om()!==null)try{await av({region:t.region,clientId:t.cognitoClientId??Fa,cliTokensPath:e}),r=_v(t.tokenPath),t.log?.("[mx-mailbox] refreshed IdToken from device-auth refresh token")}catch(R){let Z=R instanceof Error?R.message:String(R);t.log?.(`[mx-mailbox] device-auth refresh failed: ${Z}`)}if(r.cognito===void 0)throw new Error("agent_mailbox_not_logged_in: ~/.lmctl/cli-tokens.json has no cognito tokens; run `webcli login` or `lmctl device login` first");let n=r.cognito.idToken;if(typeof n!="string"||n==="")throw new Error("agent_mailbox_no_id_token: cli-tokens.json's cognito.idToken is empty; run `webcli login` or `lmctl device login` first");let s=`cognito-idp.${t.region}.amazonaws.com/${t.cognitoUserPoolId}`,i=r.cognito.identityId,o=!1;i===void 0||i===""?i=await hv({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}):(o=!0,t.log?.(`[mx-mailbox] using cached identityId from cli-tokens (skipping GetId) for ${i}`));let a=mv({identityId:i,logins:{[s]:n},clientConfig:{region:t.region}}),l=new fv({region:t.region,credentials:a}),d={ListObjectsV2Command:QF,GetObjectCommand:ZF,PutObjectCommand:e1},c=Xs(n),u=c??i,f=t.deviceId,m=On({identityId:i,userId:c,deviceId:f,mailboxKey:t.mailboxKey}),p=t.cursorStore,h;if(p!==void 0){let R=p.loadMailboxCursor(u,m);if(R!==null)h=R.last_processed_seq??void 0,t.log?.(`[mx-mailbox] resumed seq cursor=${h??"(sentinel)"} for user_id=${u}`);else{let Z=!1,B=0;for(;!Z&&B<2;){B+=1;try{let b=ea(m,"web"),I=0,L;do{let W=await l.send(new d.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:b,MaxKeys:1e3,...L!==void 0?{ContinuationToken:L}:{}}));for(let j of W.Contents??[]){let D=ta(j.Key??"",m,"web");D!==void 0&&D>I&&(I=D)}L=W.IsTruncated===!0?W.NextContinuationToken:void 0}while(L!==void 0);h=I,t.log?.(`[mx-mailbox] cold start: seeded seq cursor=${I} for user_id=${u}`),Z=!0}catch(b){let I=b instanceof Error?b.message:String(b);if(o&&B===1&&c1(b)){t.log?.(`[mx-mailbox] cached identityId rejected by cognito (${I}); clearing + refreshing`),d1(e),o=!1,i=await hv({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}),a=mv({identityId:i,logins:{[s]:n},clientConfig:{region:t.region}}),l=new fv({region:t.region,credentials:a}),m=On({identityId:i,userId:c,deviceId:f,mailboxKey:t.mailboxKey});continue}t.log?.(`[mx-mailbox] cold start seq probe failed: ${I}`);break}}p.saveMailboxCursor({user_id:u,mailbox_key:m,last_processed_version_id:null,last_processed_seq:h??null,last_processed_at:new Date().toISOString()})}}let g=null,_=t.terminalSessionManager,y=t.persistentSessionManager,T=t.promptTriggerStore,S=new Oa,A=new Hr({bucket:t.mailboxBucket,identityId:i,...c!==null?{userId:c}:{},...f!==void 0?{deviceId:f}:{},...t.mailboxKey!==void 0?{mailboxKey:t.mailboxKey}:{},s3:l,commands:d,selfRole:"agent",onS3Op:R=>S.record(R),onMessage:async R=>{if(_!==void 0&&Zu(R.payload)){_.onInbound(R.payload);return}if(y!==void 0&&Qu(R.payload)){await y.onInbound(R.payload);return}if(!tm(R.payload)){if(T!==void 0&&rm(R.payload)){dm({store:T,payload:R.payload,log:t.log});return}g!==null&&await g.handleIncoming(R.payload,R)}},...p!==void 0?{onCursorAdvance:R=>{p.saveMailboxCursor({user_id:u,mailbox_key:m,last_processed_version_id:null,last_processed_seq:R,last_processed_at:new Date().toISOString()})}}:{},...h!==void 0?{cursor:h}:{},...t.pollIntervalMs!==void 0?{pollIntervalMs:t.pollIntervalMs}:{},...t.readIntervalMs!==void 0?{readIntervalMs:t.readIntervalMs}:{},...t.heartbeatIdleMs!==void 0?{heartbeatIdleMs:t.heartbeatIdleMs}:{},...t.backoffReadIntervalMs!==void 0?{backoffReadIntervalMs:t.backoffReadIntervalMs}:{}});g=new Hs({client:A,...t.log!==void 0?{log:t.log}:{}}),_!==void 0&&_.setPublish(async R=>A.putMessage({conversation_id:`terminal:${R.session_id}`,payload:R})),y!==void 0&&y.setPublish(async R=>A.putMessage({conversation_id:`provider:${R.session_id}`,payload:R}));let N=R=>A.putMessage({conversation_id:em,payload:R});A.start();let F=t.chatLogTailStore===void 0?void 0:o1({store:t.chatLogTailStore,publishDaemonEvent:N,cursorKey:m,intervalMs:t.chatLogPollIntervalMs??t.readIntervalMs??t.pollIntervalMs??vv,log:t.log});t.log?.(`[mx-mailbox] agent polling ${m} (bucket=${t.mailboxBucket})`);let Se=t.deviceId??i,q=`${u}/usage/`,U;return U=t.usageStore===void 0?void 0:WT({meter:S,store:t.usageStore,userId:u,deviceId:Se,ceilingUsd:t.usageQuotaUsd??1/0,onQuotaExceeded:({period:R,costUsd:Z,ceilingUsd:B})=>{t.log?.(`[usage] month ${R} cost $${Z.toFixed(4)} >= ceiling $${B} \u2014 blocking mailbox`),A.stop().catch(()=>{}),U?.stop()},publishOwnRollup:async(R,Z)=>{await l.send(new d.PutObjectCommand({Bucket:t.mailboxBucket,Key:`${q}${Se}-${R}.json`,Body:JSON.stringify({...Z,updated_at:new Date().toISOString()}),ContentType:"application/json"}))},readUserTotal:async R=>{let Z={put:0,get:0,list:0},B;do{let b=await l.send(new d.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:q,MaxKeys:1e3,...B!==void 0?{ContinuationToken:B}:{}}));for(let I of b.Contents??[]){let L=I.Key??"";if(L.endsWith(`-${R}.json`))try{let W=await l.send(new d.GetObjectCommand({Bucket:t.mailboxBucket,Key:L}));if(W.Body===void 0)continue;let j=JSON.parse(await W.Body.transformToString("utf-8"));Z.put+=j.put??0,Z.get+=j.get??0,Z.list+=j.list??0}catch{}}B=b.IsTruncated===!0?b.NextContinuationToken:void 0}while(B!==void 0);return Z},intervalMs:t.usageFlushIntervalMs??36e5,...t.log!==void 0?{log:t.log}:{}}),{identityId:i,mailbox:A,fetchClient:g,publishDaemonEvent:N,async stop(){F?.stop(),U!==void 0&&(await U.flushNow().catch(()=>{}),U.stop()),await g.stop().catch(()=>{}),await A.stop().catch(()=>{})}}}async function bv(t){let e=t.s3!==void 0&&t.commands!==void 0?{s3:t.s3,commands:t.commands}:La(t.rootDir),r=On({identityId:Gs,userId:Gs,deviceId:pv}),n=null,s=t.terminalSessionManager,i=t.persistentSessionManager,o=t.promptTriggerStore,a=new Hr({bucket:"local",identityId:Gs,userId:Gs,deviceId:pv,s3:e.s3,commands:e.commands,selfRole:"agent",onMessage:async d=>{if(s!==void 0&&Zu(d.payload)){s.onInbound(d.payload);return}if(i!==void 0&&Qu(d.payload)){await i.onInbound(d.payload);return}if(!tm(d.payload)){if(o!==void 0&&rm(d.payload)){dm({store:o,payload:d.payload,log:t.log});return}n!==null&&await n.handleIncoming(d.payload,d)}},pollIntervalMs:t.pollIntervalMs??Da,readIntervalMs:t.readIntervalMs??Da,heartbeatIdleMs:t.heartbeatIdleMs??Da,backoffReadIntervalMs:t.backoffReadIntervalMs??Da});n=new Hs({client:a,...t.log!==void 0?{log:t.log}:{}}),s!==void 0&&s.setPublish(async d=>a.putMessage({conversation_id:`terminal:${d.session_id}`,payload:d})),i!==void 0&&i.setPublish(async d=>a.putMessage({conversation_id:`provider:${d.session_id}`,payload:d}));let l=d=>a.putMessage({conversation_id:em,payload:d});return a.start(),t.log?.(`[local-webui] agent polling ${r} (local-fs ${t.rootDir})`),{identityId:Gs,mailbox:a,fetchClient:n,publishDaemonEvent:l,async stop(){await n.stop().catch(()=>{}),await a.stop().catch(()=>{})}}}function _v(t){let e=t??wv(Tv(),".lmctl","cli-tokens.json");try{let r=Pa(e,"utf8");return JSON.parse(r)}catch{return{}}}function l1(t,e){if(e===void 0||e==="")return;let r={};try{let s=Pa(t,"utf8");r=JSON.parse(s)}catch{}if(r.cognito===void 0)return;let n={...r,cognito:{...r.cognito,identityId:e}};yv(cm(t),{recursive:!0,mode:448}),Ev(t,JSON.stringify(n,null,2));try{gv(t,384)}catch{}}function d1(t){let e={};try{let n=Pa(t,"utf8");e=JSON.parse(n)}catch{return}if(e.cognito===void 0)return;let r={...e,cognito:{...e.cognito}};delete r.cognito.identityId,yv(cm(t),{recursive:!0,mode:448}),Ev(t,JSON.stringify(r,null,2));try{gv(t,384)}catch{}}async function hv(t){t.log?.("[mx-mailbox] cli-tokens has no identityId; calling GetId");let r=await new YF({region:t.region}).send(new zF({IdentityPoolId:t.identityPoolId,Logins:{[t.idpProvider]:t.idToken}}));if(r.IdentityId===void 0||r.IdentityId==="")throw new Error("cognito_getid_no_identity_id");try{l1(t.tokenPath,r.IdentityId),t.log?.(`[mx-mailbox] persisted identityId=${r.IdentityId} to ${t.tokenPath}`)}catch(n){let s=n instanceof Error?n.message:String(n);t.log?.(`[mx-mailbox] WARNING: identityId persist failed (${s}); will redo GetId on next restart`)}return r.IdentityId}function c1(t){if(t===null||typeof t!="object")return!1;let e=t,r=[typeof e.name=="string"?e.name:void 0,typeof e.Code=="string"?e.Code:void 0,typeof e.__type=="string"?e.__type:void 0];for(let s of r)if(s!==void 0&&(s==="NotAuthorizedException"||s==="ResourceNotFoundException"||s==="InvalidIdentityPoolConfigurationException"||s==="ExpiredTokenException"))return!0;let n=typeof e.message=="string"?e.message:"";return!!(n.includes("NotAuthorizedException")||n.includes("Invalid identity pool configuration")||n.includes("Identity")&&n.includes("not found"))}var vv,Da,Fa,t1,r1,n1,Gs,pv,um=E(()=>{"use strict";ia();Gu();Yu();qT();HT();XT();JT();GT();nm();ra();sm();lm();uv();vv=3e3,Da=1e3,Fa="79u5jhkk46qofog661c9i0bdcs",t1="us-east-1:69636ff0-e008-4cbc-853d-180e5526a198",r1="us-east-1_4iUdFggDn",n1="lmctl-next-preview-mailbox-254332045686";Gs="local",pv="local"});import{spawn as _m}from"node:child_process";import{createInterface as Iv}from"node:readline";var mm,fm,pm,kv,Nv=E(()=>{"use strict";$i();me();mm=class{child;ctx;rl;nextRpcId=1;pending=new Map;threadId;nextLocalTurnId=1;closed=!1;setResumeThreadId(e){this.threadId=e}async start(e,r){this.ctx=r;let n=_m(e.command,e.args,{cwd:e.cwd??process.cwd(),env:e.env??process.env,stdio:["pipe","pipe","pipe"]});if(this.child=n,this.rl=Iv({input:n.stdout}),this.rl.on("line",s=>{r.generation===r.currentGeneration()&&this.handleLine(s)}),n.stderr?.on("data",s=>{if(r.generation!==r.currentGeneration())return;let i=s instanceof Buffer?s.toString("utf8"):String(s);r.emit({event_type:"notification",payload:{source:"stderr",text:i}})}),await this.rpc("initialize",{clientInfo:{name:"lmctl-dt3",title:"lmctl DT-3",version:"0.1.0"},capabilities:{experimentalApi:!1}}),this.notify("initialized",{}),this.threadId!==void 0&&this.threadId!=="")try{await this.rpc("thread/resume",{threadId:this.threadId,approvalPolicy:"never",sandbox:"danger-full-access"}),r.emit({event_type:"thread_started",payload:{thread_id:this.threadId,resumed:!0}})}catch{let i=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,o=typeof i?.id=="string"?i.id:void 0;this.threadId=o,r.emit({event_type:"thread_started",payload:{thread_id:o,resumed:!1}})}else{let i=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,o=typeof i?.id=="string"?i.id:void 0;this.threadId=o,r.emit({event_type:"thread_started",payload:{thread_id:o,resumed:!1}})}return n}async sendTurn(e){if(this.closed)throw new Error("codex_session_closed");if(this.threadId===void 0||this.threadId==="")throw new Error("codex_no_thread_id");let r=`local-${this.nextLocalTurnId++}`;this.ctx?.turnMap.set(r,{startedAt:Date.now()});try{let s=(await this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}]})).result?.turn,i=typeof s?.id=="string"?s.id:void 0;if(i!==void 0){let o=this.ctx?.turnMap.get(r);this.ctx?.turnMap.delete(r),o!==void 0&&this.ctx?.turnMap.set(i,o)}}catch(n){throw this.ctx?.turnMap.delete(r),n}}async stop(){if(this.closed=!0,this.rl!==void 0&&(this.rl.close(),this.rl=void 0),this.child?.stdin!==null&&this.child?.stdin?.end!==void 0)try{this.child.stdin.end()}catch{}for(let e of this.pending.values())e.reject(new Error("codex_session_stopping"));this.pending.clear()}async rpc(e,r){if(this.child?.stdin===null||this.child===void 0)throw new Error("codex_child_unavailable");return new Promise((n,s)=>{let i=this.nextRpcId++;this.pending.set(i,{resolve:n,reject:s});let o=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:r});try{this.child.stdin.write(o+`
|
|
2320
|
+
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var ve,rF,nF,Na,wt=E(()=>{"use strict";tr();rr();ve=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}},rF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,nF=/^ses_[A-Za-z0-9_-]+$/,Na=/^[A-Za-z][A-Za-z0-9_-]*$/});function Aa(t){return oF.has(t)}function Uu(){return Fu===null&&(Fu=Nt(xt())),Fu}function Wu(t,e,r={}){if(!Aa(t))return null;try{let n=Uu().getAdapter?.(t);if(n===void 0)return null;let s=n.resumeCommand(e).trim();if(s.length===0)return null;let i=s.split(/\s+/),o=t==="codex"&&r.isLead===!0?Ri({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?iF[t]?.(r.model):void 0;return r.model!==void 0&&r.model.trim().length>0&&a===void 0&&r.onModelIgnored?.({provider:t,model:r.model,reason:`${t} terminal resume does not implement per-session model selection`}),[...i,...a??[],...o,...TT[t]??[]]}catch{return null}}function xa(t,e,r={}){let n=Wu(t,e,r);return n===null?null:n.join(" ")}function Be(t,e){return Uu().getSession(t,e)}async function Pn(t){return(await Uu().resolveSessions(t)).map(r=>r.provider.name)}var TT,iF,oF,vT,Fu,nr=E(()=>{"use strict";Lt();Yl();TT={claude:["--dangerously-skip-permissions"],codex:["--dangerously-bypass-approvals-and-sandbox"],gemini:["-y"],copilot:["--yolo"],opencode:[],qwen:["--approval-mode","yolo"],agy:[],lmplayer:[]},iF={claude:t=>["--model",t],codex:t=>["--model",t],gemini:t=>["--model",t],opencode:t=>["--model",t],qwen:t=>["--model",t],agy:t=>["--model",t],lmplayer:t=>["--model",t]},oF=new Set(Object.keys(TT)),vT=/^[\w.:-]+$/;Fu=null});function aF(t=process.env){let e=t.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return ST;let r=Number(e);return!Number.isFinite(r)||r<=0?ST:r}async function lF(t,e,r){try{let n=De(e,r,t),s=n.sessionid;if(typeof s!="string"||s.trim()===""||s===".")return null;let i;if(typeof n.provider=="string"&&n.provider.trim()!=="")i=n.provider;else{let d=await Pn(s);if(d.length!==1)return null;i=d[0]}let o=await Be(s,i);if(o===null)return null;let a=o.modifiedAt;if(!(a instanceof Date))return null;let l=a.getTime();return Number.isFinite(l)?Date.now()-l:null}catch{return null}}async function Ra(t,e,r,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??aF(),o=await lF(t,r,n),a=o!==null&&o>=i;return a&&C({event:"session_idle_reclaim",receiver_teamfile:r,receiver_alias:n,idle_ms:o,idle_minutes:o===null?null:Math.round(o/6e4),threshold_ms:i,reason:"in-flight holder idle past session-idle threshold; lease will be force-reclaimed"}),a}var ST,qu=E(()=>{"use strict";me();nr();wt();ST=36e5});function dF(t=process.env){let e=t.LMCTL_DAEMON_MAILBOX_RELAY_MAX_BATCHES;if(e===void 0||e.trim()==="")return bT;let r=Number(e);return!Number.isFinite(r)||r<=0?bT:Math.max(1,Math.trunc(r))}async function kT(t){let e=t.env??process.env,r=t.maxBatches??dF(e),n=hF(t.dal),s={scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0};_F(t.dal,e);let i=new Set;for(;s.scanned<r;){let o=t.dal.listRelayMailboxLanes(r).find(l=>!i.has(IT(l)));if(o===void 0)break;i.add(IT(o)),s.scanned+=1;let a=await cF(t.dal,n,e,o);s.delivered+=a.delivered,s.skipped_busy+=a.skipped_busy,s.skipped_terminal+=a.skipped_terminal,s.errors+=a.errors}return s}function IT(t){return JSON.stringify([t.sender_teamfile,t.sender_alias,t.receiver_teamfile,t.receiver_alias])}async function cF(t,e,r,n){let s={scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0},i=Wt(t,n.receiver_teamfile,n.receiver_alias),o=!1;if(i.busy){if(!await Ra(t,i,n.receiver_teamfile,n.receiver_alias))return i.reason==="terminal-held"?{...s,skipped_terminal:1}:{...s,skipped_busy:1};o=!0}let a=null,l=null;try{let d=De(n.receiver_teamfile,n.receiver_alias,t),c=ar(t,{receiver_teamfile:n.receiver_teamfile,receiver_alias:n.receiver_alias,sender_teamfile:n.sender_teamfile,sender_alias:n.sender_alias,ttlMs:br(),...o?{force:!0}:{}});if(!c.acquired)return{...s,skipped_busy:1};if(a={row:c.lease,leaseId:c.leaseId},l=sn(f=>t.heartbeatAgentInflight(a.row,a.leaseId,f),{intervalMs:_i(r)}),n.message_type==="response"){let f=await nT({sender:{teamfile:n.sender_teamfile,alias:n.sender_alias},receiver:{teamfile:n.receiver_teamfile,alias:n.receiver_alias,provider:d.provider,sessionId:d.sessionid,cwd:d.sessiondir,...d.model!==void 0?{model:d.model}:{},...d.effort!==void 0?{effort:d.effort}:{},...d.isLead!==void 0?{isLead:d.isLead}:{}},io:e,permissionMode:"yolo",env:r});return fF(f)}let u=await Ea({sender:{teamfile:n.sender_teamfile,alias:n.sender_alias},receiver:{teamfile:n.receiver_teamfile,alias:n.receiver_alias,provider:d.provider,sessionId:d.sessionid,cwd:d.sessiondir,...d.model!==void 0?{model:d.model}:{},...d.effort!==void 0?{effort:d.effort}:{},...d.isLead!==void 0?{isLead:d.isLead}:{}},io:e,permissionMode:"yolo",env:r,finalize:"caller"});return mF(t,u)}catch(d){return uF(t,n,`relay delivery error: ${d instanceof Error?d.message:String(d)}`)}finally{if(l!==null&&clearInterval(l),a!==null)try{t.releaseAgentInflight(a.row,a.leaseId)}catch{}}}function uF(t,e,r){let n={scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0};try{let s=e.message_type==="response"?t.listEnqueuedResponseMailFromSender(e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias):t.listEnqueuedRequestMailFromSender(e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias),i=e.message_type==="response"?t.markMailDelivered(s.map(o=>o.id),r,new Date().toISOString()):t.markRelayRequestDeliveredAndEnqueueResponses(s,r,new Date().toISOString()).marked;return{...n,delivered:i,errors:1}}catch{return{...n,errors:1}}}function mF(t,e){let r={scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0},n=pF(e),s=new Date().toISOString(),{marked:i}=t.markRelayRequestDeliveredAndEnqueueResponses(e.queued,n,s);return{...r,delivered:i,errors:e.status==="ok"?0:1}}function fF(t){return{...{scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0},delivered:t.deliveredIds.length,errors:t.status==="ok"?0:1}}function pF(t){return t.status==="ok"?t.receipt:t.status==="stalled"?`relay delivery error: provider stalled${t.stalledAfterMs!==void 0?` after ${t.stalledAfterMs}ms`:""}
|
|
2321
|
+
${t.receipt}`:`relay delivery error: ${t.error}`}function _F(t,e){t.reclaimStaleMailboxDeliveries(new Date(Date.now()-Au(e)).toISOString())}function hF(t){return{stdout:{write:()=>{}},stderr:{write:()=>{}},dal:t}}var bT,NT=E(()=>{"use strict";lr();xu();Ta();wt();qu();bT=10});function Bs(){let t=process.env.LMCTL_DAEMON_INTERVAL_MS;if(t===void 0||t.trim().length===0)return 5e3;let e=Number(t);return Number.isFinite(e)&&e>0?e:5e3}function yF(t=process.env){let e=t.LMCTL_DAEMON_FEATURES;if(e===void 0)return new Set(["mailbox-relay"]);if(e.trim()==="")return new Set;let r=new Set;for(let n of e.split(",")){let s=n.trim();if(s!==""){if(s==="all")return new Set(AT);gF.has(s)&&r.add(s)}}return r}function xT(t){let e=t.intervalMs??Bs(),r=t.runOnceFn??Br,n=new Set(t.features??yF()),s={running:t.autoStart!==!1,in_flight:!1,interval_ms:e,enabled_features:[...n].sort(),cycles:0,jobs_processed:0,last_jobs_processed:0,last_started_at:null,last_finished_at:null,last_error:null,last_session_sizes_recorded:0,last_session_size_failures:0,last_intake_scanned:0,last_intake_new_jobs:0,last_intake_failures:0,last_session_hung_detected:0,last_session_monitor_checked_at:null,last_session_monitor_error:null,last_mailbox_relay_scanned:0,last_mailbox_relay_delivered:0,last_mailbox_relay_errors:0},i=null,o=null,a=null,l=null,d=null;n.has("rollup-updater")&&t.startRollupUpdaterFn!==!1&&(d=(t.startRollupUpdaterFn??Kw)(t.dal));let c=m=>{s.running&&(i=setTimeout(()=>{f.runCycle().finally(()=>c(e))},m))},u=m=>{s.running&&(o=setTimeout(()=>{l===null&&(l=RT(t.dal,n,t.monitorSessionActivityFn??rc,e,s).finally(()=>{l=null})),l.finally(()=>u(nc(t.dal,e)))},m))},f={state:s,runCycle:async()=>(a!==null||(a=EF(t.dal,r,t.collectSessionSizesFn??yh,t.scanIntakeFn??xo,t.monitorSessionActivityFn??rc,t.mailboxRelayFn??kT,t.worker_id??"daemon",e,n,s).finally(()=>{a=null})),a),stop:async()=>{s.running=!1,i!==null&&clearTimeout(i),o!==null&&clearTimeout(o),d?.stop(),a!==null&&await a.catch(()=>{}),l!==null&&await l.catch(()=>{})}};if(s.running){let m=t.firstDelayMs??5e3;c(m),n.has("session-monitor")&&u(m)}return f}async function EF(t,e,r,n,s,i,o,a,l,d){d.in_flight=!0,d.last_started_at=new Date().toISOString(),d.last_error=null;let c=[],u=0,f=0,m=[],p=null,h=wF();try{if(l.has("durable-memory-policies")&&IE({dal:t}),l.has("drift-detectors")&&Zw({dal:t}),l.has("intake")&&(m=await n(t)),l.has("job-worker"))for(;;){let g=await e({dal:t,worker_id:o,lease_ms:6e5});if(g===null)break;c.push(g)}if(l.has("mailbox-relay")&&(h=await i({dal:t})),l.has("session-size")){let g=await r(t);u=g.recorded,f=g.failed}l.has("session-monitor")&&(p=await RT(t,l,s,a,d))}catch(g){d.last_error=g instanceof Error?g.message:String(g);try{t.raiseAttention({kind:"daemon_worker_failed",severity:"error",payload:JSON.stringify({error:d.last_error})})}catch{}}finally{d.in_flight=!1,d.cycles+=1,d.last_jobs_processed=c.length,d.last_session_sizes_recorded=u,d.last_session_size_failures=f,d.last_intake_scanned=m.reduce((g,_)=>g+_.scanned,0),d.last_intake_new_jobs=m.reduce((g,_)=>g+_.new_jobs,0),d.last_intake_failures=m.filter(g=>g.error!==void 0).length,d.last_session_hung_detected=p?.hung_detected??0,d.last_mailbox_relay_scanned=h.scanned,d.last_mailbox_relay_delivered=h.delivered,d.last_mailbox_relay_errors=h.errors,d.jobs_processed+=c.length,d.last_finished_at=new Date().toISOString()}return{jobs_processed:c.length,outcomes:c,session_sizes_recorded:u,session_size_failures:f,intake:m,session_monitor:p,mailbox_relay:h}}function wF(){return{scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0}}async function RT(t,e,r,n,s){if(!e.has("session-monitor"))return null;let i=nc(t,n),o=Date.now();if(s.last_session_monitor_checked_at!==null){let a=Date.parse(s.last_session_monitor_checked_at);if(Number.isFinite(a)&&o-a<i)return null}s.last_session_monitor_checked_at=new Date(o).toISOString(),s.last_session_monitor_error=null;try{return await r({dal:t,nowMs:o})}catch(a){s.last_session_monitor_error=a instanceof Error?a.message:String(a);try{t.raiseAttention({kind:"daemon_session_monitor_failed",severity:"error",payload:JSON.stringify({error:s.last_session_monitor_error})})}catch{}return null}}var AT,gF,Bu=E(()=>{"use strict";Nc();zo();su();to();Yw();Qw();sc();NT();AT=["durable-memory-policies","drift-detectors","intake","job-worker","mailbox-relay","session-size","session-monitor","rollup-updater"],gF=new Set(AT)});function LT(t){let e=t.listMembersInState("in_chat");for(let r of e)t.setMemberState(r.id,"attention_needed","daemon_restarted_mid_chat");return e.length}var OT=E(()=>{"use strict"});import{mkdirSync as TF,readFileSync as vF,readdirSync as SF,statSync as bF,writeFileSync as IF}from"node:fs";import{dirname as kF,join as CT,sep as $T}from"node:path";function La(t){return{s3:{async send(n){let s=n;switch(s._localfsTag){case MT:return NF(t,s.input);case DT:return AF(t,s.input);case jT:return xF(t,s.input);default:throw new Error("createLocalFsS3Client: unknown command")}}},commands:{ListObjectsV2Command:Ju,GetObjectCommand:Xu,PutObjectCommand:Hu}}}function NF(t,e){let r=PT(t,e.Key);return TF(kF(r),{recursive:!0}),IF(r,e.Body),{}}function AF(t,e){let r=PT(t,e.Key),n;try{n=vF(r)}catch(i){throw i.code==="ENOENT"?Object.assign(new Error("NoSuchKey"),{name:"NoSuchKey"}):i}let s=n.toString("utf-8");return{Body:{transformToString:async()=>s}}}function xF(t,e){let r=e.Prefix??"";FT(r);let s=RF(t).sort((c,u)=>c.key<u.key?-1:c.key>u.key?1:0).filter(c=>c.key.startsWith(r)),i=e.ContinuationToken;i!==void 0&&i!==""&&(s=s.filter(c=>c.key>i));let o=typeof e.MaxKeys=="number"&&Number.isFinite(e.MaxKeys)&&e.MaxKeys>0?Math.floor(e.MaxKeys):void 0,a=s,l=!1;o!==void 0&&s.length>o&&(a=s.slice(0,o),l=!0);let d={Contents:a.map(c=>({Key:c.key,LastModified:c.lastModified})),IsTruncated:l};return l&&(d.NextContinuationToken=a[a.length-1].key),d}function PT(t,e){return FT(e),CT(t,e)}function FT(t){if(t.split("/").includes(".."))throw new Error(`localfs-s3-client: refusing key/prefix with '..': ${t}`)}function RF(t){let e=[],r=(n,s)=>{let i;try{i=SF(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(let o of i){let a=s===""?o.name:`${s}/${o.name}`,l=CT(n,o.name);if(o.isDirectory())r(l,a);else if(o.isFile()){let d=$T==="/"?a:a.split($T).join("/");e.push({key:d,lastModified:bF(l).mtime})}}};return r(t,""),e}var MT,DT,jT,Hu,Xu,Ju,Gu=E(()=>{"use strict";MT="localfs-put",DT="localfs-get",jT="localfs-list",Hu=class{input;_localfsTag=MT;constructor(e){this.input=e}},Xu=class{input;_localfsTag=DT;constructor(e){this.input=e}},Ju=class{input;_localfsTag=jT;constructor(e){this.input=e}}});function UT(){return{put:0,get:0,list:0}}function Vu(t,e=LF){return t.put*e.putUsd+t.get*e.getUsd+t.list*e.listUsd}function Ku(t){let e=new Date(t),r=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0");return`${r}-${n}`}var LF,Oa,Yu=E(()=>{"use strict";LF={putUsd:5e-6,getUsd:40000000000000003e-23,listUsd:5e-6};Oa=class{counts=UT();record(e,r=1){this.counts[e]+=r}peek(){return{...this.counts}}drain(){let e={...this.counts};return this.counts=UT(),e}estimateCostUsd(e){return Vu(this.counts,e)}}});function WT(t){let e=t.now??Date.now,r=t.timers??OF,n=null,s=null;async function i(){let l=e(),d=Ku(l),c=t.meter.drain();(c.put>0||c.get>0||c.list>0)&&t.store.addUsage({user_id:t.userId,device_id:t.deviceId,period:d,put:c.put,get:c.get,list:c.list,updated_at:new Date(l).toISOString()});let u=t.store.loadUsage(t.userId,t.deviceId,d),f=u?{put:u.put_count,get:u.get_count,list:u.list_count}:{put:0,get:0,list:0};if(t.publishOwnRollup!==void 0)try{await t.publishOwnRollup(d,f)}catch(h){t.log?.(`[usage] publish rollup failed: ${h instanceof Error?h.message:String(h)}`)}let m=f;if(t.readUserTotal!==void 0)try{m=await t.readUserTotal(d)}catch(h){t.log?.(`[usage] read user total failed: ${h instanceof Error?h.message:String(h)}`),m=f}let p=Vu(m);if(n!==d&&p>=t.ceilingUsd){n=d,t.log?.(`[usage] quota exceeded period=${d} cost=$${p.toFixed(4)} >= ceiling $${t.ceilingUsd}`);try{t.onQuotaExceeded({period:d,costUsd:p,ceilingUsd:t.ceilingUsd})}catch(h){t.log?.(`[usage] onQuotaExceeded threw: ${h instanceof Error?h.message:String(h)}`)}}}function o(){return s=(s??Promise.resolve()).then(()=>i()).catch(()=>{}),s}let a=r.setInterval(()=>{o()},t.intervalMs);return{stop(){r.clearInterval(a)},flushNow(){return o()},isOverQuota(){return n!==null&&n===Ku(e())}}}var OF,qT=E(()=>{"use strict";Yu();OF={setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)}});var zu=E(()=>{"use strict";ra();sa();sa()});function $F(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;if(typeof e.message_id!="string"||e.message_id==="")return null;if(typeof e.reply_to=="string"&&e.reply_to!==""){let s=e.response;if(typeof s!="object"||s===null)return null;let i=s;return typeof i.status!="number"?null:{message_id:e.message_id,reply_to:e.reply_to,response:i}}let r=e.request;if(typeof r!="object"||r===null)return null;let n=r;return typeof n.method!="string"||n.method===""||typeof n.path!="string"||n.path===""?null:{message_id:e.message_id,request:n}}function CF(t){return t.reply_to!==void 0&&t.response!==void 0}function MF(t){if(typeof t!="object"||t===null)return;let e=t.conversation_id;return typeof e=="string"?e:void 0}function BT(t){let e=t.reason;if(e!==void 0)return e;try{return new DOMException("Aborted","AbortError")}catch{let r=new Error("Aborted");return r.name="AbortError",r}}var $a,Hs,HT=E(()=>{"use strict";zu();$a=class extends Error{name="MailboxFetchStoppedError";code="mailbox_fetch_stopped";constructor(e="MailboxFetchClient stopped before a response arrived"){super(e)}},Hs=class{client;log;now;random;pending=new Map;requestHandler=null;stopped=!1;constructor(e){this.client=e.client,this.log=e.log??(()=>{}),this.now=e.now??Date.now,this.random=e.random??Math.random}onRequest(e){if(this.requestHandler!==null)throw new Error("MailboxFetchClient: onRequest handler already registered");this.requestHandler=e}async fetch(e,r){if(this.stopped)throw new $a("MailboxFetchClient.fetch after stop()");if(typeof e.path!="string"||e.path==="")throw new Error("MailboxFetchClient.fetch: request.path is required");let n=e.method;if(typeof n!="string"||n==="")throw new Error("MailboxFetchClient.fetch: request.method is required");let s=Qt(this.now(),this.random);if(this.pending.has(s))throw new Error(`MailboxFetchClient.fetch: duplicate message_id=${s}`);let i=r?.conversationId??s,o={message_id:s,request:e};return new Promise((a,l)=>{let d=r?.abortSignal,c;if(d!==void 0){if(d.aborted){l(BT(d));return}c=()=>{this.pending.has(s)&&(this.pending.delete(s),l(BT(d)))},d.addEventListener("abort",c,{once:!0})}this.pending.set(s,{resolve:a,reject:l,...c!==void 0?{abortListener:c}:{},...d!==void 0?{abortSignal:d}:{}}),this.client.putMessage({conversation_id:i,payload:o}).catch(u=>{let f=this.pending.get(s);f!==void 0&&(this.pending.delete(s),f.abortListener!==void 0&&f.abortSignal!==void 0&&f.abortSignal.removeEventListener("abort",f.abortListener),f.reject(u))})})}async stop(){if(this.stopped)return;this.stopped=!0;let e=Array.from(this.pending.values());this.pending.clear();let r=new $a;for(let n of e){n.abortListener!==void 0&&n.abortSignal!==void 0&&n.abortSignal.removeEventListener("abort",n.abortListener);try{n.reject(r)}catch{}}}async handleIncoming(e,r){let n=$F(e);if(n===null){this.log("MailboxFetchClient: dropping non-envelope inbound payload");return}if(CF(n)){let l=this.pending.get(n.reply_to);if(l===void 0){this.log(`MailboxFetchClient: dropping response for unknown reply_to=${n.reply_to}`);return}this.pending.delete(n.reply_to),l.abortListener!==void 0&&l.abortSignal!==void 0&&l.abortSignal.removeEventListener("abort",l.abortListener),l.resolve(n.response);return}if(this.requestHandler===null){this.log(`MailboxFetchClient: no handler registered; dropping request message_id=${n.message_id}`);return}let s=r?.conversation_id??MF(e)??n.message_id,i;try{i=await this.requestHandler(n.request)}catch(l){let d=l instanceof Error?l.message:String(l),c=typeof l.code=="string"?l.code:"INTERNAL_ERROR";i={status:500,headers:{"content-type":"application/json"},body:{error:c,message:d}}}let a={message_id:Qt(this.now(),this.random),reply_to:n.message_id,response:i};try{await this.client.putMessage({conversation_id:s,payload:a})}catch(l){this.log(`MailboxFetchClient: response PUT failed for reply_to=${n.message_id}: ${l instanceof Error?l.message:String(l)}`)}}}});function Zu(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;return!(e.kind!=="terminal"||typeof e.session_id!="string"||e.session_id===""||e.direction!=="agent_to_user"&&e.direction!=="user_to_agent"||typeof e.data!="string"||typeof e.ts!="number")}var XT=E(()=>{"use strict"});function Qu(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;if(e.kind!=="provider"||typeof e.session_id!="string"||e.session_id===""||e.direction!=="agent_to_user"&&e.direction!=="user_to_agent"||typeof e.ts!="number")return!1;if(e.direction==="agent_to_user"){if(!Array.isArray(e.events))return!1;for(let r of e.events)if(typeof r!="object"||r===null||Array.isArray(r)||typeof r.event_type!="string")return!1}else if(typeof e.user_input!="string")return!1;return!0}var JT=E(()=>{"use strict"});function tm(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;if(e.kind!=="daemon_event"||typeof e.event!="string"||e.event===""||typeof e.ts!="number")return!1;if(e.event==="workflows"){if(!Array.isArray(e.workflows))return!1;for(let r of e.workflows){if(typeof r!="object"||r===null||Array.isArray(r))return!1;let n=r;if(typeof n.teamfile_path!="string"||n.teamfile_path===""||n.name!==null&&typeof n.name!="string"||typeof n.registered_at!="string"||n.registered_at===""||n.last_seeded_at!==null&&typeof n.last_seeded_at!="string")return!1}}else if(e.event==="chat_log"){if(typeof e.entry!="object"||e.entry===null||Array.isArray(e.entry))return!1;let r=e.entry;if(typeof r.id!="number"||typeof r.root_teamfile!="string"||r.root_teamfile===""||r.sender_teamfile!==null&&(typeof r.sender_teamfile!="string"||r.sender_teamfile==="")||r.sender_alias!==null&&(typeof r.sender_alias!="string"||r.sender_alias==="")||typeof r.receiver_teamfile!="string"||r.receiver_teamfile===""||typeof r.receiver_alias!="string"||r.receiver_alias===""||typeof r.message!="string"||r.response!==null&&typeof r.response!="string"||typeof r.status!="string"||r.status===""||typeof r.created_at!="string"||r.created_at==="")return!1}return!0}var em,GT=E(()=>{"use strict";em="daemon:events"});function KT(t){return{kind:"prompt",prompt_id:t.prompt_id??Qt(t.now?.()??Date.now(),t.random??Math.random),root_teamfile:t.root_teamfile,text:t.text}}function rm(t){if(t===null||typeof t!="object")return!1;let e=t;return e.kind==="prompt"&&typeof e.prompt_id=="string"&&e.prompt_id.length>0&&typeof e.root_teamfile=="string"&&e.root_teamfile.length>0&&typeof e.text=="string"}var VT,nm=E(()=>{"use strict";zu();VT="prompt:root"});function Xs(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(zT(e[1]));return typeof r.sub=="string"&&r.sub!==""?r.sub:null}catch{return null}}function DF(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(zT(e[1]));return typeof r.exp=="number"&&Number.isFinite(r.exp)?r.exp:null}catch{return null}}function YT(t,e=60){if(typeof t!="string"||t==="")return!0;let r=DF(t);return r===null?!0:Date.now()/1e3>=r-e}function zT(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"="),n=globalThis.Buffer;return n!==void 0?n.from(r,"base64").toString("utf8"):atob(r)}var sm=E(()=>{"use strict"});async function Ca(t){let e=t.fetchImpl??fetch,r=`https://cognito-idp.${t.region}.amazonaws.com/`,n=await e(r,{method:"POST",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":jF},body:JSON.stringify({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:t.clientId,AuthParameters:{REFRESH_TOKEN:t.refreshToken}})}),s=await n.text();if(!n.ok){let l=s;try{let d=JSON.parse(s);l=d.message??d.__type??s}catch{}throw new Error(`cognito_refresh_failed: ${n.status} ${l}`)}let o=JSON.parse(s).AuthenticationResult,a=o?.IdToken;if(typeof a!="string"||a==="")throw new Error("cognito_refresh_no_id_token: InitiateAuth returned no IdToken");return{idToken:a,...typeof o?.AccessToken=="string"&&o.AccessToken!==""?{accessToken:o.AccessToken}:{},...typeof o?.ExpiresIn=="number"&&Number.isFinite(o.ExpiresIn)?{expiresAt:Date.now()+o.ExpiresIn*1e3}:{}}}var jF,im=E(()=>{"use strict";jF="AWSCognitoIdentityProviderService.InitiateAuth"});import{chmodSync as ZT,mkdirSync as QT,readFileSync as ev,writeFileSync as tv}from"node:fs";import{homedir as rv}from"node:os";import{dirname as nv,join as sv}from"node:path";function Js(){return process.env.LMCTL_DEVICE_AUTH_PATH??sv(rv(),".lmctl","device-auth.json")}function iv(){return process.env.LMCTL_TOKEN_PATH??sv(rv(),".lmctl","cli-tokens.json")}function om(t=Js()){try{let e=JSON.parse(ev(t,"utf8"));return typeof e.userId!="string"||e.userId===""||typeof e.refreshToken!="string"||e.refreshToken===""?null:{userId:e.userId,refreshToken:e.refreshToken}}catch{return null}}function ov(t,e=Js()){QT(nv(e),{recursive:!0,mode:448}),tv(e,JSON.stringify(t,null,2));try{ZT(e,384)}catch{}}function am(t,e=iv()){let r={};try{r=JSON.parse(ev(e,"utf8"))}catch{}let n={...r.cognito??{}};n.idToken=t.idToken,t.accessToken!==void 0&&(n.accessToken=t.accessToken),t.refreshToken!==void 0&&(n.refreshToken=t.refreshToken),t.expiresAt!==void 0&&(n.expiresAt=t.expiresAt);let s={...r,cognito:n};QT(nv(e),{recursive:!0,mode:448}),tv(e,JSON.stringify(s,null,2));try{ZT(e,384)}catch{}}async function av(t){let e=t.deviceAuthPath??Js(),r=om(e);if(r===null)throw new Error("device_auth_not_found: no ~/.lmctl/device-auth.json; run `lmctl device login` first");let n=await Ca({region:t.region,clientId:t.clientId,refreshToken:r.refreshToken,...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}});return am({idToken:n.idToken,...n.accessToken!==void 0?{accessToken:n.accessToken}:{},refreshToken:r.refreshToken,...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{}},t.cliTokensPath??iv()),{idToken:n.idToken,userId:r.userId}}var lm=E(()=>{"use strict";im()});import{existsSync as PF,realpathSync as FF}from"node:fs";import{dirname as UF}from"node:path";function dm(t){WF(t).catch(e=>{t.log?.(`[mailbox] prompt trigger failed: ${e instanceof Error?e.message:String(e)}`)})}async function WF(t){let e=t.payload.root_teamfile;try{e=FF(t.payload.root_teamfile)}catch(i){let o=`prompt root missing/unreadable: ${t.payload.root_teamfile}: ${i instanceof Error?i.message:String(i)}`;return Fn({rootTeamfile:t.payload.root_teamfile,receiverTeamfile:t.payload.root_teamfile,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:o,reason:"root_unavailable"}),t.log?.(`[mailbox] ${o}`),{status:"error",response:null,error_detail:o}}if(t.store.getRootTeam(e)===null){let i=`prompt root is not registered: ${e}`;return Fn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:i,reason:"root_unregistered"}),t.log?.(`[mailbox] ${i}`),{status:"error",response:null,error_detail:i}}let r=BF(e);if("error"in r)return Fn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:r.error,reason:"root_invalid"}),t.log?.(`[mailbox] ${r.error}`),{status:"error",response:null,error_detail:r.error};let n=ar(t.store,{receiver_teamfile:e,receiver_alias:r.alias,sender_teamfile:`prompt:${t.payload.prompt_id}`,sender_alias:"operator",ttlMs:GF(t.env??process.env)});if(!n.acquired){let i=JF(r.alias,n.current);return Fn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:i,reason:"unavailable"}),t.log?.(`[mailbox] prompt rejected: ${i}`),{status:"error",response:null,error_detail:i}}let s=sn(i=>t.store.heartbeatAgentInflight(n.lease,n.leaseId,i),{intervalMs:_i(t.env??process.env)});try{let o=await(t.chat??Rt)({provider:r.provider,sessionId:r.sessionid,cwd:r.sessiondir,prompt:t.payload.text,env:t.env??process.env,alias:r.alias,permissionMode:"yolo",...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}}),a=o.status==="stalled",l=!a&&o.text.trim()==="",d=a?`provider stalled${o.stalledAfterMs!==void 0?` after ${o.stalledAfterMs}ms`:""}`:l?"provider returned empty response":null,c=a||l?"error":"ok";return c==="ok"?await HF(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,response:o.text,status:c,error_detail:null,log:t.log}):Fn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:d??"provider failed",reason:a?"stalled":"empty_response"}),{status:c,response:c==="error"?null:o.text,error_detail:d}}catch(i){let o=i instanceof Error?i.message:String(i);return Fn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:o,reason:"provider_error"}),t.log?.(`[mailbox] prompt provider error: ${o}`),{status:"error",response:null,error_detail:o}}finally{clearInterval(s);try{t.store.releaseAgentInflight(n.lease,n.leaseId)}catch(i){t.log?.(`[mailbox] failed to release prompt in-flight slot: ${i instanceof Error?i.message:String(i)}`)}}}function Fn(t){C({event:"prompt_trigger_error",reason:t.reason,prompt_id:t.promptId,root_teamfile:t.rootTeamfile,sender_teamfile:t.rootTeamfile,sender_alias:"operator",receiver_teamfile:t.receiverTeamfile,receiver_alias:t.receiverAlias,error_detail:t.detail,message_preview:qF(t.message)})}function qF(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function BF(t){if(!PF(t))return{error:`prompt root missing/unreadable: ${t}`};let e=rt(t);if(e.parseErrors.length>0)return{error:`prompt root parse error: ${e.parseErrors.join("; ")}`};let r=Dt(e);return r===void 0?{error:`prompt root has no Lead: ${t}`}:r.session===void 0||r.session.trim()===""?{error:`prompt root Lead is unseeded: ${t}`}:{alias:r.alias,provider:r.provider,sessionid:r.session,sessiondir:r.sessiondir??UF(t)}}async function HF(t,e){let r=cv(e.message),n=e.response===null?null:cv(e.response);try{t.insertTeamChatLog({root_teamfile:e.rootTeamfile,sender_teamfile:e.rootTeamfile,sender_alias:"operator",receiver_teamfile:e.receiverTeamfile,receiver_alias:e.receiverAlias,message:r.text,response:n?.text??null,origin:"unknown",status:e.status,error_detail:e.error_detail,truncated:r.truncated||n?.truncated?1:0,created_at:new Date().toISOString()})}catch(s){e.log?.(`[mailbox] warning: failed to record prompt chat log: ${s instanceof Error?s.message:String(s)}`)}}function cv(t){return t.length<=lv?{text:t,truncated:!1}:{text:t.slice(0,lv),truncated:!0}}function XF(t,e){return`${t} is servicing ${e.sender_alias} (${e.sender_teamfile}) since ${e.started_at}`}function JF(t,e){return e.sender_teamfile.startsWith("prompt:")?`${t} is busy servicing another prompt since ${e.started_at}`:XF(t,e)}function GF(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return dv;let r=Number(e);return!Number.isFinite(r)||r<=0?dv:r}var lv,dv,uv=E(()=>{"use strict";Lt();tr();me();lr();lv=256*1024,dv=30*60*1e3});import{chmodSync as gv,existsSync as VF,mkdirSync as yv,readFileSync as Pa,writeFileSync as Ev}from"node:fs";import{dirname as cm,resolve as Ma,join as wv}from"node:path";import{fileURLToPath as KF}from"node:url";import{homedir as Tv}from"node:os";import{CognitoIdentityClient as YF,GetIdCommand as zF}from"@aws-sdk/client-cognito-identity";import{fromCognitoIdentity as mv}from"@aws-sdk/credential-provider-cognito-identity";import{GetObjectCommand as ZF,ListObjectsV2Command as QF,PutObjectCommand as e1,S3Client as fv}from"@aws-sdk/client-s3";function Vs(t={}){let e=t.env??process.env,r=t.tfstatePath!==void 0?[t.tfstatePath]:i1(t.selfUrl),n={},s;for(let A of r)if(VF(A)){n=s1(A),s=A;break}let i=(...A)=>{for(let N of A)if(typeof N=="string"&&N!=="")return N},o=i(e.LMCTL_NEXT_IDENTITY_POOL_ID,n.LMCTL_NEXT_IDENTITY_POOL_ID)??t1,a=i(e.LMCTL_NEXT_COGNITO_USER_POOL_ID,n.LMCTL_NEXT_COGNITO_USER_POOL_ID)??r1,l=i(e.LMCTL_NEXT_MAILBOX_BUCKET,e.LMCTL_NEXT_POLICY_BUCKET,n.LMCTL_NEXT_MAILBOX_BUCKET,n.LMCTL_NEXT_POLICY_BUCKET)??n1,d=i(e.AWS_REGION,e.AWS_DEFAULT_REGION)??"us-east-1",c=i(e.LMCTL_NEXT_COGNITO_CLIENT_ID,n.LMCTL_NEXT_COGNITO_CLIENT_ID)??Fa,u=[];o===void 0&&u.push("LMCTL_NEXT_IDENTITY_POOL_ID"),a===void 0&&u.push("LMCTL_NEXT_COGNITO_USER_POOL_ID"),l===void 0&&u.push("LMCTL_NEXT_MAILBOX_BUCKET");let f={missing:u,tfstateCandidatesChecked:r,...s!==void 0?{tfstatePathUsed:s}:{}};if(u.length>0)return f;let m=e.LMCTL_MAILBOX_POLL_MS,p=m!==void 0&&m.length>0?Number(m):void 0,h=ja(e.LMCTL_MAILBOX_READ_INTERVAL_SECONDS),g=ja(e.LMCTL_MAILBOX_HEARTBEAT_IDLE_SECONDS),_=ja(e.LMCTL_MAILBOX_BACKOFF_READ_INTERVAL_SECONDS),y=ja(e.LMCTL_MAILBOX_CHATLOG_POLL_SECONDS),T=i(e.LMCTL_MAILBOX_KEY),S=i(e.LMCTL_TOKEN_PATH);return f.config={identityPoolId:o,cognitoUserPoolId:a,cognitoClientId:c,region:d,mailboxBucket:l,...typeof p=="number"&&Number.isFinite(p)&&p>=100?{pollIntervalMs:p}:{},...h!==void 0?{readIntervalMs:h}:{},...g!==void 0?{heartbeatIdleMs:g}:{},..._!==void 0?{backoffReadIntervalMs:_}:{},...y!==void 0?{chatLogPollIntervalMs:y}:{},...T!==void 0?{mailboxKey:T}:{},...S!==void 0?{tokenPath:S}:{}},f}function s1(t){try{let e=Pa(t,"utf8"),n=JSON.parse(e).outputs??{},s={};for(let[i,o]of Object.entries(n))o!==null&&typeof o=="object"&&typeof o.value=="string"&&(s[i]=o.value);return s}catch{return{}}}function i1(t){let e=cm(KF(t??import.meta.url));return[Ma(e,"..","..","..","..","infra","terraform","terraform.tfstate"),Ma(e,"..","..","..","..","..","infra","terraform","terraform.tfstate"),Ma(e,"..","..","..","infra","terraform","terraform.tfstate"),Ma(e,"..","..","infra","terraform","terraform.tfstate")]}function ja(t){if(t===void 0||t==="")return;let e=Number(t);if(!(!Number.isFinite(e)||e<=0))return e*1e3}function o1(t){let e=a1(t.intervalMs)??vv,r=Math.max(1,Math.trunc(t.limit??500)),n=t.now??Date.now,s=t.cursorKey!==void 0&&t.store.loadTeamChatLogCursor!==void 0&&t.store.saveTeamChatLogCursor!==void 0?{key:t.cursorKey,load:t.store.loadTeamChatLogCursor.bind(t.store),save:t.store.saveTeamChatLogCursor.bind(t.store)}:null,i,o=!1,a=!1,l=()=>{try{if(s!==null){let u=s.load(s.key);if(u!==null)return i=u.last_pushed_id,!0}return i=t.store.getMaxTeamChatLogId(),s!==null&&s.save({cursor_key:s.key,last_pushed_id:i,updated_at:new Date(n()).toISOString()}),!0}catch(u){return t.log?.(`[mailbox] daemon_event chat_log seed failed: ${u instanceof Error?u.message:String(u)}`),!1}};l();let d=async()=>{if(!(a||o)){o=!0;try{if(i===void 0&&!l())return;let u=t.store.listTeamChatLogSinceId(i,r);for(let f of u){let m={kind:"daemon_event",event:"chat_log",ts:n(),entry:{id:f.id,root_teamfile:f.root_teamfile,sender_teamfile:f.sender_teamfile,sender_alias:f.sender_alias,receiver_teamfile:f.receiver_teamfile,receiver_alias:f.receiver_alias,message:f.message,response:f.response,status:f.status,created_at:f.created_at}};await t.publishDaemonEvent(m),s!==null&&s.save({cursor_key:s.key,last_pushed_id:f.id,updated_at:new Date(n()).toISOString()}),i=Math.max(i,f.id)}}catch(u){t.log?.(`[mailbox] daemon_event chat_log tail failed: ${u instanceof Error?u.message:String(u)}`)}finally{o=!1}}},c=setInterval(()=>{d()},e);return typeof c.unref=="function"&&c.unref(),{pollNow:d,stop(){a=!0,clearInterval(c)}}}function a1(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}async function Sv(t){let e=t.tokenPath??wv(Tv(),".lmctl","cli-tokens.json"),r=_v(t.tokenPath);if(YT(r.cognito?.idToken)&&om()!==null)try{await av({region:t.region,clientId:t.cognitoClientId??Fa,cliTokensPath:e}),r=_v(t.tokenPath),t.log?.("[mx-mailbox] refreshed IdToken from device-auth refresh token")}catch(R){let Z=R instanceof Error?R.message:String(R);t.log?.(`[mx-mailbox] device-auth refresh failed: ${Z}`)}if(r.cognito===void 0)throw new Error("agent_mailbox_not_logged_in: ~/.lmctl/cli-tokens.json has no cognito tokens; run `webcli login` or `lmctl device login` first");let n=r.cognito.idToken;if(typeof n!="string"||n==="")throw new Error("agent_mailbox_no_id_token: cli-tokens.json's cognito.idToken is empty; run `webcli login` or `lmctl device login` first");let s=`cognito-idp.${t.region}.amazonaws.com/${t.cognitoUserPoolId}`,i=r.cognito.identityId,o=!1;i===void 0||i===""?i=await hv({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}):(o=!0,t.log?.(`[mx-mailbox] using cached identityId from cli-tokens (skipping GetId) for ${i}`));let a=mv({identityId:i,logins:{[s]:n},clientConfig:{region:t.region}}),l=new fv({region:t.region,credentials:a}),d={ListObjectsV2Command:QF,GetObjectCommand:ZF,PutObjectCommand:e1},c=Xs(n),u=c??i,f=t.deviceId,m=On({identityId:i,userId:c,deviceId:f,mailboxKey:t.mailboxKey}),p=t.cursorStore,h;if(p!==void 0){let R=p.loadMailboxCursor(u,m);if(R!==null)h=R.last_processed_seq??void 0,t.log?.(`[mx-mailbox] resumed seq cursor=${h??"(sentinel)"} for user_id=${u}`);else{let Z=!1,B=0;for(;!Z&&B<2;){B+=1;try{let b=ea(m,"web"),I=0,L;do{let W=await l.send(new d.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:b,MaxKeys:1e3,...L!==void 0?{ContinuationToken:L}:{}}));for(let j of W.Contents??[]){let D=ta(j.Key??"",m,"web");D!==void 0&&D>I&&(I=D)}L=W.IsTruncated===!0?W.NextContinuationToken:void 0}while(L!==void 0);h=I,t.log?.(`[mx-mailbox] cold start: seeded seq cursor=${I} for user_id=${u}`),Z=!0}catch(b){let I=b instanceof Error?b.message:String(b);if(o&&B===1&&c1(b)){t.log?.(`[mx-mailbox] cached identityId rejected by cognito (${I}); clearing + refreshing`),d1(e),o=!1,i=await hv({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}),a=mv({identityId:i,logins:{[s]:n},clientConfig:{region:t.region}}),l=new fv({region:t.region,credentials:a}),m=On({identityId:i,userId:c,deviceId:f,mailboxKey:t.mailboxKey});continue}t.log?.(`[mx-mailbox] cold start seq probe failed: ${I}`);break}}p.saveMailboxCursor({user_id:u,mailbox_key:m,last_processed_version_id:null,last_processed_seq:h??null,last_processed_at:new Date().toISOString()})}}let g=null,_=t.terminalSessionManager,y=t.persistentSessionManager,T=t.promptTriggerStore,S=new Oa,A=new Hr({bucket:t.mailboxBucket,identityId:i,...c!==null?{userId:c}:{},...f!==void 0?{deviceId:f}:{},...t.mailboxKey!==void 0?{mailboxKey:t.mailboxKey}:{},s3:l,commands:d,selfRole:"agent",onS3Op:R=>S.record(R),onMessage:async R=>{if(_!==void 0&&Zu(R.payload)){_.onInbound(R.payload);return}if(y!==void 0&&Qu(R.payload)){await y.onInbound(R.payload);return}if(!tm(R.payload)){if(T!==void 0&&rm(R.payload)){dm({store:T,payload:R.payload,log:t.log});return}g!==null&&await g.handleIncoming(R.payload,R)}},...p!==void 0?{onCursorAdvance:R=>{p.saveMailboxCursor({user_id:u,mailbox_key:m,last_processed_version_id:null,last_processed_seq:R,last_processed_at:new Date().toISOString()})}}:{},...h!==void 0?{cursor:h}:{},...t.pollIntervalMs!==void 0?{pollIntervalMs:t.pollIntervalMs}:{},...t.readIntervalMs!==void 0?{readIntervalMs:t.readIntervalMs}:{},...t.heartbeatIdleMs!==void 0?{heartbeatIdleMs:t.heartbeatIdleMs}:{},...t.backoffReadIntervalMs!==void 0?{backoffReadIntervalMs:t.backoffReadIntervalMs}:{}});g=new Hs({client:A,...t.log!==void 0?{log:t.log}:{}}),_!==void 0&&_.setPublish(async R=>A.putMessage({conversation_id:`terminal:${R.session_id}`,payload:R})),y!==void 0&&y.setPublish(async R=>A.putMessage({conversation_id:`provider:${R.session_id}`,payload:R}));let N=R=>A.putMessage({conversation_id:em,payload:R});A.start();let F=t.chatLogTailStore===void 0?void 0:o1({store:t.chatLogTailStore,publishDaemonEvent:N,cursorKey:m,intervalMs:t.chatLogPollIntervalMs??t.readIntervalMs??t.pollIntervalMs??vv,log:t.log});t.log?.(`[mx-mailbox] agent polling ${m} (bucket=${t.mailboxBucket})`);let Se=t.deviceId??i,q=`${u}/usage/`,U;return U=t.usageStore===void 0?void 0:WT({meter:S,store:t.usageStore,userId:u,deviceId:Se,ceilingUsd:t.usageQuotaUsd??1/0,onQuotaExceeded:({period:R,costUsd:Z,ceilingUsd:B})=>{t.log?.(`[usage] month ${R} cost $${Z.toFixed(4)} >= ceiling $${B} \u2014 blocking mailbox`),A.stop().catch(()=>{}),U?.stop()},publishOwnRollup:async(R,Z)=>{await l.send(new d.PutObjectCommand({Bucket:t.mailboxBucket,Key:`${q}${Se}-${R}.json`,Body:JSON.stringify({...Z,updated_at:new Date().toISOString()}),ContentType:"application/json"}))},readUserTotal:async R=>{let Z={put:0,get:0,list:0},B;do{let b=await l.send(new d.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:q,MaxKeys:1e3,...B!==void 0?{ContinuationToken:B}:{}}));for(let I of b.Contents??[]){let L=I.Key??"";if(L.endsWith(`-${R}.json`))try{let W=await l.send(new d.GetObjectCommand({Bucket:t.mailboxBucket,Key:L}));if(W.Body===void 0)continue;let j=JSON.parse(await W.Body.transformToString("utf-8"));Z.put+=j.put??0,Z.get+=j.get??0,Z.list+=j.list??0}catch{}}B=b.IsTruncated===!0?b.NextContinuationToken:void 0}while(B!==void 0);return Z},intervalMs:t.usageFlushIntervalMs??36e5,...t.log!==void 0?{log:t.log}:{}}),{identityId:i,mailbox:A,fetchClient:g,publishDaemonEvent:N,async stop(){F?.stop(),U!==void 0&&(await U.flushNow().catch(()=>{}),U.stop()),await g.stop().catch(()=>{}),await A.stop().catch(()=>{})}}}async function bv(t){let e=t.s3!==void 0&&t.commands!==void 0?{s3:t.s3,commands:t.commands}:La(t.rootDir),r=On({identityId:Gs,userId:Gs,deviceId:pv}),n=null,s=t.terminalSessionManager,i=t.persistentSessionManager,o=t.promptTriggerStore,a=new Hr({bucket:"local",identityId:Gs,userId:Gs,deviceId:pv,s3:e.s3,commands:e.commands,selfRole:"agent",onMessage:async d=>{if(s!==void 0&&Zu(d.payload)){s.onInbound(d.payload);return}if(i!==void 0&&Qu(d.payload)){await i.onInbound(d.payload);return}if(!tm(d.payload)){if(o!==void 0&&rm(d.payload)){dm({store:o,payload:d.payload,log:t.log});return}n!==null&&await n.handleIncoming(d.payload,d)}},pollIntervalMs:t.pollIntervalMs??Da,readIntervalMs:t.readIntervalMs??Da,heartbeatIdleMs:t.heartbeatIdleMs??Da,backoffReadIntervalMs:t.backoffReadIntervalMs??Da});n=new Hs({client:a,...t.log!==void 0?{log:t.log}:{}}),s!==void 0&&s.setPublish(async d=>a.putMessage({conversation_id:`terminal:${d.session_id}`,payload:d})),i!==void 0&&i.setPublish(async d=>a.putMessage({conversation_id:`provider:${d.session_id}`,payload:d}));let l=d=>a.putMessage({conversation_id:em,payload:d});return a.start(),t.log?.(`[local-webui] agent polling ${r} (local-fs ${t.rootDir})`),{identityId:Gs,mailbox:a,fetchClient:n,publishDaemonEvent:l,async stop(){await n.stop().catch(()=>{}),await a.stop().catch(()=>{})}}}function _v(t){let e=t??wv(Tv(),".lmctl","cli-tokens.json");try{let r=Pa(e,"utf8");return JSON.parse(r)}catch{return{}}}function l1(t,e){if(e===void 0||e==="")return;let r={};try{let s=Pa(t,"utf8");r=JSON.parse(s)}catch{}if(r.cognito===void 0)return;let n={...r,cognito:{...r.cognito,identityId:e}};yv(cm(t),{recursive:!0,mode:448}),Ev(t,JSON.stringify(n,null,2));try{gv(t,384)}catch{}}function d1(t){let e={};try{let n=Pa(t,"utf8");e=JSON.parse(n)}catch{return}if(e.cognito===void 0)return;let r={...e,cognito:{...e.cognito}};delete r.cognito.identityId,yv(cm(t),{recursive:!0,mode:448}),Ev(t,JSON.stringify(r,null,2));try{gv(t,384)}catch{}}async function hv(t){t.log?.("[mx-mailbox] cli-tokens has no identityId; calling GetId");let r=await new YF({region:t.region}).send(new zF({IdentityPoolId:t.identityPoolId,Logins:{[t.idpProvider]:t.idToken}}));if(r.IdentityId===void 0||r.IdentityId==="")throw new Error("cognito_getid_no_identity_id");try{l1(t.tokenPath,r.IdentityId),t.log?.(`[mx-mailbox] persisted identityId=${r.IdentityId} to ${t.tokenPath}`)}catch(n){let s=n instanceof Error?n.message:String(n);t.log?.(`[mx-mailbox] WARNING: identityId persist failed (${s}); will redo GetId on next restart`)}return r.IdentityId}function c1(t){if(t===null||typeof t!="object")return!1;let e=t,r=[typeof e.name=="string"?e.name:void 0,typeof e.Code=="string"?e.Code:void 0,typeof e.__type=="string"?e.__type:void 0];for(let s of r)if(s!==void 0&&(s==="NotAuthorizedException"||s==="ResourceNotFoundException"||s==="InvalidIdentityPoolConfigurationException"||s==="ExpiredTokenException"))return!0;let n=typeof e.message=="string"?e.message:"";return!!(n.includes("NotAuthorizedException")||n.includes("Invalid identity pool configuration")||n.includes("Identity")&&n.includes("not found"))}var vv,Da,Fa,t1,r1,n1,Gs,pv,um=E(()=>{"use strict";ia();Gu();Yu();qT();HT();XT();JT();GT();nm();ra();sm();lm();uv();vv=3e3,Da=1e3,Fa="79u5jhkk46qofog661c9i0bdcs",t1="us-east-1:69636ff0-e008-4cbc-853d-180e5526a198",r1="us-east-1_4iUdFggDn",n1="lmctl-next-preview-mailbox-254332045686";Gs="local",pv="local"});import{spawn as _m}from"node:child_process";import{createInterface as Iv}from"node:readline";var mm,fm,pm,kv,Nv=E(()=>{"use strict";$i();me();mm=class{child;ctx;rl;nextRpcId=1;pending=new Map;threadId;nextLocalTurnId=1;closed=!1;setResumeThreadId(e){this.threadId=e}async start(e,r){this.ctx=r;let n=_m(e.command,e.args,{cwd:e.cwd??process.cwd(),env:e.env??process.env,stdio:["pipe","pipe","pipe"]});if(this.child=n,this.rl=Iv({input:n.stdout}),this.rl.on("line",s=>{r.generation===r.currentGeneration()&&this.handleLine(s)}),n.stderr?.on("data",s=>{if(r.generation!==r.currentGeneration())return;let i=s instanceof Buffer?s.toString("utf8"):String(s);r.emit({event_type:"notification",payload:{source:"stderr",text:i}})}),await this.rpc("initialize",{clientInfo:{name:"lmctl-dt3",title:"lmctl DT-3",version:"0.1.0"},capabilities:{experimentalApi:!1}}),this.notify("initialized",{}),this.threadId!==void 0&&this.threadId!=="")try{await this.rpc("thread/resume",{threadId:this.threadId,approvalPolicy:"never",sandbox:"danger-full-access"}),r.emit({event_type:"thread_started",payload:{thread_id:this.threadId,resumed:!0}})}catch{let i=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,o=typeof i?.id=="string"?i.id:void 0;this.threadId=o,r.emit({event_type:"thread_started",payload:{thread_id:o,resumed:!1}})}else{let i=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,o=typeof i?.id=="string"?i.id:void 0;this.threadId=o,r.emit({event_type:"thread_started",payload:{thread_id:o,resumed:!1}})}return n}async sendTurn(e){if(this.closed)throw new Error("codex_session_closed");if(this.threadId===void 0||this.threadId==="")throw new Error("codex_no_thread_id");let r=`local-${this.nextLocalTurnId++}`;this.ctx?.turnMap.set(r,{startedAt:Date.now()});try{let s=(await this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}]})).result?.turn,i=typeof s?.id=="string"?s.id:void 0;if(i!==void 0){let o=this.ctx?.turnMap.get(r);this.ctx?.turnMap.delete(r),o!==void 0&&this.ctx?.turnMap.set(i,o)}}catch(n){throw this.ctx?.turnMap.delete(r),n}}async stop(){if(this.closed=!0,this.rl!==void 0&&(this.rl.close(),this.rl=void 0),this.child?.stdin!==null&&this.child?.stdin?.end!==void 0)try{this.child.stdin.end()}catch{}for(let e of this.pending.values())e.reject(new Error("codex_session_stopping"));this.pending.clear()}async rpc(e,r){if(this.child?.stdin===null||this.child===void 0)throw new Error("codex_child_unavailable");return new Promise((n,s)=>{let i=this.nextRpcId++;this.pending.set(i,{resolve:n,reject:s});let o=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:r});try{this.child.stdin.write(o+`
|
|
2321
2322
|
`)}catch(a){this.pending.delete(i),s(a instanceof Error?a:new Error(String(a)))}})}notify(e,r){if(this.child?.stdin===null||this.child===void 0)return;let n=JSON.stringify({jsonrpc:"2.0",method:e,params:r});try{this.child.stdin.write(n+`
|
|
2322
2323
|
`)}catch{}}handleLine(e){if(e.trim()==="")return;let r;try{r=JSON.parse(e)}catch{return}if(typeof r.id=="number"&&this.pending.has(r.id)){let o=this.pending.get(r.id);if(this.pending.delete(r.id),r.error!==void 0){let a=r.error,l=typeof a?.message=="string"&&a.message!==""?a.message:JSON.stringify(r.error);o.reject(new Error(`codex_rpc_error: ${l}`))}else o.resolve(r);return}let n=typeof r.method=="string"?r.method:void 0;if(n===void 0)return;let s=r.params??{},i=this.normalizeNotification(n,s);i!==void 0&&this.ctx?.emit(i)}normalizeNotification(e,r){if(e==="thread/started"){let n=r.thread;return typeof n?.id=="string"&&(this.threadId=n.id),{event_type:"thread_started",payload:{thread_id:this.threadId,raw:r}}}if(e==="turn/started")return{event_type:"turn_started",payload:{turn_id:r.turn?.id,thread_id:this.threadId}};if(e==="item/agentMessage/delta")return{event_type:"assistant_message_delta",payload:{text:typeof r.delta=="string"?r.delta:""}};if(e==="item/started"||e==="item/completed"){let n=r.item;return n?.type!==void 0&&n.type!=="agentMessage"&&n.type!=="userMessage"?{event_type:"tool_call",payload:{name:n.name??n.type,status:e==="item/started"?"started":"completed",item:n}}:{event_type:"notification",payload:{method:e,params:r}}}if(e==="turn/completed"){let n=r.turn;return typeof n?.id=="string"&&this.ctx?.turnMap.delete(n.id),{event_type:"turn_complete",payload:r}}if(e==="error"){let n=r.error;return{event_type:"error",payload:{message:typeof n?.message=="string"?n.message:JSON.stringify(r),raw:r}}}return{event_type:"notification",payload:{method:e,params:r}}}},fm=class{child;ctx;buffer="";sessionIdSeen;closed=!1;async start(e,r){this.ctx=r;let n=_m(e.command,e.args,{cwd:e.cwd??process.cwd(),env:e.env??process.env,stdio:["pipe","pipe","pipe"]});return this.child=n,n.stdout.on("data",s=>{if(r.generation!==r.currentGeneration())return;let i=s instanceof Buffer?s.toString("utf8"):String(s);this.buffer+=i;let o=this.buffer.split(`
|
|
2323
2324
|
`);this.buffer=o.pop()??"";for(let a of o)this.handleLine(a)}),n.stderr?.on("data",s=>{if(r.generation!==r.currentGeneration())return;let i=s instanceof Buffer?s.toString("utf8"):String(s);r.emit({event_type:"notification",payload:{source:"stderr",text:i}})}),n}async sendTurn(e){if(this.closed)throw new Error("claude_session_closed");if(this.child===void 0||this.child.stdin===null)throw new Error("claude_child_unavailable");let r=`claude-${Date.now()}`;this.ctx?.turnMap.set(r,{startedAt:Date.now()});let n=JSON.stringify({type:"user",message:{role:"user",content:e}});try{this.child.stdin.write(n+`
|
|
@@ -2445,7 +2446,7 @@ The session marker may be stale or the team may not be registered in this lmctl
|
|
|
2445
2446
|
Consulted ${Qn(Q())}
|
|
2446
2447
|
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function gS(t){return`unknown option --from
|
|
2447
2448
|
${Im(t)}`}function yS(t,e){let r=Jn(t,e);return r.ok?{ok:!0,identity:r.identity,source:"session"}:r}function Jn(t,e){let r=t[ps];if(r===void 0||r.length===0)return{ok:!1,reason:"unset"};let n=[];for(let i of e.listRootTeams()){let o;try{o=qe(i.teamfile_path,e)}catch{continue}for(let a of o.members)a.teamfile===void 0&&a.session===r&&n.push(`${i.teamfile_path}:${a.alias}`)}let s=[...new Set(n)];if(s.length===0)return{ok:!1,reason:"not-found"};if(s.length>1)throw new Error("LMCTL_SELF_SESSIONID matches multiple team members; the team registry is ambiguous");return{ok:!0,identity:s[0]}}var zs=E(()=>{"use strict";ut();Ye();rr()});function He(t){let e=Jr(t);if(e===null)throw new Error(`invalid agent identity: ${t}`);return{teamfile:e.teamfile,alias:e.alias,value:t}}var Xa=E(()=>{"use strict";wt()});async function Va(t){let e=t.onEvent??(()=>{}),r=_U(t.io,e),n=null,s=null,i=null,o,a,l=null,d=t.prompt;try{let c=await O(r,N=>De(t.teamfile,t.alias,N)),u=c.teamfile,f=await O(r,N=>SU(N,t.env??process.env)),m=f.sender,p=await bU(r,{explicitRoot:t.rootFlag,sender:m,receiverTeamfile:u,operatorOrigin:f.origin==="operator"}),h=m===null?null:await IU(r,{rootTeamfile:p,sender:m,receiverTeamfile:u,receiverAlias:c.alias});h!==null&&!h.allowed&&e({kind:"warning",message:`warning: out-of-policy chat send: ${h.reason}
|
|
2448
|
-
`}),i=await yU(r,{receiverTeamfile:u,receiverAlias:c.alias,sender:m,rootTeamfile:p,provider:c.provider,model:c.model,sessionId:c.sessionid,cwd:c.sessiondir,prompt:t.prompt,origin:f.origin}),o=TU(r,i);try{Hn(r,rt(u),u)}catch{}n={root_teamfile:p,sender_teamfile:m?.teamfile??null,sender_alias:m?.alias??null,receiver_teamfile:u,receiver_alias:c.alias,receiver_provider:c.provider,receiver_session_id:c.sessionid,origin:f.origin,policy:h};let g=await SS(r,u,c.alias);if(g!==null){let N=Sm(g);if(m!==null){let F=await km(r,{sender:m,receiverTeamfile:u,receiverAlias:c.alias,receiverProvider:c.provider,receiverSessionId:c.sessionid,rootTeamfile:p,payload:t.prompt});return l=Ja(`enqueued mailbox message ${F.id}`,null),Nm(F.id,m,u,c.alias)}return Gn(i,n,t.prompt,N,"unavailable"),l=Am(N,null),{status:"busy",message:N,teamChatLogId:null}}let _=await hU(r,u,c.alias);if(_.busy){if(m!==null){let F=await km(r,{sender:m,receiverTeamfile:u,receiverAlias:c.alias,receiverProvider:c.provider,receiverSessionId:c.sessionid,rootTeamfile:p,payload:t.prompt});return l=Ja(`enqueued mailbox message ${F.id}`,null),Nm(F.id,m,u,c.alias)}let N=await gU(r,u,c.alias);return Gn(i,n,t.prompt,N,"unavailable"),l=Am(N,null),{status:"busy",message:N,teamChatLogId:null}}if(m!==null&&m.teamfile!==u){let N=await O(r,F=>lT(F,{root:p,sender:m,receiverTeamfile:u,receiverAlias:c.alias,now:new Date}));if(N.stop){let F=cT(N.chain);return Gn(i,n,t.prompt,F,"cycle"),l=Ga(F,null),{status:"error",errorKind:"cycle",message:F,teamChatLogId:null}}}let y=await AU(r,{receiver_teamfile:u,receiver_alias:c.alias,sender_teamfile:m?.teamfile??u,sender_alias:m?.alias??"operator",..._.idleReclaim?{force:!0,reclaimReason:"session-idle"}:{}});if(!y.acquired){let N=bS(u,c.alias,y.current);if(m!==null){let F=await km(r,{sender:m,receiverTeamfile:u,receiverAlias:c.alias,receiverProvider:c.provider,receiverSessionId:c.sessionid,rootTeamfile:p,payload:t.prompt});return l=Ja(`enqueued mailbox message ${F.id}`,null),Nm(F.id,m,u,c.alias)}return Gn(i,n,t.prompt,N,"unavailable"),l=Am(N,null),{status:"busy",message:N,teamChatLogId:null}}s=y.lease,a=sn(N=>O(r,F=>F.heartbeatAgentInflight(s,
|
|
2449
|
+
`}),i=await yU(r,{receiverTeamfile:u,receiverAlias:c.alias,sender:m,rootTeamfile:p,provider:c.provider,model:c.model,sessionId:c.sessionid,cwd:c.sessiondir,prompt:t.prompt,origin:f.origin}),o=TU(r,i);try{Hn(r,rt(u),u)}catch{}n={root_teamfile:p,sender_teamfile:m?.teamfile??null,sender_alias:m?.alias??null,receiver_teamfile:u,receiver_alias:c.alias,receiver_provider:c.provider,receiver_session_id:c.sessionid,origin:f.origin,policy:h};let g=await SS(r,u,c.alias);if(g!==null){let N=Sm(g);if(m!==null){let F=await km(r,{sender:m,receiverTeamfile:u,receiverAlias:c.alias,receiverProvider:c.provider,receiverSessionId:c.sessionid,rootTeamfile:p,payload:t.prompt});return l=Ja(`enqueued mailbox message ${F.id}`,null),Nm(F.id,m,u,c.alias)}return Gn(i,n,t.prompt,N,"unavailable"),l=Am(N,null),{status:"busy",message:N,teamChatLogId:null}}let _=await hU(r,u,c.alias);if(_.busy){if(m!==null){let F=await km(r,{sender:m,receiverTeamfile:u,receiverAlias:c.alias,receiverProvider:c.provider,receiverSessionId:c.sessionid,rootTeamfile:p,payload:t.prompt});return l=Ja(`enqueued mailbox message ${F.id}`,null),Nm(F.id,m,u,c.alias)}let N=await gU(r,u,c.alias);return Gn(i,n,t.prompt,N,"unavailable"),l=Am(N,null),{status:"busy",message:N,teamChatLogId:null}}if(m!==null&&m.teamfile!==u){let N=await O(r,F=>lT(F,{root:p,sender:m,receiverTeamfile:u,receiverAlias:c.alias,now:new Date}));if(N.stop){let F=cT(N.chain);return Gn(i,n,t.prompt,F,"cycle"),l=Ga(F,null),{status:"error",errorKind:"cycle",message:F,teamChatLogId:null}}}let y=await AU(r,{receiver_teamfile:u,receiver_alias:c.alias,sender_teamfile:m?.teamfile??u,sender_alias:m?.alias??"operator",..._.idleReclaim?{force:!0,reclaimReason:"session-idle"}:{}});if(!y.acquired){let N=bS(u,c.alias,y.current);if(m!==null){let F=await km(r,{sender:m,receiverTeamfile:u,receiverAlias:c.alias,receiverProvider:c.provider,receiverSessionId:c.sessionid,rootTeamfile:p,payload:t.prompt});return l=Ja(`enqueued mailbox message ${F.id}`,null),Nm(F.id,m,u,c.alias)}return Gn(i,n,t.prompt,N,"unavailable"),l=Am(N,null),{status:"busy",message:N,teamChatLogId:null}}s={row:y.lease,leaseId:y.leaseId},a=sn(N=>O(r,F=>F.heartbeatAgentInflight(s.row,s.leaseId,N)),{intervalMs:vS,onError:N=>{ce()&&$e(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:N instanceof Error?N.message:String(N)}))}});let T=await Ea({sender:m??{teamfile:u,alias:"operator"},receiver:{teamfile:u,alias:c.alias,provider:c.provider,sessionId:c.sessionid,cwd:c.sessiondir,...c.model!==void 0?{model:c.model}:{},...c.effort!==void 0?{effort:c.effort}:{},...c.isLead!==void 0?{isLead:c.isLead}:{}},newMessage:t.prompt,newMessageFrom:m===null?"operator":`${m.teamfile}:${m.alias}`,io:r,permissionMode:t.permissionMode,env:t.env??process.env,...t.idleTimeoutMs!==void 0?{idleTimeoutMs:t.idleTimeoutMs}:{},onDelta:N=>e({kind:"delta",chunk:N}),onProgress:N=>e({kind:"progress",alias:c.alias,event:N}),onPromptBuilt:N=>{if(d=N,i!==null)return wU(r,i,N)}});d=T.prompt;let S=T.status==="stalled",A=null;if(S){let N=`provider stalled${T.stalledAfterMs!==void 0?` after ${T.stalledAfterMs}ms`:""}`;Gn(i,n,d,N,"error"),l=Ga(N,null,T.receipt)}else A=await RU(r,{...n,message:d,response:T.receipt,status:n.policy?.outOfPolicy===!0?"out_of_policy":"ok",error_detail:n.policy?.outOfPolicy===!0?n.policy.reason:null}),l=Ja(T.receipt,A);return{status:S?"stalled":"ok",replyText:T.receipt,wroteDelta:T.wroteDelta,teamChatLogId:A,durationMs:T.durationMs}}catch(c){let u=c instanceof Error?c.message:String(c);return Gn(i,n,d,u,"error"),l=Ga(u,null),{status:"error",errorKind:c instanceof ve?"target":"provider",message:u,teamChatLogId:null}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),s!==null&&await xU(r,s.row,s.leaseId),i!==null&&await EU(r,i,l??Ga("chat turn exited without a terminal outcome",null))}}function _U(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function hU(t,e,r){let n=await O(t,i=>Wt(i,e,r));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await O(t,i=>Ra(i,n,e,r));return{busy:!s,idleReclaim:s}}async function gU(t,e,r){let n=await SS(t,e,r);if(n!==null)return Sm(n);let s=await O(t,i=>i.getAgentInflight(e,r));return s!==null?bS(e,r,s):`${r} is busy; wait and retry`}async function km(t,e){return await wa(t,t.env??process.env),await O(t,r=>{let n=De(e.sender.teamfile,e.sender.alias,r);return r.enqueueMail({sender_teamfile:e.sender.teamfile,sender_alias:e.sender.alias,sender_provider:n.provider,sender_session_id:n.sessionid,receiver_teamfile:e.receiverTeamfile,receiver_alias:e.receiverAlias,receiver_provider:e.receiverProvider,receiver_session_id:e.receiverSessionId,root_teamfile:e.rootTeamfile,payload:e.payload})})}function Nm(t,e,r,n){let s=`${r}:${n}`;return{status:"enqueued",id:t,message:`mailbox message ${t} enqueued to ${s}`,teamChatLogId:null,sender:`${e.teamfile}:${e.alias}`,receiver:s}}async function yU(t,e){try{return(await O(t,n=>n.startTrackedInvocation({kind:"chat",origin:e.origin,scope_teamfile:e.receiverTeamfile,from_identity:e.sender===null?"operator":`${e.sender.teamfile}:${e.sender.alias}`,target_teamfile:e.receiverTeamfile,target_alias:e.receiverAlias,root_teamfile:e.rootTeamfile,cwd:e.cwd??null,command:vU(e.receiverTeamfile,e.receiverAlias,e.prompt),holder_pid:process.pid,request_payload:e.prompt,meta:JSON.stringify({provider:e.provider,model:e.model??null,sessionid:e.sessionId??null})}))).id}catch(r){return ce()&&$e(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function EU(t,e,r){try{await O(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){ce()&&$e(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function wU(t,e,r){try{await O(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){ce()&&$e(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}function TU(t,e){if(e===null)return;let r=setInterval(()=>{O(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{ce()&&$e(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},vS);return r.unref?.(),r}function Ja(t,e){return{status:"done",result_summary:Zs(t),error:null,team_chat_log_id:e}}function Am(t,e){return{status:"busy",result_summary:Zs(t),error:t,team_chat_log_id:e}}function Ga(t,e,r){return{status:"error",result_summary:Zs(r===void 0?t:r),error:t,team_chat_log_id:e}}function Zs(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function vU(t,e,r){return`lmctl chat ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function SU(t,e){let r=yS(e,t);if(r.ok)return{sender:He(r.identity),origin:"agent"};if(r.reason==="unset")return{sender:null,origin:"operator"};throw new Error(Nr("chat"))}async function bU(t,e){if(e.explicitRoot!==void 0)return await O(t,n=>Te(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await O(t,n=>dT(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function IU(t,e){return await O(t,r=>uS({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:kU(r,e.sender.teamfile,e.receiverTeamfile)}))}function kU(t,e,r){return{teams:[e,r].map(s=>NU(s,t))}}function NU(t,e){let r=qe(t,e),n=Dt(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function AU(t,e){return await O(t,r=>{let n=ce(),s=ar(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:br(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&$e(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:s.reclaimReason===null?"acquired":"reclaimed",...s.reclaimReason===null?{}:{reclaim_reason:s.reclaimReason,holder:wS(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&$e(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:wS(s.current)})),{acquired:!1,current:s.current})})}async function SS(t,e,r){return await O(t,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,r);if(o===null)return null;if(vm(o).live)return o;let l=n.getAgentInflight(e,r);if(n.clearTerminalLock(e,r,o.lock_id))return l!==null&&l.sender_teamfile===e&&l.sender_alias==="terminal"&&n.clearObservedTerminalAgentInflight(e,r,{sender_teamfile:l.sender_teamfile,sender_alias:l.sender_alias,started_at:l.started_at,holder_pid:l.holder_pid}),null}let s=n.getTerminalLock(e,r);return s===null?null:vm(s).live?s:null})}function wS(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}}async function xU(t,e,r){try{await O(t,n=>{n.releaseAgentInflight(e,r)})}catch(n){t.stderr.write(`warning: failed to release chat in-flight slot: ${n instanceof Error?n.message:String(n)}
|
|
2449
2450
|
`)}}function bS(t,e,r){return`${e} is servicing ${r.sender_alias} (${r.sender_teamfile}) since ${r.started_at} \u2014 wait and retry, or inspect without waking it: lmctl tail "${t}" ${e}`}async function RU(t,e){let r=TS(e.message),n=e.response===null?null:TS(e.response);try{return await O(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,receiver_provider:e.receiver_provider,receiver_session_id:e.receiver_session_id,provider_prompt:e.message,message:r.text,response:n?.text??null,origin:e.origin,status:e.status,error_detail:e.error_detail,truncated:r.truncated||n?.truncated?1:0,created_at:new Date().toISOString()}))}catch(s){return t.stderr.write(`warning: failed to record chat log: ${s instanceof Error?s.message:String(s)}
|
|
2450
2451
|
`),null}}function Gn(t,e,r,n,s){t!==null||e===null||C({event:"chat_attempt_error",reason:s,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,origin:e.origin,error_detail:n,message_preview:Zs(r)})}function TS(t){return t.length<=ES?{text:t,truncated:!1}:{text:t.slice(0,ES),truncated:!0}}var ES,vS,xm=E(()=>{"use strict";wt();tr();Ys();mS();rr();Ta();me();Me();lr();qu();bm();zs();Xa();xu();ES=256*1024,vS=3e4});var RS={};he(RS,{parseIdleTimeoutMs:()=>AS,resolvePromptInput:()=>NS,runChat:()=>$U});import{readFileSync as LU}from"node:fs";async function $U(t,e={stdout:process.stdout,stderr:process.stderr}){let r=e.env??process.env;if(t.length===0||t[0]==="--help"||t[0]==="-h")return e.stdout.write(`${kS}
|
|
2451
2452
|
`),t.length===0?2:0;let n=CU(t);if(typeof n=="string")return e.stderr.write(`error: ${n}
|
|
@@ -3037,7 +3038,7 @@ Examples:
|
|
|
3037
3038
|
|
|
3038
3039
|
# Same shape, codex for the Lead and Reviewer2
|
|
3039
3040
|
lmctl plan ./backend --provider codex
|
|
3040
|
-
`});import{execFileSync as e2}from"node:child_process";import{resolve as yI}from"node:path";function t2(t){return t.filter(e=>e.state!=="retired")}function EI(t,e,r){if(r!==void 0){let a=e.findProjectByName(r);return a===null?k(t,`project not found: ${r}`):a}let n=t.cwd??process.cwd(),s;try{s=e2("git",["rev-parse","--show-toplevel"],{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return k(t,"terminal cannot infer a member from cwd because this directory is not in a git repo; use `lmctl terminal <teamfile> <alias>`")}let i=yI(s),o=e.listProjects().find(a=>yI(a.local_path)===i);return o===void 0?k(t,`terminal cannot infer a member from cwd ${i}; use \`lmctl terminal <teamfile> <alias>\``):o}function wI(t,e,r,n){if(n!==void 0){let i=e.findTeamByName(n);return i===null?k(t,`team not found: ${n}`):i}let s=e.getTeam(r.team_id);return s===null?k(t,`project ${r.name} has no assigned team; use --team <name>`):s}function TI(t,e,r,n){if(n!==void 0){let i=e.findTeamMemberByAlias(r.id,n);return i===null||i.state==="retired"?k(t,`member not found: ${n}`):i}let s=t2(e.listTeamMembers(r.id)).find(i=>i.role==="agent");return s===void 0?k(t,`team ${r.name} has no active agent member`):s}var vI=E(()=>{"use strict";Me()});var II={};he(II,{SIZE_WARN_EST_TOKENS:()=>ai,estimateTokens:()=>bI,runTerminal:()=>i2});import{spawn as r2}from"node:child_process";import{statSync as n2}from"node:fs";async function i2(t,e){if(t.includes("--help")||t.includes("-h"))return m2(e);let r=te(t,["--project","--team","--alias","--run"],["--size","--json","--help"]);if(r.error!==void 0)return k(e,r.error);let n=M(r,"--run");if(n!==void 0){let s=Number.parseInt(n,10);if(!Number.isFinite(s)||s<=0||String(s)!==n)return k(e,`invalid --run "${n}" (expected a positive integer run id)`);if(r.positionals.length>0)return k(e,"--run is mutually exclusive with positional <teamfile>[:alias]");let i=["--team","--project","--size","--json"];for(let o of i)if(o==="--size"||o==="--json"?V(r,o):M(r,o)!==void 0)return k(e,`--run is mutually exclusive with ${o}`);try{return await O(e,async o=>{let a=M(r,"--alias"),l=ww(o,s,a);return"err"in l?k(e,l.err):lf(e,{provider:l.ok.provider,sessionid:l.ok.sessionid,sessiondir:l.ok.sessiondir,...l.ok.model!==void 0?{model:l.ok.model}:{}})})}catch(o){return We(e,o)}}if(r.positionals.length>0){let s=["--team","--project","--size","--alias","--json"];for(let l of s)if(l==="--size"||l==="--json"?V(r,l):M(r,l)!==void 0)return k(e,`positional <teamfile>[:alias] is mutually exclusive with ${l} (alias is the SECOND POSITIONAL: \`terminal <teamfile> <alias>\`).`);if(r.positionals.length>2)return k(e,`too many positionals (${r.positionals.length}); expected <teamfile>[:alias] [alias]`);let i=r.positionals[0],o=r.positionals[1],a=Ir(s2,{target:i,alias:o,flags:{}});return a.mode==="error"?k(e,a.message):a.mode!=="ai-team"?k(e,`internal: terminal positional yielded unexpected mode "${a.mode}"`):a.alias===void 0?k(e,"terminal: alias required for the teamfile target"):await O(e,l=>o2(e,a.teamfile,a.alias,l))}try{return await O(e,async s=>{let i=d2(e,s,r);if(typeof i=="number")return i;let o=M(r,"--alias");return V(r,"--size")?u2(e,s,i,o,V(r,"--json")):c2(e,s,i,o)})}catch(s){return We(e,s)}}async function o2(t,e,r,n){let s;try{s=De(e,r,n)}catch(c){return c instanceof ve?k(t,c.message):We(t,c)}let i=ar(n,{receiver_teamfile:s.teamfile,receiver_alias:s.alias,sender_teamfile:s.teamfile,sender_alias:"terminal",ttlMs:br()});if(!i.acquired)return k(t,`${s.alias} is busy/held by ${i.current.sender_alias} (${i.current.sender_teamfile}) since ${i.current.started_at}`);let o=pS({teamfile:s.teamfile,alias:s.alias}),a=null,l=null,d=null;try{n.setTerminalLock(o),l=a2(n,s),a=setInterval(()=>{try{let c=new Date().toISOString(),u=n.heartbeatTerminalLock(o.teamfile,o.alias,o.lock_id,c);u&&n.heartbeatAgentInflight(i.lease,i.leaseId,c),!u&&a!==null&&(clearInterval(a),a=null)}catch{}},_S()),a.unref?.();try{Hn(t,rt(s.teamfile),s.teamfile)}catch{}return d=await lf(t,{provider:s.provider,sessionid:s.sessionid,sessiondir:s.sessiondir,...s.model!==void 0?{model:s.model}:{},isLead:s.isLead}),d}finally{a!==null&&clearInterval(a),n.clearTerminalLock(o.teamfile,o.alias,o.lock_id),n.releaseAgentInflight(i.lease),l2(n,l,d)}}function a2(t,e){try{return t.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:e.teamfile,from_identity:`${e.teamfile}:terminal`,target_teamfile:e.teamfile,target_alias:e.alias,root_teamfile:e.teamfile,cwd:e.sessiondir,command:`lmctl terminal ${e.teamfile} ${e.alias}`,holder_pid:process.pid,launch_source:"terminal",meta:JSON.stringify({provider:e.provider,sessionid:e.sessionid,...e.model!==void 0?{model:e.model}:{}})}).id}catch{return null}}function l2(t,e,r){if(e!==null)try{t.finishTrackedInvocation(e,{status:r===0?"done":"error",exit_code:r,result_summary:r===0?"terminal session ended":null,error:r===0?null:`terminal exited with code ${r??"unknown"}`})}catch{}}async function lf(t,e){let{provider:r,sessionid:n,sessiondir:s,model:i}=e;if(!Aa(r))return k(t,`no resume incantation for provider "${r}"`);if(!vT.test(n))return k(t,"refusing to resume: malformed sessionid");let o=Wu(r,n,{isLead:e.isLead,model:i,onModelIgnored:d=>{let c=`warning: ${d.provider} terminal ignored model=${d.model}: ${d.reason}`;t.stderr.write(`${c}
|
|
3041
|
+
`});import{execFileSync as e2}from"node:child_process";import{resolve as yI}from"node:path";function t2(t){return t.filter(e=>e.state!=="retired")}function EI(t,e,r){if(r!==void 0){let a=e.findProjectByName(r);return a===null?k(t,`project not found: ${r}`):a}let n=t.cwd??process.cwd(),s;try{s=e2("git",["rev-parse","--show-toplevel"],{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return k(t,"terminal cannot infer a member from cwd because this directory is not in a git repo; use `lmctl terminal <teamfile> <alias>`")}let i=yI(s),o=e.listProjects().find(a=>yI(a.local_path)===i);return o===void 0?k(t,`terminal cannot infer a member from cwd ${i}; use \`lmctl terminal <teamfile> <alias>\``):o}function wI(t,e,r,n){if(n!==void 0){let i=e.findTeamByName(n);return i===null?k(t,`team not found: ${n}`):i}let s=e.getTeam(r.team_id);return s===null?k(t,`project ${r.name} has no assigned team; use --team <name>`):s}function TI(t,e,r,n){if(n!==void 0){let i=e.findTeamMemberByAlias(r.id,n);return i===null||i.state==="retired"?k(t,`member not found: ${n}`):i}let s=t2(e.listTeamMembers(r.id)).find(i=>i.role==="agent");return s===void 0?k(t,`team ${r.name} has no active agent member`):s}var vI=E(()=>{"use strict";Me()});var II={};he(II,{SIZE_WARN_EST_TOKENS:()=>ai,estimateTokens:()=>bI,runTerminal:()=>i2});import{spawn as r2}from"node:child_process";import{statSync as n2}from"node:fs";async function i2(t,e){if(t.includes("--help")||t.includes("-h"))return m2(e);let r=te(t,["--project","--team","--alias","--run"],["--size","--json","--help"]);if(r.error!==void 0)return k(e,r.error);let n=M(r,"--run");if(n!==void 0){let s=Number.parseInt(n,10);if(!Number.isFinite(s)||s<=0||String(s)!==n)return k(e,`invalid --run "${n}" (expected a positive integer run id)`);if(r.positionals.length>0)return k(e,"--run is mutually exclusive with positional <teamfile>[:alias]");let i=["--team","--project","--size","--json"];for(let o of i)if(o==="--size"||o==="--json"?V(r,o):M(r,o)!==void 0)return k(e,`--run is mutually exclusive with ${o}`);try{return await O(e,async o=>{let a=M(r,"--alias"),l=ww(o,s,a);return"err"in l?k(e,l.err):lf(e,{provider:l.ok.provider,sessionid:l.ok.sessionid,sessiondir:l.ok.sessiondir,...l.ok.model!==void 0?{model:l.ok.model}:{}})})}catch(o){return We(e,o)}}if(r.positionals.length>0){let s=["--team","--project","--size","--alias","--json"];for(let l of s)if(l==="--size"||l==="--json"?V(r,l):M(r,l)!==void 0)return k(e,`positional <teamfile>[:alias] is mutually exclusive with ${l} (alias is the SECOND POSITIONAL: \`terminal <teamfile> <alias>\`).`);if(r.positionals.length>2)return k(e,`too many positionals (${r.positionals.length}); expected <teamfile>[:alias] [alias]`);let i=r.positionals[0],o=r.positionals[1],a=Ir(s2,{target:i,alias:o,flags:{}});return a.mode==="error"?k(e,a.message):a.mode!=="ai-team"?k(e,`internal: terminal positional yielded unexpected mode "${a.mode}"`):a.alias===void 0?k(e,"terminal: alias required for the teamfile target"):await O(e,l=>o2(e,a.teamfile,a.alias,l))}try{return await O(e,async s=>{let i=d2(e,s,r);if(typeof i=="number")return i;let o=M(r,"--alias");return V(r,"--size")?u2(e,s,i,o,V(r,"--json")):c2(e,s,i,o)})}catch(s){return We(e,s)}}async function o2(t,e,r,n){let s;try{s=De(e,r,n)}catch(c){return c instanceof ve?k(t,c.message):We(t,c)}let i=ar(n,{receiver_teamfile:s.teamfile,receiver_alias:s.alias,sender_teamfile:s.teamfile,sender_alias:"terminal",ttlMs:br()});if(!i.acquired)return k(t,`${s.alias} is busy/held by ${i.current.sender_alias} (${i.current.sender_teamfile}) since ${i.current.started_at}`);let o=pS({teamfile:s.teamfile,alias:s.alias}),a=null,l=null,d=null;try{n.setTerminalLock(o),l=a2(n,s),a=setInterval(()=>{try{let c=new Date().toISOString(),u=n.heartbeatTerminalLock(o.teamfile,o.alias,o.lock_id,c);u&&n.heartbeatAgentInflight(i.lease,i.leaseId,c),!u&&a!==null&&(clearInterval(a),a=null)}catch{}},_S()),a.unref?.();try{Hn(t,rt(s.teamfile),s.teamfile)}catch{}return d=await lf(t,{provider:s.provider,sessionid:s.sessionid,sessiondir:s.sessiondir,...s.model!==void 0?{model:s.model}:{},isLead:s.isLead}),d}finally{a!==null&&clearInterval(a),n.clearTerminalLock(o.teamfile,o.alias,o.lock_id),n.releaseAgentInflight(i.lease,i.leaseId),l2(n,l,d)}}function a2(t,e){try{return t.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:e.teamfile,from_identity:`${e.teamfile}:terminal`,target_teamfile:e.teamfile,target_alias:e.alias,root_teamfile:e.teamfile,cwd:e.sessiondir,command:`lmctl terminal ${e.teamfile} ${e.alias}`,holder_pid:process.pid,launch_source:"terminal",meta:JSON.stringify({provider:e.provider,sessionid:e.sessionid,...e.model!==void 0?{model:e.model}:{}})}).id}catch{return null}}function l2(t,e,r){if(e!==null)try{t.finishTrackedInvocation(e,{status:r===0?"done":"error",exit_code:r,result_summary:r===0?"terminal session ended":null,error:r===0?null:`terminal exited with code ${r??"unknown"}`})}catch{}}async function lf(t,e){let{provider:r,sessionid:n,sessiondir:s,model:i}=e;if(!Aa(r))return k(t,`no resume incantation for provider "${r}"`);if(!vT.test(n))return k(t,"refusing to resume: malformed sessionid");let o=Wu(r,n,{isLead:e.isLead,model:i,onModelIgnored:d=>{let c=`warning: ${d.provider} terminal ignored model=${d.model}: ${d.reason}`;t.stderr.write(`${c}
|
|
3041
3042
|
`),Oe({event:"model_ignored",provider:d.provider,model:d.model,reason:d.reason})}});if(o===null||o.length===0)return k(t,`no resume incantation for provider "${r}"`);let[a,...l]=o;return await new Promise(d=>{let c=r2(a,l,{stdio:"inherit",cwd:s,env:Fe(process.env,s,n,"terminal")});c.on("error",u=>{d(k(t,`failed to launch ${a}: ${u.message}`))}),c.on("exit",u=>d(u??0))})}function d2(t,e,r){let n=M(r,"--team");if(n!==void 0){let o=e.findTeamByName(n);return o===null?k(t,`team not found: ${n}`):o}let s=EI(t,e,M(r,"--project"));return typeof s=="number"?s:wI(t,e,s,void 0)}async function c2(t,e,r,n){let s=TI(t,e,r,n);if(typeof s=="number")return s;let i=s.sessionid;return i===null||i.trim().length===0?k(t,`member ${s.alias} has no session yet \u2014 run \`lmctl team seed ${r.name}\` first`):lf(t,{provider:Xe(s),sessionid:i,sessiondir:s.sessiondir,...s.model!==null&&s.model!==void 0?{model:s.model}:{}})}function bI(t){if(t&&Array.isArray(t.messages)&&t.messages.length>0){let r=t.messages.reduce((n,s)=>n+(s.content?.length??0),0);return{chars:r,est:Math.ceil(r/4),messages:t.messages.length,bytes:null}}let e=t?.filePath;if(e!==void 0)try{let r=n2(e).size;return{chars:r,est:Math.ceil(r/4),messages:t?.messages?.length??null,bytes:r}}catch{}return{chars:0,est:0,messages:null,bytes:null}}async function u2(t,e,r,n,s){let i;if(n!==void 0){let a=e.findTeamMemberByAlias(r.id,n);if(a===null||a.state==="retired")return k(t,`member not found: ${n}`);i=[a]}else i=e.listTeamMembers(r.id).filter(a=>a.state!=="retired"&&a.sessionid!==null);let o=[];for(let a of i){let l=a.sessionid;if(l===null)continue;let d=Xe(a),c=a.model??null,u=null;Aa(d)&&(u=await Be(l,d));let f=bI(u),m=f.est>ai;o.push({alias:a.alias,provider:d,sessionid:l,messages:f.messages,bytes:f.bytes,est_tokens:f.est,estimate:!0,over_guide:m,model:c,resume_incantation:m?xa(d,l,c!==null?{model:c}:{}):null})}if(s)return le(t,{estimate:!0,legend:SI,guide_tokens:ai,members:o}),0;t.stdout.write(`session size \u2014 ESTIMATE only (nothing is changed automatically)
|
|
3042
3043
|
`),t.stdout.write(`${SI}
|
|
3043
3044
|
`);for(let a of o){let l=a.messages===null?"?":String(a.messages),d=a.bytes===null?"?":String(a.bytes);t.stdout.write(`${a.alias} ${a.provider} msgs=${l} bytes=${d} ~${a.est_tokens} tok (rough estimate)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lmctl-ai/lmctl",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.203",
|
|
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",
|