@lmctl-ai/lmctl 0.1.240 → 0.1.241
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 +1 -1
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1623,7 +1623,7 @@ var zN=Object.defineProperty;var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var he=(e,t)=>{f
|
|
|
1623
1623
|
`),...qp(e),...Fp(e)}}function Px(e,t){return t===void 0?{resumed:!1,reason:e}:{resumed:!1,reason:e,valid:t}}var dd,dt=w(()=>{"use strict";Ql();Up();Bp();Fi();Gp();Qt();pe();kn();g_();Ns();dd=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;recvMailboxMessagesTxn;constructor(t){t.pragma("foreign_keys = ON"),this.db=t,this.stmts=jx(t),this.claimTxn=t.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=t.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=t.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=t.transaction((r,n,s)=>Px("state_not_found")),this.resumeInteractiveTxn=t.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=t.transaction((r,n,s)=>{let i=this.stmts.getAttention.get(r);if(i===void 0)return{resumed:!1,reason:"not_found"};if(i.kind!==Ki)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!==Is&&!a.includes(n))return{resumed:!1,reason:E_};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=n_(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=t.transaction((r,n)=>{let s=this.stmts.listAllMailboxMessagesForReceiver.all(r,n),i=Kr(s.filter(a=>a.message_type==="request")),o=i===null?null:{action:"set",messageId:De(i.id)};for(let a of s)bs(this.db,a,"",$(),null,a.message_type==="request"?o:null),this.stmts.deleteMailboxMessage.run(a.id);return s})}close(){this.db.close()}query(t,...r){let n=t.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(t).all(...r)}insertWorkflow(t){v_(t.name,t.definition,o=>this.getWorkflowByName(o));let r=this.stmts.insertWorkflow.run(t.name,t.version??1,t.definition_schema_version??1,t.definition,$()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,t.definition,t.author??null,$());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,n.id),(t.source_uri!=null||t.source_sha256!=null)&&this.stmts.setWorkflowSource.run(t.source_uri??null,t.source_sha256??null,n.id);let i=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,t.definition),i}upsertWorkflow(t){v_(t.name,t.definition,o=>this.getWorkflowByName(o));let r=this.getWorkflowByName(t.name);if(r===null)return this.insertWorkflow({name:t.name,definition_schema_version:t.definition_schema_version,definition:t.definition,author:t.author,source_uri:t.source_uri,source_sha256:t.source_sha256});let s=(this.stmts.getLatestWorkflowVersion.get(r.id)?.version??r.version)+1,i=this.stmts.insertWorkflowVersion.run(r.id,s,t.definition,t.author??null,$());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.lastInsertRowid),t.definition,t.definition_schema_version??r.definition_schema_version,s,r.id),(t.source_uri!=null||t.source_sha256!=null)&&this.stmts.setWorkflowSource.run(t.source_uri??null,t.source_sha256??null,r.id),this.syncWorkflowTriggers(r.id,t.definition),this.getWorkflow(r.id)}insertCompositionUnit(t){this.stmts.insertCompositionUnit.run(t.name,t.version,t.lang,t.source,t.source_sha,t.compiled_workflow_version_id,$())}getWorkflow(t){return this.stmts.getWorkflow.get(t)??null}getWorkflowByName(t,r){return(r===void 0?this.stmts.findWorkflowLatest.get(t):this.stmts.findWorkflowVersion.get(t,r))??null}findWorkflowByName(t,r){return this.getWorkflowByName(t,r)}insertWorkflowVersion(t,r,n){let i=(this.stmts.getLatestWorkflowVersion.get(t)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(t,i,r,n??null,$());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(t,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==t)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,t),this.syncWorkflowTriggers(t,n.definition),this.getWorkflow(t)}getWorkflowVersionById(t){return this.stmts.getWorkflowVersion.get(t)??null}listWorkflowVersions(t){return this.stmts.listWorkflowVersions.all(t)}upsertTriggerInstance(t){return this.stmts.upsertTriggerInstance.run(t.workflow_id,t.trigger_id,t.trigger_type,t.parameters,t.enabled===!1?0:1,$()),this.stmts.getTriggerInstanceByWorkflowAndId.get(t.workflow_id,t.trigger_id)}listTriggerInstancesForWorkflow(t){return this.stmts.listTriggerInstancesForWorkflow.all(t)}listEnabledTriggerInstances(){return this.stmts.listEnabledTriggerInstances.all()}setTriggerCursor(t,r){return this.stmts.setTriggerCursor.run(r,$(),t),this.stmts.getTriggerInstance.get(t)??null}setTriggerFailure(t,r){return this.stmts.setTriggerFailure.run($(),r,t),this.stmts.getTriggerInstance.get(t)??null}syncWorkflowTriggers(t,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:t,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(t){let r=this.stmts.insertTeam.run(t.name,$());return this.stmts.getTeam.get(r.lastInsertRowid)}getTeam(t){return this.stmts.getTeam.get(t)??null}findTeamByName(t){return this.stmts.findTeamByName.get(t)??null}listTeams(){return this.stmts.listTeams.all()}insertTeamMember(t){let r=this.stmts.insertTeamMember.run(t.team_id,t.alias,t.role??"agent",t.provider,t.model??null,t.sessionid??null,t.sessiondir,$());return this.stmts.getTeamMember.get(r.lastInsertRowid)}listTeamMembers(t){return this.stmts.listTeamMembers.all(t)}findTeamMemberByAlias(t,r){return this.stmts.findTeamMemberByAlias.get(t,r)??null}updateTeamMemberSession(t,r){return this.stmts.updateTeamMemberSession.run(r,t),this.stmts.getTeamMember.get(t)??null}setMemberState(t,r,n){return this.stmts.setMemberState.run(r,n??null,$(),t),this.stmts.getTeamMember.get(t)??null}listMembersInState(t){return this.stmts.listMembersInState.all(t)}setMemberPromptSnapshot(t,r){return this.stmts.setMemberPromptSnapshot.run(r,t),this.stmts.getTeamMember.get(t)??null}setMemberProviderResolved(t,r){return this.stmts.setMemberProviderResolved.run(r,t),this.stmts.getTeamMember.get(t)??null}setMemberRolePrompt(t,r){return this.stmts.setMemberRolePrompt.run(r,t),this.stmts.getTeamMember.get(t)??null}updateTeamMemberMeta(t,r){let n=this.stmts.getTeamMember.get(t);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,t),this.stmts.getTeamMember.get(t)??null}insertTeamMemberCompanion(t){let r=this.stmts.insertTeamMemberCompanion.run(t.interpreter_id,t.companion_id,$());return this.stmts.getTeamMemberCompanion.get(r.lastInsertRowid)}insertProject(t){let r=this.stmts.insertProject.run(t.name,t.description??null,t.local_path,t.workflow_name,t.team_id,t.default_branch??null,t.intake_config??null,t.test_argv??null,t.test_command??null,t.durable_memory_mode??"folder",$());return this.stmts.getProject.get(r.lastInsertRowid)}listProjects(){return this.stmts.listProjects.all()}getProject(t){return this.stmts.getProject.get(t)??null}findProjectByName(t){return this.stmts.findProjectByName.get(t)??null}setProjectIntakeConfig(t,r){return this.stmts.setProjectIntakeConfig.run(r,t),this.stmts.getProject.get(t)??null}updateProjectSettings(t,r){let n=this.stmts.getProject.get(t);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,t),this.stmts.getProject.get(t)??null}listProjectsWithIntakeEnabled(){return this.stmts.listProjectsWithIntakeConfig.all().filter(t=>{if(t.intake_config===null)return!1;try{let r=JSON.parse(t.intake_config);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.scan_github_issues===!0}catch{return!1}})}getProjectByJob(t){return this.stmts.getProjectByJob.get(t)??null}insertProjectWorkflow(t){let r=t.condition??null,n=this.stmts.findProjectWorkflowUnique.get(t.project_id,t.workflow_id,r);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(t.project_id,t.workflow_id,r,t.parameters_override??null,t.enabled===!1?0:1,t.priority??100,$());return s.changes===1?this.stmts.getProjectWorkflow.get(s.lastInsertRowid):this.stmts.findProjectWorkflowUnique.get(t.project_id,t.workflow_id,r)}getProjectWorkflow(t){return this.stmts.getProjectWorkflow.get(t)??null}listProjectWorkflows(t,r={}){return r.enabled_only===!0?this.stmts.listEnabledProjectWorkflows.all(t):this.stmts.listProjectWorkflows.all(t)}removeProjectWorkflow(t){return this.stmts.removeProjectWorkflow.run(t).changes>0}setProjectWorkflowEnabled(t,r){return this.stmts.setProjectWorkflowEnabled.run(r?1:0,t),this.getProjectWorkflow(t)}createIssue(t){let r=$(),n=this.stmts.createIssue.run(t.project_id,t.title,t.body,t.severity??"medium",t.labels??null,t.ai_test_path??null,t.source_run_id??null,r,r);return this.stmts.getIssue.get(n.lastInsertRowid)}getIssue(t){return this.stmts.getIssue.get(t)??null}listIssues(t,r={}){return this.stmts.listIssuesForProject.all(t).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(t,r){return this.stmts.claimNextIssue.get(r,$(),t)??null}claimIssue(t,r){return this.stmts.claimIssue.get(r,$(),t)??null}closeIssue(t,r,n){let s=$(),i=this.stmts.closeIssue.get(r,n??null,s,s,t);if(i===void 0)throw new Error(`issue not found: ${t}`);return i}reopenIssue(t,r){let n=this.stmts.reopenIssue.get(r,$(),t);if(n===void 0)throw this.getIssue(t)===null?new Error(`issue not found: ${t}`):new Error(`issue ${t} is not closed`);return n}updateIssue(t,r){let n=this.getIssue(t);if(n===null)throw new Error(`issue not found: ${t}`);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,$(),t);if(o===void 0)throw new Error(`issue not found: ${t}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(t,r){let n=this.stmts.getWebuiSession.get(t);if(n!==void 0)return n;let s=$();return this.stmts.insertWebuiSession.run(t,r,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(t)}getWebuiSession(t){return this.stmts.getWebuiSession.get(t)??null}updateWebuiSessionTransition(t,r,n,s,i){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,i,$(),t).changes===0)throw new Error(`webui_session not found: ${t}`);return this.stmts.getWebuiSession.get(t)}setWebuiSessionChatbot(t,r){if(this.stmts.setWebuiSessionChatbot.run(r,$(),t).changes===0)throw new Error(`webui_session not found: ${t}`);return this.stmts.getWebuiSession.get(t)}createChatbotSession(t,r){let n=T_(),s=$();return this.stmts.insertChatbotSession.run(n,t,r??null,s,s,"active"),this.stmts.getChatbotSession.get(n)}getChatbotSession(t){return this.stmts.getChatbotSession.get(t)??null}listChatbotSessions(t){return this.stmts.listChatbotSessionsForUser.all(t)}appendChatbotMessage(t,r,n,s){let i=$(),o=this.stmts.insertChatbotMessage.run(t,r,n,s??null,i);return this.stmts.touchChatbotSession.run(i,t),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(t){return this.stmts.listChatbotMessages.all(t)}getConfig(t){return this.stmts.getConfig.get(t)?.value??null}setConfig(t,r){this.stmts.upsertConfig.run(t,r,$())}getConfigAll(){let t=this.stmts.listConfig.all(),r={};for(let n of t)r[n.key]=n.value;return r}enqueueJob(t){let r=this.stmts.insertJob.run(t.project_id,t.workflow_id_override??null,t.source,t.source_ref??null,t.payload??null,t.priority??0,t.available_at??$(),t.dedupe_key??null,t.concurrency_key??null,$());if(r.changes===1)return this.stmts.getJob.get(r.lastInsertRowid);if(t.dedupe_key===void 0||t.dedupe_key===null)throw new Error("job insert ignored without dedupe key");return this.stmts.findJobByDedupe.get(t.source,t.dedupe_key)}claimNextJob(t){let r=$(),n=new Date(Date.now()+t.lease_ms).toISOString();return this.claimTxn(t.worker_id,n,r)}claimNextJobWithConcurrency(t){let r=$(),n=new Date(Date.now()+t.lease_ms).toISOString();return this.claimWithConcurrencyTxn(t.worker_id,n,r,t.evaluator)}claimJobByIdWithConcurrency(t){let r=$(),n=new Date(Date.now()+t.lease_ms).toISOString();return this.claimByIdWithConcurrencyTxn(t.job_id,t.worker_id,n,r,t.evaluator)}releaseJob(t,r,n){let s=r==="queued"||r==="running"?null:$();return this.stmts.releaseJob.run(r,n??null,s,t),this.getJob(t)}getJob(t){return this.stmts.getJob.get(t)??null}findJobBySourceAndDedupe(t,r){return this.stmts.findJobByDedupe.get(t,r)??null}insertRun(t){let r=this.getWorkflow(t.workflow_id);if(r===null)throw new Error(`workflow not found: ${t.workflow_id}`);let n=this.stmts.insertRun.run(t.job_id,t.workflow_id,t.team_id,t.current_state??null,r.active_version_id,t.parent_run_id??null,$()),s=this.stmts.getRun.get(n.lastInsertRowid);return(t.parent_run_id===void 0||t.parent_run_id===null)&&this.stmts.setJobRun.run(s.id,t.job_id),s}setJobRun(t,r){return this.stmts.setJobRun.run(r,t),this.getJob(t)}insertPromptDispatch(t){return this.stmts.insertPromptDispatch.run(t.prompt_id,t.project_id,t.job_id,t.text,t.context_json??null,$()),this.stmts.getPromptDispatch.get(t.prompt_id)}getPromptDispatch(t){return this.stmts.getPromptDispatch.get(t)??null}setPromptDispatchCompleted(t,r){return this.stmts.setPromptDispatchCompleted.run(r??$(),t),this.getPromptDispatch(t)}getWorkspace(t){return this.stmts.getWorkspace.get(t)??null}ensureWorkspace(t={}){let r=t.id??"default";this.stmts.ensureWorkspace.run(r,t.name??"Default workspace",t.idleThresholdMs??6e5,$());let n=this.getWorkspace(r);if(n===null)throw new Error(`workspace ${r} missing after upsert`);return n}listWebProjectsActive(t){return this.stmts.listWebProjectsActive.all(t)}getWebProject(t){return this.stmts.getWebProject.get(t)??null}insertWebProject(t){let r=$(),n=this.stmts.insertWebProject.run(t.workspace_id,t.name,t.repo_path,t.config_json??null,t.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(t){let r=this.getWebProject(t.id);return r===null||r.deleted_at!==null?null:(this.stmts.updateWebProject.run(t.name??r.name,t.config_json===void 0?r.config_json:t.config_json,$(),t.id),this.getWebProject(t.id))}softDeleteWebProject(t){return this.stmts.softDeleteWebProject.run($(),t).changes===1}loadMailboxCursor(t,r){return this.stmts.loadMailboxCursor.get(t,r)??null}saveMailboxCursor(t){this.stmts.saveMailboxCursor.run(t.user_id,t.mailbox_key,t.last_processed_version_id,t.last_processed_seq??null,t.last_processed_at)}addUsage(t){this.stmts.addUsage.run(t.user_id,t.device_id,t.period,t.put,t.get,t.list,t.updated_at)}loadUsage(t,r,n){return this.stmts.loadUsage.get(t,r,n)??null}sumUsageForPeriod(t,r){let n=this.stmts.sumUsageForPeriod.get(t,r);return{put:n?.put??0,get:n?.get??0,list:n?.list??0}}upsertRootTeam(t){this.stmts.upsertRootTeam.run(t.teamfile_path,t.name,t.raw_text,t.raw_sha256,t.registered_at,t.last_seeded_at)}getRootTeam(t){return this.stmts.getRootTeam.get(t)??null}listRootTeams(){return this.stmts.listRootTeams.all()}insertTeamChatLog(t){return this.db.transaction(()=>{let r=this.stmts.insertTeamChatLog.run(t.root_teamfile,t.sender_teamfile,t.sender_alias,t.receiver_teamfile,t.receiver_alias,t.message,t.response,t.origin,t.status,t.error_detail,t.truncated,t.created_at),n=Number(r.lastInsertRowid);return sd(this.db,n,t),Xi(this.db,n,t),n})()}beginTeamChatLog(t){return this.db.transaction(()=>{let r=this.stmts.insertTeamChatLog.run(t.root_teamfile,t.sender_teamfile,t.sender_alias,t.receiver_teamfile,t.receiver_alias,t.message,t.response,t.origin,t.status,t.error_detail,t.truncated,t.created_at),n=Number(r.lastInsertRowid);return sd(this.db,n,t),n})()}finishTeamChatLog(t,r){this.db.transaction(()=>{if(this.stmts.updateTeamChatLogResponse.run(r.response,r.status,r.error_detail,r.truncated,t).changes!==1)throw new Error(`team_chat_log row disappeared during finish: ${t}`);Xi(this.db,t,r)})()}setCurrentlyHandlingMessage(t,r,n){this.db.transaction(()=>{bn(this.db,t,r,n)})()}clearCurrentlyHandlingMessage(t,r,n){return this.db.transaction(()=>Hi(this.db,t,r,n))()}listTeamChatLog(t){return this.stmts.listTeamChatLog.all(t)}listTeamChatLogSinceId(t,r=500){return this.stmts.listTeamChatLogSinceId.all(t,Math.max(1,Math.trunc(r)))}getMaxTeamChatLogId(){return this.stmts.getMaxTeamChatLogId.get()?.max_id??0}loadTeamChatLogCursor(t){return this.stmts.loadTeamChatLogCursor.get(t)??null}saveTeamChatLogCursor(t){this.stmts.saveTeamChatLogCursor.run(t.cursor_key,t.last_pushed_id,t.updated_at)}startTrackedInvocation(t){return this.db.transaction(()=>this.startTrackedInvocationInner(t))()}startTrackedInvocationInner(t){let r=t.started_at??$(),n=t.holder_host??As(),s=t.last_heartbeat_at??r,i=this.stmts.insertTrackedInvocation.run(t.kind,t.origin,t.scope_teamfile??null,t.from_identity,t.target_teamfile??null,t.target_alias??null,t.root_teamfile??null,t.cwd??null,Lt(t.command),r,t.holder_pid??null,n,s,Lt(t.meta),t.launch_source??t.kind,t.request_payload??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return f_(this.db,o),o}getTrackedInvocation(t){return this.stmts.getTrackedInvocation.get(t)??null}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}finishTrackedInvocation(t,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,Lt(r.result_summary),Lt(r.error),r.team_chat_log_id??null,Lt(r.meta),n,t).changes!==1)return null;let i=this.getTrackedInvocation(t);return Ji(this.db,i),i})()}reclaimTrackedInvocationIfUnchanged(t,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,Lt(n.result_summary),Lt(n.error),n.team_chat_log_id??null,Lt(n.meta),s,t,r.holder_pid,r.holder_host,r.started_at,r.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(t);return Ji(this.db,o),o})()}heartbeatTrackedInvocation(t,r=$()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(r,t).changes!==1)return null;let s=this.getTrackedInvocation(t);return p_(this.db,s,r),s})()}updateTrackedInvocationRequestPayload(t,r){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(r,t).changes!==1?null:(__(this.db,t,r),this.getTrackedInvocation(t)))()}linkTrackedInvocationMessage(t,r){return this.db.transaction(()=>this.stmts.linkTrackedInvocationChatLog.run(r,t).changes!==1?null:(h_(this.db,t,tr(r)),this.getTrackedInvocation(t)))()}abortTrackedInvocationAndTerminalizeMessage(t,r,n){return this.db.transaction(()=>{let s=$();if(this.stmts.abortTrackedInvocationIfUnchanged.run(s,Lt(n),t,r.holder_pid,r.holder_host,r.started_at,r.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(t);return Ji(this.db,o),o.team_chat_log_id!==null&&this.terminalizeLinkedChatMessage(o.team_chat_log_id,n),o})()}terminalizeLinkedChatMessage(t,r){let n=this.stmts.getTeamChatLogById.get(t);n===void 0||n.status!=="running"||this.stmts.terminalizeTeamChatLogIfRunning.run("error",r,t).changes!==1||Xi(this.db,t,{root_teamfile:n.root_teamfile,sender_teamfile:n.sender_teamfile,sender_alias:n.sender_alias,receiver_teamfile:n.receiver_teamfile,receiver_alias:n.receiver_alias,message:n.message,response:null,origin:n.origin,status:"error",error_detail:r,truncated:n.truncated,created_at:$()})}listClaimableTerminalTrackedInvocations(t){let r=["status IN ('done', 'error', 'busy', 'cancelled')","ended_at IS NOT NULL","notified_by IS NULL"],n=[];t.from!==void 0&&(r.push("from_identity = ?"),n.push(t.from)),t.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(t.scope_teamfile));let s=Math.max(1,Math.min(1e3,Math.trunc(t.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(t,r,n=$()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(r,n,t).changes!==1)return null;let i=this.getTrackedInvocation(t);return m_(this.db,i,r,n),i})()}listTrackedInvocations(t={}){let r=[],n=[];t.from!==void 0&&(r.push("from_identity = ?"),n.push(t.from)),t.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(t.scope_teamfile)),t.status!==void 0&&(r.push("status = ?"),n.push(t.status)),t.kind!==void 0&&(r.push("kind = ?"),n.push(t.kind)),t.origin!==void 0&&(r.push("origin = ?"),n.push(t.origin));let s=Math.max(1,Math.min(1e3,Math.trunc(t.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(t={}){let r=[],n=[];t.from!==void 0&&(r.push("from_identity = ?"),n.push(t.from)),t.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(t.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(t={}){return this.listTrackedInvocations({...t,status:"running"})}enqueueMail(t){return this.sendMailboxMessage(t)}sendMailboxMessage(t){return this.db.transaction(()=>{let n=this.stmts.insertMailboxMessage.run(t.receiver_teamfile,t.receiver_alias,t.sender_teamfile??null,t.sender_alias??null,t.root_teamfile??null,ws(t.payload),t.created_at??$(),t.remote_transport??null,t.remote_message_id??null,t.remote_thread_id??null,t.meta??null,t.message_type??"request",t.reply_mode??"pull",t.request_mailbox_id??null),s=this.getMailboxMessage(Number(n.lastInsertRowid));return nd(this.db,s,{provider:t.receiver_provider,sessionId:t.receiver_session_id},{provider:t.sender_provider,sessionId:t.sender_session_id}),s})()}listEnqueuedRequestMailFromSender(t,r,n,s){return this.stmts.listEnqueuedRequestMailFromSender.all(t,r,n,s)}listEnqueuedResponseMailFromSender(t,r,n,s){return this.stmts.listEnqueuedResponseMailFromSender.all(t,r,n,s)}listRelayMailboxLanes(t){return this.stmts.listRelayMailboxLanes.all(Math.max(1,Math.trunc(t)))}markMailDelivered(t,r,n){let s=[...new Set(t.map(a=>Math.trunc(a)).filter(a=>Number.isInteger(a)&&a>0))];if(s.length===0)return 0;let i=ws(r),o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0;for(let d of s){let c=this.getMailboxMessage(d),u=this.stmts.markMailboxMessageDelivered.run(n,i,d);a+=u.changes,u.changes===1&&c!==null&&o.push(c)}let l=new Map;for(let d of o){if(d.message_type!=="request")continue;let c=`${d.receiver_teamfile}\0${d.receiver_alias}`,u=l.get(c);(u===void 0||Kr([u,d])?.id===d.id)&&l.set(c,d)}for(let d of o){let c=l.get(`${d.receiver_teamfile}\0${d.receiver_alias}`)??null;bs(this.db,d,i,n,null,d.message_type==="request"&&c!==null?{action:"clear",messageId:De(c.id)}:null)}this.db.exec("COMMIT");for(let d of o)Sr("mailbox_delivery_delivered",d,{transition:d.delivering_at===null?"pending->delivered":"delivering->delivered",delivered_at:n});return a}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}markRelayRequestDelivered(t,r,n){let s=ws(r),i=[],o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0;for(let c of t){if(this.stmts.markMailboxMessageDeliveredIfUnchanged.run(n,s,c.id,c.delivering_at,c.delivery_holder_pid,c.delivery_holder_host).changes!==1){o.push(c);continue}a+=1,i.push(c)}let l=Kr(i),d=l===null?null:{action:"clear",messageId:De(l.id)};for(let c of i)bs(this.db,c,s,n,null,d);this.db.exec("COMMIT");for(let c of i)Sr("mailbox_delivery_delivered",c,{transition:"delivering->delivered",delivered_at:n,finalizer:"lease-cas"});for(let c of o)Sr("mailbox_delivery_finalize_skipped",c,{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(t,r,n){let s=ws(r),i=[],o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0,l=0;for(let p of t){if(this.stmts.markMailboxMessageDeliveredIfUnchanged.run(n,s,p.id,p.delivering_at,p.delivery_holder_pid,p.delivery_holder_host).changes!==1){o.push(p);continue}a+=1,i.push(p)}let d=[...i].sort((p,h)=>p.created_at.localeCompare(h.created_at)||p.id-h.id),c=Kr(i),u=null;if(c!==null&&c.sender_teamfile!==null&&c.sender_alias!==null){let p=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=p.changes,p.changes===1&&(u=this.getMailboxMessage(Number(p.lastInsertRowid)),u===null))throw new Error("mailbox response disappeared during event append")}let f=u===null?null:De(u.id),m=c===null?null:{action:"clear",messageId:De(c.id)};for(let p of i)bs(this.db,p,s,n,c!==null&&p.id!==c.id?f:null,m);u!==null&&nd(this.db,u,{},{},d.map(p=>De(p.id))),this.db.exec("COMMIT");for(let p of i)Sr("mailbox_delivery_delivered",p,{transition:"delivering->delivered",delivered_at:n,finalizer:"lease-cas-with-response"});for(let p of o)Sr("mailbox_delivery_finalize_skipped",p,{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(t,r,n=process.pid,s=As()){let i=[...new Set(t.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&&(t_(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)Sr("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(t){let r=[...new Set(t.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&&(id(this.db,o,"explicit-clear"),n.push(o))}this.db.exec("COMMIT");for(let i of n)Sr("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(t,r="delivery-failure"){return this.db.transaction(()=>{let s=this.getMailboxMessage(t.id);if(this.stmts.clearMailboxMessageDeliveryIfUnchanged.run(t.id,t.delivering_at,t.delivery_holder_pid,t.delivery_holder_host).changes!==1)return null;if(s===null)throw new Error("mailbox row disappeared during claim release");return s.delivering_at!==null&&id(this.db,s,r),this.getMailboxMessage(t.id)})()}reclaimStaleMailboxDeliveries(t){let r=this.stmts.listInFlightMailboxDeliveries.all(),n=[],s=[];this.db.exec("BEGIN IMMEDIATE");try{for(let i of r){let o=Mx(i,t);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)Sr(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:t,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(t,r){return this.stmts.listDeliveredReceiptsForSender.all(t,r)}listOutboundPendingForSender(t,r){return this.stmts.listOutboundPendingForSender.all(t,r)}getMailboxMessage(t){return this.stmts.getMailboxMessage.get(t)??null}peekMailboxMessages(t,r=1e3){return this.stmts.listMailboxMessagesForReceiver.all(t.receiver_teamfile,t.receiver_alias,Math.max(1,Math.min(1e3,Math.trunc(r))))}recvMailboxMessages(t){return this.recvMailboxMessagesTxn(t.receiver_teamfile,t.receiver_alias)}updateTeamChatLogResponse(t,r){this.stmts.updateTeamChatLogResponse.run(r.response,r.status,r.error_detail,r.truncated,t)}getAgentInflight(t,r){return this.stmts.getAgentInflight.get(t,r)??null}listAgentInflight(){return this.stmts.listAgentInflight.all()}tryAcquireAgentInflight(t,r){return this.tryAcquireAgentInflightTxn(t,r)}heartbeatAgentInflight(t,r,n=$()){return this.db.transaction(()=>{let s=this.getAgentInflight(t.receiver_teamfile,t.receiver_alias);return s===null||s.sender_teamfile!==t.sender_teamfile||s.sender_alias!==t.sender_alias||s.started_at!==t.started_at?!1:s_(this.db,s,r,n)})()}clearAgentInflight(t,r){this.db.transaction(()=>{let s=this.getAgentInflight(t,r);if(s===null)return;this.stmts.clearAgentInflight.run(t,r).changes===1&&ks(this.db,s,"INFLIGHT_RECLAIM","stale")})()}clearObservedTerminalAgentInflight(t,r,n){return this.db.transaction(()=>{let i=this.getAgentInflight(t,r),o=this.stmts.clearObservedTerminalAgentInflight.run({receiver_teamfile:t,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&&ks(this.db,i,"INFLIGHT_RELEASE"),o.changes===1})()}releaseAgentInflight(t,r){this.db.exec("BEGIN IMMEDIATE");try{let n=this.getAgentInflight(t.receiver_teamfile,t.receiver_alias);if(n===null||n.sender_teamfile!==t.sender_teamfile||n.sender_alias!==t.sender_alias)return this.db.exec("COMMIT"),!1;if(r!==void 0&&this.db.prepare(`SELECT lease_id FROM agent_state
|
|
1624
1624
|
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(t.receiver_teamfile,t.receiver_alias)?.lease_id!==r)return this.db.exec("COMMIT"),!1;if(n.active_count<=1){let i=this.stmts.clearAgentInflightIfSender.run(t.receiver_teamfile,t.receiver_alias,t.sender_teamfile,t.sender_alias);return i.changes===1&&ks(this.db,n,"INFLIGHT_RELEASE"),this.db.exec("COMMIT"),i.changes===1}let s=this.stmts.decrementAgentInflight.run(t.receiver_teamfile,t.receiver_alias,t.sender_teamfile,t.sender_alias);return this.db.exec("COMMIT"),s.changes===1}catch(n){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),n}}clearAgentInflightOlderThan(t){return this.db.transaction(()=>{let n=this.listAgentInflight().filter(i=>i.started_at<t),s=0;for(let i of n)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(ks(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(t,r){let n=this.stmts.getRuntimeState.get(Ts,Ss(t,r),vs);return n===void 0?null:Jp(n.data)}setTerminalLock(t){this.db.transaction(()=>{let n=this.getTerminalLock(t.teamfile,t.alias);n!==null&&n.lock_id!==t.lock_id&&od(this.db,n,!0),this.stmts.upsertRuntimeState.run(Ts,Ss(t.teamfile,t.alias),vs,JSON.stringify(t),t.last_heartbeat),n?.lock_id!==t.lock_id&&i_(this.db,t)})()}heartbeatTerminalLock(t,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(t,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(Ts,Ss(t,r),vs,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(t,r,n){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(t,r);if(s===null||s.lock_id!==n)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(Ts,Ss(t,r),vs);return i.changes===1&&od(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(t,r,n){let s=this.stmts.getRuntimeState.get(t,r,n);return s===void 0?null:Cx(s.data)}tryAcquireRuntimeProcessLock(t,r,n,s,i=$()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(t,r,n);if(o!==null&&!$x(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:T_(),holder_pid:process.pid,holder_host:As(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(t,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(t,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(t,r,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(t,r,n);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(t){return this.stmts.getRun.get(t)??null}setRunCurrentState(t,r){return this.stmts.setRunCurrentState.run(r,t),this.stmts.getRun.get(t)??null}setRunPausedState(t,r,n){return this.stmts.setRunPausedState.run(r,n,t),this.stmts.getRun.get(t)??null}setRunPendingEscalationDecision(t,r){return this.stmts.setRunPendingEscalationDecision.run(r,t),this.stmts.getRun.get(t)??null}setRunTerminalState(t,r){return this.stmts.setRunTerminalState.run(r,$(),t),this.stmts.getRun.get(t)??null}pauseJob(t){return this.stmts.pauseJob.run(t),this.getJob(t)}resumeRun(t,r){return this.resumeRunTxn(t,r,$())}insertStep(t){let r=this.stmts.insertStep.run(t.run_id,t.parent_step_id??null,t.state_name,t.outcome??null,t.status_detail??null,$());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(t,r,n){return this.stmts.finishStep.run(r??null,n??null,$(),t),this.stmts.getStep.get(t)??null}listStepsForRun(t){return this.stmts.listStepsForRun.all(t)}listLatestStepOutcomesByState(t){let r=this.stmts.listLatestStepOutcomesByState.all(t),n={};for(let s of r)n[s.state_name]=s.outcome;return n}insertSubmittedPr(t){let r=this.stmts.insertSubmittedPr.run(t.repo,t.pr_url,t.issue_url??null,t.local_path??null,t.branch??null,t.head_sha??null,t.status??"watching",t.submitted_at??$(),t.last_known_state??null,t.created_by_run_id??null);return this.stmts.getSubmittedPr.get(r.lastInsertRowid)}listSubmittedPrs(t){return t?.status!==void 0?this.stmts.listSubmittedPrsByStatus.all(t.status):this.stmts.listSubmittedPrs.all()}getSubmittedPr(t){return this.stmts.getSubmittedPr.get(t)??null}findSubmittedPrByUrl(t){return this.stmts.findSubmittedPrByUrl.get(t)??null}insertStepArtifact(t){let r=this.stmts.insertStepArtifact.run(t.step_id,t.kind,t.path??null,t.content??null,t.sha??null,t.provider_call_mode??null,$());return this.stmts.getStepArtifact.get(r.lastInsertRowid)}insertExternalObject(t){let n=this.stmts.insertExternalObject.run(t.type,t.provider,t.project_id,t.run_id??null,t.external_id,t.url??null,t.status??null,t.metadata??null,t.last_seen_at??null,$()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(t.provider,t.type,t.external_id),inserted:n}}insertExternalSignal(t){let r=this.stmts.insertExternalSignal.run(t.object_id,t.kind,t.source??null,t.occurred_at??null,t.payload??null,t.signal_hash??null,null,$()),n=r.changes===1;return{row:t.signal_hash===void 0||t.signal_hash===null?this.stmts.getExternalSignal.get(r.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(t.object_id,t.kind,t.signal_hash),inserted:n}}raiseAttention(t){let r=this.stmts.insertAttention.run(t.kind,t.severity??"warn",t.project_id??null,t.run_id??null,t.external_object_id??null,t.requires_user===!0?1:0,t.payload??null,$());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(t){return this.stmts.ackAttention.run($(),t),this.stmts.getAttention.get(t)??null}upsertDurableMemory(t){let r=$();return this.stmts.upsertDurableMemory.run(t.project_id,t.type,t.name,t.description??null,t.body,r,r),this.stmts.getDurableMemoryByName.get(t.project_id,t.name)}getDurableMemoryByName(t,r){return this.stmts.getDurableMemoryByName.get(t,r)??null}deleteDurableMemory(t,r){return this.stmts.deleteDurableMemory.run(t,r).changes>0}listDurableMemory(t,r){return r!==void 0?this.stmts.listDurableMemoryByType.all(t,r):this.stmts.listDurableMemory.all(t)}indexDurableMemory(t,r){return r!==void 0&&r.length>0?this.stmts.listDurableMemory.all(t).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(t).map(({name:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}recordSessionSize(t){let r=this.stmts.insertSessionSize.run(t.team_name,t.alias,t.sessionid,t.input_tokens??null,t.cache_tokens??null,t.output_tokens??null,t.total_tokens??null,t.observed_at??$());return this.stmts.getSessionSize.get(r.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(t,r,n=20){return this.stmts.sessionSizeHistory.all(t,r,n)}insertSessionEvent(t){let r=this.stmts.insertSessionEvent.run(t.run_id,t.step_id??null,t.kind,t.timestamp_ms,t.payload,t.payload_truncated??0,t.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(r.lastInsertRowid)}listSessionEvents(t,r){return r!==void 0?this.stmts.listSessionEventsSince.all(t,r):this.stmts.listSessionEvents.all(t)}listSessionEventsSince(t,r=1e3){return this.stmts.listAllEventsSince.all(t,r)}latestAgentCall(t){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(t);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(t){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(t),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(t){this.stmts.upsertRollupStat.run(t.run_id,t.step_id??null,t.metric_kind,t.value,t.bucket_start_ms,t.bucket_end_ms,t.updated_at)}listRollupStats(t){return this.stmts.listRollupStats.all(t)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(t){this.stmts.setRollupCursor.run("last_event_id",t)}insertDriftSignal(t){let r=this.stmts.insertDriftSignal.run(t.team_member_id,t.project_id??null,t.signal_kind,t.severity,t.description,t.detected_at,t.expires_at??null,t.payload??null);return this.stmts.getDriftSignal.get(r.lastInsertRowid)}listDriftSignals(t={}){return t.team_member_id!==void 0&&t.unacked?this.stmts.listUnackedDriftByMember.all(t.team_member_id):t.team_member_id!==void 0?this.stmts.listDriftByMember.all(t.team_member_id):t.project_id!==void 0?this.stmts.listDriftByProject.all(t.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(t,r,n){return this.stmts.findUnackedDrift.get(t,r??null,n)!==void 0}acknowledgeDriftSignal(t){return this.stmts.ackDriftSignal.run(Date.now(),t),this.stmts.getDriftSignal.get(t)??null}insertInteractiveSession(t){let r=Date.now();return this.stmts.insertInteractiveSession.run(t.run_id,t.step_id,t.state_name,t.status,r,r),this.stmts.getInteractiveSessionByStepId.get(t.step_id)}getInteractiveSessionByStepId(t){return this.stmts.getInteractiveSessionByStepId.get(t)??null}getInteractiveSessionByRunAndState(t,r){return this.stmts.getInteractiveSessionByRunAndState.get(t,r)??null}setInteractiveAgentOutput(t,r,n){this.stmts.setInteractiveAgentOutput.run(r,n,Date.now(),t)}resumeInteractive(t,r,n){return this.resumeInteractiveTxn(t,r,n,$())}resumeEscalation(t,r){return this.resumeEscalationTxn(t,r,$())}}});import{realpathSync as Fx}from"node:fs";import{resolve as Ux}from"node:path";function cd(e){let t=Ux(e);try{return Fx(t)}catch{return t}}var b_=w(()=>{"use strict"});import{platform as k_}from"node:os";function Ct(e){let t=new xs;for(let r of e)t.registerAdapter(r);return t}var xs,ud=w(()=>{"use strict";b_();xs=class{providers=[];adapters=new Map;register(t){this.providers.push(t)}async listAll(t){let r=[],n=t?.provider?this.providers.filter(o=>o.name===t.provider):this.providers,s=await Promise.all(n.map(o=>o.discoverSessions()));for(let o of s)r.push(...o);let i=r;if(t?.workspace){let o=cd(t.workspace);i=i.filter(a=>cd(a.cwd)===o)}if(t?.from){let o=t.from.getTime();i=i.filter(a=>a.modifiedAt.getTime()>=o)}if(t?.to){let o=t.to.getTime();i=i.filter(a=>a.modifiedAt.getTime()<=o)}return i.sort((o,a)=>a.modifiedAt.getTime()-o.modifiedAt.getTime()),t?.limit&&(i=i.slice(0,t.limit)),i}async getSession(t,r){let n=r?this.providers.filter(s=>s.name===r):this.providers;for(let s of n){let i=await s.loadSession(t);if(i)return i}return null}async resolveSession(t,r){let n=await this.resolveSessions(t,r);return n.length===1?n[0]:null}async resolveSessions(t,r){let n=r?this.providers.filter(i=>i.name===r):this.providers,s=[];for(let i of n){let o=await i.resolveSessionPath(t);o&&s.push({provider:i,filePath:o})}return s}getWatchTargets(){let t=k_()==="darwin"||k_()==="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:t,filePattern:s.filePattern});return r}async deleteSession(t,r){let n=await this.resolveSession(t,r);return n?n.provider.deleteSession(t):!1}registerAdapter(t){this.adapters.set(t.name,t),this.providers.push({name:t.name,discoverSessions:()=>t.discover(),loadSession:r=>t.load(r),resolveSessionPath:r=>t.resolvePath(r),deleteSession:r=>t.delete(r),getWatchPaths:()=>t.getWatchPaths?.()??[]})}getAdapter(t){return this.adapters.get(t)}getAllAdapters(){return[...this.adapters.values()]}}});import{createReadStream as I_}from"node:fs";import{createInterface as N_}from"node:readline";import{stat as Wx}from"node:fs/promises";import{homedir as qx}from"node:os";function A_(e){try{let t=JSON.parse(e);return t===null||typeof t!="object"||Array.isArray(t)?void 0:t}catch{return}}async function*He(e){let t=I_(e,{encoding:"utf-8"}),r=N_({input:t,crlfDelay:1/0});try{for await(let n of r){let s=n.trim();if(!s)continue;let i=A_(s);i!==void 0&&(yield i)}}finally{t.destroy()}}async function Xe(e,t){let r=[],n=I_(e,{encoding:"utf-8"}),s=N_({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=A_(o);if(a!==void 0&&r.push(a),r.length>=t)break}}finally{s.close(),n.destroy()}return r}async function Ce(e){let t=await Wx(e);return{createdAt:t.birthtime,modifiedAt:t.mtime}}function fe(e){return e.replace(/\\n/g,`
|
|
1625
1625
|
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function J(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function $t(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}var ve,nr=w(()=>{"use strict";ve=qx()});import{readdir as Yi,stat as x_,unlink as Bx}from"node:fs/promises";import{join as Nn,basename as R_}from"node:path";function Hx(e){return e==="file-history-snapshot"||e==="progress"||e==="system"||e==="queue-operation"}function Xx(e){if(e.type==="system"){let t=e.message?.content;if(typeof t=="string"&&t.trim())return fe(t.trim());if(t!==void 0)return JSON.stringify(t,null,2)}return e.type==="progress"&&e.data!==void 0?JSON.stringify(e.data,null,2):JSON.stringify(e,null,2)}async function L_(e){let t=0,r=0,n=0,s=0,i=0,o=0,a;for await(let l of He(e))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;t++}}else if(l.type==="assistant"&&l.message){let d=l.message.content;if(Array.isArray(d))for(let u of d)u.type==="text"&&t++;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:t,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a}}function Jx(e){let t=Gx(e),r=new Set;for(let n of e){if(n.role!=="tool_use"||n.toolName!=="Bash"||n.toolInputData?.run_in_background!==!0||n.toolCallId===void 0)continue;let s=t.get(n.toolCallId);if(s===void 0)continue;let i=s.content.match(/Command running in background with ID:\s*([A-Za-z0-9_-]+)/)?.[1];i!==void 0&&(r.add(i),n.backgroundTaskId=i,s.backgroundTaskId=i)}for(let n of e){if(n.role!=="tool_use"||n.toolName!=="TaskOutput"&&n.toolName!=="TaskStop"||n.toolCallId===void 0)continue;let s=n.toolInputData?.task_id;if(typeof s!="string"||!r.has(s))continue;n.backgroundTaskId=s;let i=t.get(n.toolCallId);i!==void 0&&(i.backgroundTaskId=s)}}function Gx(e){let t=new Map;for(let r of e)r.role==="tool_result"&&r.toolCallId!==void 0&&t.set(r.toolCallId,r);return t}var zi,O_=w(()=>{"use strict";nr();zi=class{name="claude";claudeDir;projectsDir;constructor(t={}){this.claudeDir=t.claudeDir||Nn(ve,".claude"),this.projectsDir=Nn(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let t=[],r;try{r=await Yi(this.projectsDir)}catch{return t}for(let n of r){let s=Nn(this.projectsDir,n);if(!(await x_(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Yi(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=R_(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let d=Nn(s,a);try{let c=await this.extractSummary(d,l);c&&t.push(c)}catch{}}}return t}async extractSummary(t,r){let n=await Xe(t,50),s=await Ce(t),i="",o,a,l,d,c,u;for(let m of n)if(!Hx(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=J(p.trim(),80)),c=J(p.trim(),80)}}if(!i)return null;let f=await L_(t);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:t,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(t){let r=await this.resolveSessionFile(t);if(!r)return null;let n=await Ce(r),s=[],i="",o,a,l,d,c,u,f,m=t,p;for await(let _ of He(r))if(_.type!=="file-history-snapshot"&&!_.isSidechain){if(!i&&_.cwd&&(i=_.cwd),!o&&_.slug&&(o=_.slug),!a&&_.version&&(a=_.version),!d&&_.gitBranch&&(d=_.gitBranch),!f&&_.timestamp&&(f=new Date(_.timestamp)),_.sessionId&&(m=_.sessionId),_.type==="system"||_.type==="progress"||_.type==="queue-operation"){s.push({role:"system",timestamp:new Date(_.timestamp||0),content:Xx(_)});continue}if(_.type==="user"&&_.message){if(_.isMeta)continue;let g=new Date(_.timestamp||0),y=_.message.content;if(typeof y=="string"){if(y.includes("<command-name>")||y.includes("<local-command-"))continue;c||(c=J(y.trim(),80)),u=J(y.trim(),80),p=void 0,s.push({role:"user",timestamp:g,content:fe(y.trim())})}else if(Array.isArray(y)){for(let E of y)if(E.type==="tool_result"){let v=typeof E.content=="string"?fe(E.content):JSON.stringify(E.content);s.push({role:"tool_result",timestamp:g,content:v,toolCallId:E.tool_use_id})}}}if(_.type==="assistant"&&_.message){_.message.stop_reason===null||_.message.stop_reason==="tool_use"?p="in_progress":typeof _.message.stop_reason=="string"&&(p="complete"),_.message.model&&(l=_.message.model);let g=new Date(_.timestamp||0),y=_.message.content;if(Array.isArray(y))for(let E of y)E.type==="text"&&E.text?s.push({role:"assistant",timestamp:g,content:fe(E.text),model:_.message.model,...typeof _.message.stop_reason=="string"?{stopReason:_.message.stop_reason}:{}}):E.type==="tool_use"?s.push({role:"tool_use",timestamp:g,content:E.name||"unknown tool",toolName:E.name,toolInput:JSON.stringify(E.input,null,2),toolInputData:E.input,toolCallId:E.id,model:_.message.model,...typeof _.message.stop_reason=="string"?{stopReason:_.message.stop_reason}:{}}):E.type==="thinking"&&E.thinking&&s.push({role:"thinking",timestamp:g,content:E.thinking})}}if(!i)return null;Jx(s);let h=await L_(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,turnStatus:p,firstUserMessage:c,lastUserMessage:u,messageCount:h.messageCount,filePath:r,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:h.totalCacheWriteInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,lastInputTokens:h.lastInputTokens||void 0,lastTokenUsage:h.lastTokenUsage,messages:s}}async resolveSessionPath(t){return this.resolveSessionFile(t)}async deleteSession(t){let r=await this.resolveSessionFile(t);return r?(await Bx(r),!0):!1}async resolveSessionFile(t){let r;try{r=await Yi(this.projectsDir)}catch{return null}let n=[];for(let o of r){let a=Nn(this.projectsDir,o);if(!(await x_(a).catch(()=>null))?.isDirectory())continue;let d;try{d=await Yi(a)}catch{continue}for(let c of d){if(!c.endsWith(".jsonl"))continue;let u=R_(c,".jsonl");/^[0-9a-f]{8}-/.test(u)&&n.push({filePath:Nn(a,c),fileSessionId:u})}}let s=n.find(o=>o.fileSessionId===t);if(s)return s.filePath;let i=n.filter(o=>o.fileSessionId.startsWith(t));if(i.length===1)return i[0].filePath;for(let o of n){let a=await Xe(o.filePath,20);for(let l of a)if(l.slug&&l.slug===t)return o.filePath}return null}}});import{readFileSync as Kx,writeFileSync as yV,mkdirSync as EV}from"node:fs";import{join as Vx,dirname as TV}from"node:path";import{homedir as Yx}from"node:os";function Zx(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Qx(e){let t=e.indexOf("=");if(t===-1)return null;let r=e.slice(0,t).trim(),n=Zx(e.slice(t+1).trim());return r?{key:r,value:n}:null}function eR(e){let t=e.trim();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1).trim():null}function Zi(e){return"'"+e.replace(/'/g,"'\\''")+"'"}function tR(){return Vx(Yx(),".lmctl","config.toml")}function md(e){let t=e??tR(),r;try{r=Kx(t,"utf-8")}catch{return{tools:{}}}return rR(r)}function C_(e){if(typeof e=="number")return Number.isFinite(e)?e:null;let t=String(e).trim();if(!t)return null;let r=t.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 rR(e){let t={},r={},n=e.split(`
|
|
1626
|
-
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let f=t[s.tool]??{};if(s.profile){let m=f.profiles?.[s.profile]??{};i.description&&(m.description=i.description),i.flags!==void 0&&(m.flags=i.flags),f.profiles||(f.profiles={}),f.profiles[s.profile]=m}else i.start&&(f.start=i.start),i.resume&&(f.resume=i.resume),i.agent&&(f.agent=i.agent),i.profile_flag!==void 0&&(f.profile_flag=i.profile_flag);t[s.tool]=f}else if(s.kind==="compact"){let f=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let m=C_(i.min);m!==null&&(f.min=m)}if(i.max!==void 0){let m=C_(i.max);m!==null&&(f.max=m)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=f):r.global=f}i={}}for(let f of n){let m=f.trim();if(!m||m.startsWith("#"))continue;let p=eR(m);if(p!==null){if(o=!0,l(),p.startsWith("tool.")){let _=".profile.",g=p.indexOf(_);g!==-1?s={kind:"tool",tool:p.slice(5,g),profile:p.slice(g+_.length)}:s={kind:"tool",tool:p.slice(5),profile:null}}else p==="compact"?s={kind:"compact",provider:null}:p.startsWith("compact.")?s={kind:"compact",provider:p.slice(8)}:s={kind:"none"};continue}let h=Qx(m);h&&s.kind!=="none"?i[h.key]=h.value:h&&!o&&(a[h.key]=h.value)}l();let d={tools:t};(r.global||r.providers)&&(d.compact=r);let c=a.site_name;c!==void 0&&c.length>0&&(d.site_name=c);let u=a.mailbox_queue_enabled;return u!==void 0&&u.trim().length>0&&(d.mailbox_queue_enabled=u.trim().toLowerCase()!=="false"),d}function $_(e){return e.site_name??null}function M_(e=process.env){let t=e.LMCTL_MAILBOX_QUEUE_ENABLED;if(t!==void 0&&t.trim().length>0)return t.trim().toLowerCase()!=="false";try{return md().mailbox_queue_enabled??!
|
|
1626
|
+
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let f=t[s.tool]??{};if(s.profile){let m=f.profiles?.[s.profile]??{};i.description&&(m.description=i.description),i.flags!==void 0&&(m.flags=i.flags),f.profiles||(f.profiles={}),f.profiles[s.profile]=m}else i.start&&(f.start=i.start),i.resume&&(f.resume=i.resume),i.agent&&(f.agent=i.agent),i.profile_flag!==void 0&&(f.profile_flag=i.profile_flag);t[s.tool]=f}else if(s.kind==="compact"){let f=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let m=C_(i.min);m!==null&&(f.min=m)}if(i.max!==void 0){let m=C_(i.max);m!==null&&(f.max=m)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=f):r.global=f}i={}}for(let f of n){let m=f.trim();if(!m||m.startsWith("#"))continue;let p=eR(m);if(p!==null){if(o=!0,l(),p.startsWith("tool.")){let _=".profile.",g=p.indexOf(_);g!==-1?s={kind:"tool",tool:p.slice(5,g),profile:p.slice(g+_.length)}:s={kind:"tool",tool:p.slice(5),profile:null}}else p==="compact"?s={kind:"compact",provider:null}:p.startsWith("compact.")?s={kind:"compact",provider:p.slice(8)}:s={kind:"none"};continue}let h=Qx(m);h&&s.kind!=="none"?i[h.key]=h.value:h&&!o&&(a[h.key]=h.value)}l();let d={tools:t};(r.global||r.providers)&&(d.compact=r);let c=a.site_name;c!==void 0&&c.length>0&&(d.site_name=c);let u=a.mailbox_queue_enabled;return u!==void 0&&u.trim().length>0&&(d.mailbox_queue_enabled=u.trim().toLowerCase()!=="false"),d}function $_(e){return e.site_name??null}function M_(e=process.env){let t=e.LMCTL_MAILBOX_QUEUE_ENABLED;if(t!==void 0&&t.trim().length>0)return t.trim().toLowerCase()!=="false";try{return md().mailbox_queue_enabled??!1}catch{return!1}}function nR(e,t,r){if(!r)return"";let n=e.tools[t]??fd[t],s=n?.profiles?.[r]?.flags??fd[t]?.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 "${t}"`)}function D_(e,t){return!!e.tools[t]}function j_(e,t,r,n,s){let i=e.tools[t]??fd[t],o;if(i?.agent){let l=Zi(n);o=i.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=zx[t];if(!l)throw new Error(`No agent command configured for tool "${t}"`);let d=l.argv.map(c=>c.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,n));if(l.mode==="stdin"){let c=d.map(Zi).join(" ");o=`printf '%s\\n' ${Zi(n)} | ${c}`}else o=d.map(Zi).join(" ")}let a=nR(e,t,s);return a&&(o+=" "+a),o}var fd,zx,Qi=w(()=>{"use strict";fd={claude:{start:"claude",resume:"claude --resume {{session_id}} --dangerously-skip-permissions",profiles:{default:{description:"Default profile",flags:""}}},codex:{start:"codex",resume:"codex resume {{session_id}} --dangerously-bypass-approvals-and-sandbox",profiles:{default:{description:"Default profile",flags:""}}},opencode:{start:"opencode",resume:"opencode --session {{session_id}}",profiles:{default:{description:"Default profile",flags:""}}},gemini:{start:"gemini",resume:"gemini --resume {{session_id}} -y",profiles:{default:{description:"Default profile",flags:""}}},copilot:{start:"copilot",resume:"copilot --resume={{session_id}} --yolo",profiles:{default:{description:"Default profile",flags:""}}},qwen:{start:"qwen",resume:"qwen --resume {{session_id}} --approval-mode yolo",profiles:{default:{description:"Default profile",flags:""}}},agy:{start:"agy",resume:"agy --conversation {{session_id}} --dangerously-skip-permissions",profiles:{default:{description:"Default profile",flags:""}}},kimi:{start:"kimi --auto",resume:"kimi --session {{session_id}} --auto",profiles:{default:{description:"Default profile",flags:""}}}},zx={claude:{mode:"argv",argv:["claude","-p","{{prompt}}","--resume","{{session_id}}"]},codex:{mode:"argv",argv:["codex","exec","--dangerously-bypass-approvals-and-sandbox","--skip-git-repo-check","resume","{{session_id}}","{{prompt}}"]},opencode:{mode:"argv",argv:["opencode","run","--session","{{session_id}}","{{prompt}}"]},gemini:{mode:"argv",argv:["gemini","-p","{{prompt}}","--resume","{{session_id}}"]},copilot:{mode:"argv",argv:["gh","copilot","--","--resume={{session_id}}","-p","{{prompt}}","-s","--allow-all-tools"]},qwen:{mode:"argv",argv:["qwen","-p","{{prompt}}","--resume","{{session_id}}","--approval-mode","yolo"]},agy:{mode:"argv",argv:["agy","--conversation","{{session_id}}","-p","{{prompt}}","--dangerously-skip-permissions","--print-timeout","8h"]},kimi:{mode:"argv",argv:["kimi","-p","{{prompt}}","--session","{{session_id}}","--output-format","stream-json"]}}});function P_(e=process.env){let t=e.LMCTL_ONE_SHOT_TIMEOUT_MS;if(!t)return 6e5;let r=Number(t);return!Number.isFinite(r)||r<=0?6e5:r}var F_=w(()=>{"use strict"});var sR,ge,eo,gt=w(()=>{"use strict";sR="ACK: waiting for explicit lmctl task.",ge=`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: ${sR}`,eo=`send this exact lmctl seed instruction: "${ge}"`});function br(e,t){let r={...e??process.env,PWD:t};return delete r.OLDPWD,r}function oR(e,t){return t===void 0||t.length===0?e:{...e??process.env,[Rs]:t}}function Je(e,t,r,n="chat"){return{...oR(br(e,t),r),[iR]:n}}var Rs,iR,yt=w(()=>{"use strict";Rs="LMCTL_SELF_SESSIONID",iR="LMCTL_LAUNCH_SOURCE"});import{spawn as U_}from"node:child_process";import{mkdirSync as aR}from"node:fs";var pd,xe,Mt=w(()=>{"use strict";Qi();F_();gt();yt();pd=class e extends Error{cancelReason;constructor(t,r){super(t),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,e.prototype)}},xe=class e{name;capabilities;injection;provider;binary;seedArgs;seedStdin;resumeTemplate;startTemplate;transportFn;constructor(t){this.name=t.provider.name,this.provider=t.provider,this.capabilities=t.capabilities,this.injection=t.injection,this.binary=t.binary,this.seedArgs=t.seedArgs,this.seedStdin=t.seedStdin,this.resumeTemplate=t.resumeTemplate,this.startTemplate=t.startTemplate,this.transportFn=t.transport}discover(){return this.provider.discoverSessions()}load(t){return this.provider.loadSession(t)}resolvePath(t){return this.provider.resolveSessionPath(t)}delete(t){return this.provider.deleteSession(t)}getWatchPaths(){return this.provider.getWatchPaths?.()??[]}seedArgsFor(t){let r=t?.prompt;return r===void 0?this.seedArgs:this.seedArgs.map(n=>n===ge?r:n)}seed(t,r){return aR(t,{recursive:!0}),new Promise(n=>{let s;try{s=U_(this.binary,this.seedArgsFor(r),{cwd:t,env:br(void 0,t),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}
|
|
1627
1627
|
`: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(t,r){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,t)}startCommand(t){return this.startTemplate}manualSeedHint(t){return{launchCommand:`cd ${t} && ${this.binary}`,postLaunchNote:eo,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${t}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(t,r){if(r.userConfig&&D_(r.userConfig,this.name)){let s=r.userConfig.tools[this.name];if(s?.agent)return this.runOneShotAgent(t,r,s.agent)}let n=r.timeoutMs??e.DEFAULT_IDLE_TIMEOUT_MS;return n<=0&&!r.signal?this.transportFn(t,{...r,binary:this.binary}):this.withTimeouts(n,t,r)}withTimeouts(t,r,n){let s=new AbortController,i,o,a="",l,d=()=>{t<=0||(clearTimeout(i),i=setTimeout(()=>{n.onIdleWarning?.(t),c(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:t,status:"stalled",stalledAfterMs:t})},t))},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 pd("Turn cancelled","external"):p}),m=new Promise(p=>{l=p});return Promise.race([f,m])}runOneShotAgent(t,r,n){let s=j_(r.userConfig,this.name,r.sessionId,t,r.profile),i=Date.now();return new Promise((o,a)=>{let l=P_(r.env),d=U_(s,{shell:!0,cwd:r.cwd,env:Je(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 _=h.toString();m+=_,r.onDelta?.(_)}),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 _=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:_}):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 ro(e,t){let r;if(t&&typeof t=="object"){let n=t.code;typeof n=="number"&&(r=n)}return new ir(e,r,t)}var ct,Se,sr,to,ir,An=w(()=>{"use strict";ct=class extends Error{constructor(t,r){super(t,r),this.name=this.constructor.name}},Se=class extends ct{},sr=class extends ct{exitCode;signal;stderr;constructor(t,r,n=null,s){super(t),this.exitCode=r,this.signal=n,this.stderr=s}},to=class extends ct{line;constructor(t,r,n){super(t,{cause:n}),this.line=r}},ir=class extends ct{rpcCode;rpcData;constructor(t,r,n){super(t),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as hd from"node:child_process";function dR(e){if(typeof hd.spawnSync=="function")try{hd.spawnSync("taskkill",["/T","/F","/PID",String(e)],{windowsHide:!0})}catch{}}function W_(e){return e.exitCode!==null||e.signalCode!==null}function _d(e,t){return W_(e)?Promise.resolve(!0):new Promise(r=>{let n=!1,s=()=>{n||(n=!0,clearTimeout(i),r(!0))},i=setTimeout(()=>{n||(n=!0,e.removeListener("exit",s),r(!1))},t);e.once("exit",s)})}async function et(e,t={}){let r=Date.now(),n=t.stdinEnd!==!1,s=t.softDelayMs??5e3,i=t.killDelayMs??5e3,o=t.platform??process.platform,a=t.runTaskkill??dR;if(W_(e))return{signal:"natural",elapsedMs:Date.now()-r};if(n&&e.stdin&&!e.stdin.destroyed)try{e.stdin.end()}catch{}if(await _d(e,s))return{signal:"stdin",elapsedMs:Date.now()-r};if(o==="win32"&&typeof e.pid=="number")a(e.pid);else try{e.kill("SIGTERM")}catch{}if(await _d(e,i))return{signal:"SIGTERM",elapsedMs:Date.now()-r};if(o!=="win32")try{e.kill("SIGKILL")}catch{}return await _d(e,lR)?{signal:"SIGKILL",elapsedMs:Date.now()-r}:{signal:"abandoned",elapsedMs:Date.now()-r}}var lR,Ls=w(()=>{"use strict";lR=1e3});function q_(e){le()&&Fe({event:"legacy",msg:`[debug] ${e}`},{always:!0})}function kr(e,t){let r=uR[e];if(r)return r[t]??r.yolo}function mR(e,t){if(t.length===0)return!0;for(let r=0;r+t.length<=e.length;r++){let n=!0;for(let s=0;s<t.length;s++)if(e[r+s]!==t[s]){n=!1;break}if(n)return!0}return!1}function Et(e,t,r="yolo"){if(fR.has(e)){q_(`YOLO ${e} [mode=${r}]: ${e==="codex"?`JSON-RPC params (approvalPolicy=never, sandbox=${r==="plan"?"read-only":"danger-full-access"})`:e==="opencode"?".opencode/opencode.json (permission=allow)":e==="kimi"?`ACP session/set_config_option (configId=mode, value=${r==="plan"?"plan":"auto"})`:"protocol/config (out-of-band)"} \u2014 no argv flag`);return}let n=r==="plan"?kr(e,"plan"):cR[e];if(!n){let s=`unknown provider "${e}" \u2014 YOLO contract not configured. Add an entry to YOLO_FLAGS in src/providers/yolo-contract.ts before spawning this provider.`;throw M({event:"yolo_assert_failed",provider:e,reason:"unconfigured_provider",args:t.join(" "),message:s}),new Se(s)}if(!mR(t,n)){let s=n.join(" "),i=`${e} spawn missing YOLO flag '${s}' \u2014 YOLO is mandatory for every provider; see src/providers/yolo-contract.ts. Got argv: [${t.map(o=>JSON.stringify(o)).join(", ")}]`;throw M({event:"yolo_assert_failed",provider:e,reason:"flag_missing",required_flag:s,mode:r,args:t.join(" "),message:i}),new Se(i)}q_(`YOLO ${e} [mode=${r}]: argv flag '${n.join(" ")}'`)}var cR,uR,fR,xn=w(()=>{"use strict";An();pe();cR={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},uR={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"]}};fR=new Set(["codex","opencode","kimi"])});function B_(e){if(e.length===0)return"";if(e.length===1)return e[0];let t=[];for(let r=0;r<e.length;r++)r===0?t.push(e[r]):t.push(`
|
|
1628
1628
|
|
|
1629
1629
|
--- additional response (turn ${r+1} of ${e.length}; likely an injected mid-call notification) ---
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lmctl-ai/lmctl",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.241",
|
|
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",
|