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