@lmctl-ai/lmctl 0.2.470 → 0.2.472
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 +2 -2
- package/dist/cli/lmscript.js +1 -1
- package/dist/dsl.js +1 -1
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -2157,7 +2157,7 @@ ${r}`:r}function $$e(e,t){return gh(e)?.filterExpectedStderr?.(t)??t}function DZ
|
|
|
2157
2157
|
`):"":""}function k3(e){return e.model||e.message?.model}function M0e(e){let t=e.message?.content;return typeof t=="string"?t.length>0?1:0:$3(e).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function bh(e,t=!1){if(e!==void 0){if(typeof e=="string")return e;try{return JSON.stringify(e,null,t?2:void 0)}catch{return String(e)}}}function L0e(e){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let t=e;return bh(t.output??t.error??e)}return bh(e)}function $3(e){return Array.isArray(e.message?.content)?e.message.content:e.message?.parts??[]}function x3(e,t,r){let o=e.name||"tool";return{role:"tool_use",timestamp:t,content:o,toolName:o,toolInput:bh(e.args,!0),toolInputData:ro(e.args),toolCallId:e.id,model:r}}var Ub,A3=$(()=>{"use strict";Yt();Ub=class{name="qwen";baseDir;constructor(t){this.baseDir=t?.qwenDir||Ja(He,".qwen")}async discoverSessions(){let t=Ja(this.baseDir,"projects"),r;try{r=await Pb(t)}catch{return[]}let o=[];for(let n of r){let s=Ja(t,n,"chats"),i;try{i=await Pb(s)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=Ja(s,a);try{let u=await this.extractSummary(c,l);u&&o.push(u)}catch{}}}return o}async extractSummary(t,r){let o=!1,n=await Zt(t),s="(unknown)",i,a,l,c,u=0;for await(let d of Ot(t)){if(o=!0,d.cwd&&(s=d.cwd,d.version&&(a=d.version)),d.type==="system"&&d.cwd&&(s=d.cwd,d.version&&(a=d.version),d.model&&(i=d.model)),T3(d)){let f=I3(d).trim();f&&(l||(l=ge(f,80)),c=ge(f,80),u++)}if(S3(d)){let f=k3(d);f&&(i=f),u+=M0e(d)}}return o?{provider:"qwen",sessionId:r,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:t}:null}async loadSession(t){let r=await this.resolveSessionPath(t);if(!r)return null;let o=E3(r,".jsonl");return this.loadFromFile(r,o)}async loadFromFile(t,r){let o=await Zt(t),n="(unknown)",s,i,a,l,c,u,d=[],f=N0e();for await(let p of Ot(t)){if(C0e(f,p.usageMetadata),p.cwd&&(n=p.cwd,p.version&&(i=p.version),p.gitBranch&&(a=p.gitBranch)),p.type==="system"&&p.cwd&&(n=p.cwd,p.version&&(i=p.version),p.model&&(s=p.model),p.gitBranch&&(a=p.gitBranch)),!p.message)continue;let m=p.message,h=p.timestamp?new Date(p.timestamp):o.modifiedAt;if(p.type==="tool_result"){let g=$3(p).filter(_=>_.functionResponse!==void 0);g.length===0&&p.toolCallResult?.callId&&d.push({role:"tool_result",timestamp:h,content:bh(p.toolCallResult.resultDisplay??p.toolCallResult.error??p.toolCallResult.status)??"tool result",toolCallId:p.toolCallResult.callId});for(let _ of g){let w=_.functionResponse,y=L0e(w.response),b=bh(p.toolCallResult?.resultDisplay);d.push({role:"tool_result",timestamp:h,content:b??y??p.toolCallResult?.status??"tool result",toolName:w.name,toolCallId:p.toolCallResult?.callId??w.id,...y!==void 0?{toolDetailedContent:y}:{}})}}else if(T3(p)){let g=I3(p);g.trim()&&(c||(c=ge(g.trim(),80)),u=ge(g.trim(),80)),d.push({role:"user",timestamp:h,content:g})}else if(S3(p)){let g=k3(p);if(g&&(s=g),Array.isArray(m.content))for(let _ of m.content)_.type==="text"&&_.text?d.push({role:"assistant",timestamp:h,content:_.text,model:g}):_.type==="thinking"&&_.thinking?d.push({role:"thinking",timestamp:h,content:_.thinking}):_.functionCall&&d.push(x3(_.functionCall,h,g));else if(typeof m.content=="string")d.push({role:"assistant",timestamp:h,content:m.content,model:g});else if(Array.isArray(m.parts))for(let _ of m.parts)if(_.thought||_.type==="thinking"){let w=_.thinking||_.text;w&&d.push({role:"thinking",timestamp:h,content:w})}else _.functionCall?d.push(x3(_.functionCall,h,g)):_.text&&d.push({role:"assistant",timestamp:h,content:_.text,model:g})}}return{provider:"qwen",sessionId:r,slug:l,cwd:n,createdAt:o.createdAt,modifiedAt:o.modifiedAt,model:s,cliVersion:i,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:u,messageCount:d.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:t,...O0e(f),messages:d}}async resolveSessionPath(t){let r=Ja(this.baseDir,"projects");try{let o=await Pb(r),n=[];for(let s of o){let i=Ja(r,s,"chats",`${t}.jsonl`);try{return await A0e(i,{flag:"r"}),i}catch{continue}}for(let s of o){let i=Ja(r,s,"chats"),a;try{a=await Pb(i)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;E3(l,".jsonl").startsWith(t)&&n.push(Ja(i,l))}}if(n.length===1)return n[0]}catch{}return null}async deleteSession(t){let r=await this.resolveSessionPath(t);if(!r)return!1;try{return await R0e(r),!0}catch{return!1}}}});function bO(e){return new wO(e)}var wO,EO=$(()=>{"use strict";A3();on();Xa();br();wO=class extends mt{constructor(t){super({provider:new Ub(t),protocol:{transport:"stream-json",perTurnCancellation:"process",persistentCancellation:"session",persistentResume:!0},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",De,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:kb})}openSession(t){return xb({...t,binary:"qwen"})}seedArgsFor(t){let r=super.seedArgsFor(t);return t?.model?[...r,"--model",t.model]:r}}});import{readdir as R3,readFile as N3,rm as C3,stat as TO}from"node:fs/promises";import{basename as SO,dirname as O3,join as Go}from"node:path";import{fileURLToPath as D0e}from"node:url";async function P0e(e){let t=await Promise.all(e.map(r=>Zt(r)));return{createdAt:new Date(Math.min(...t.map(r=>r.createdAt.getTime()))),modifiedAt:new Date(Math.max(...t.map(r=>r.modifiedAt.getTime())))}}function U0e(e,t){if(!e)return t;let r=new Date(e);return Number.isNaN(r.getTime())?t:r}function M3(e){return e.type==="USER_INPUT"}function L3(e){return e.source==="MODEL"&&e.type==="PLANNER_RESPONSE"}function j0e(e){return e.source==="MODEL"&&e.type!=="PLANNER_RESPONSE"}function D3(e){if(!e)return"";let t=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(e);return t?t[1]:e}function P3(e){if(!e)return;let t=/Model Selection` from [^\n]+? to ([^\n]+)/.exec(e);if(t)return t[1].replace(/\. No need\b[\s\S]*$/,"").replace(/\. If reporting\b[\s\S]*$/,"").replace(/\.\s*$/,"").trim()}function F0e(e){if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}}async function z0e(e){for await(let t of Ot(e)){let r=t.tool_calls?.map(n=>n.args)??[];for(let n of r){let s=B0e(n);if(s)return s}let o=W0e(t.content);if(o)return o}return null}function B0e(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=t.Cwd??t.cwd??t.DirectoryPath;return typeof r!="string"?null:r.replace(/^"|"$/g,"")}function W0e(e){return e?/"Cwd":"([^"]+)"/.exec(e)?.[1]??null:null}function q0e(e,t){if(e.status!=="RUNNING"||!e.content)return;let r=/task id:\s*([^/\s]+)\/(task-(\d+))\b/.exec(e.content);if(!(!r||r[1]!==t)&&!(e.step_index===void 0||Number(r[3])!==e.step_index))return r[2]}function H0e(e,t){let r=new Set;for(let o of t){let n=V0e(e,r,o);if(!n)continue;r.add(n);let s=o.event.step_index===void 0?void 0:`agy-step-${o.event.step_index}`;n.message.toolCallId=s,n.message.backgroundTaskId=o.message.backgroundTaskId,o.message.toolName=n.name,o.message.toolCallId=s}}function V0e(e,t,r){let o=r.message.backgroundTaskId===void 0?void 0:K0e(r.event.content);if(o!==void 0)return U3(e.filter(s=>!t.has(s)&&Z0e(s)===o),r.event.step_index);let n=J0e(r.event);if(n!==void 0)return U3(e.filter(s=>!t.has(s)&&G0e(s.name,r.event.type)&&j3(X0e(s))===n),r.event.step_index)}function U3(e,t){if(e.length===0)return;if(e.length===1)return e[0];if(t===void 0)return;let r=e.map(o=>({call:o,distance:o.stepIndex===void 0?Number.POSITIVE_INFINITY:Math.abs(t-o.stepIndex)})).sort((o,n)=>o.distance-n.distance);return r[0].distance<r[1].distance?r[0].call:void 0}function G0e(e,t){return t==="VIEW_FILE"?e==="view_file":t!=="CODE_ACTION"?!1:e==="write_to_file"||e==="replace_file_content"||e==="multi_replace_file_content"}function X0e(e){let t=e.name==="view_file"?e.input?.AbsolutePath:e.input?.TargetFile;return typeof t=="string"?t:void 0}function J0e(e){if(!e.content)return;let t;return e.type==="VIEW_FILE"?t=/File Path:\s*`?([^`\n]+)`?/.exec(e.content)?.[1]:e.type==="CODE_ACTION"&&(t=/Created file\s+(.+?)\s+with requested content/.exec(e.content)?.[1]??/changes were made by .*? tool to:\s*(.+?)\.\s*(?:If relevant|$)/s.exec(e.content)?.[1]),j3(t)}function j3(e){if(!e)return;let t=e.trim().replace(/^`|`$/g,"");if(!t.startsWith("file://"))return t;try{return D0e(t)}catch{return}}function K0e(e){if(e)return/Task Description:\s*([^\n]+)/.exec(e)?.[1]?.trim()}function Z0e(e){if(e.name==="run_command"){let t=e.input?.CommandLine;return typeof t=="string"?t:void 0}if(e.name==="schedule"){let t=e.input?.DurationSeconds,r=e.input?.Prompt;return typeof t!="string"&&typeof t!="number"||typeof r!="string"?void 0:`Timer: ${t}s, Prompt: ${r}`}}function IO(e){if(e.endsWith(".db"))return SO(e,".db");let t="/brain/",r=e.indexOf(t);return r===-1?null:e.slice(r+t.length).split("/")[0]||null}async function Fb(e){if(e.endsWith(".jsonl"))return e;let t=IO(e);if(!t||!e.endsWith(".db"))return null;let r=O3(O3(e));for(let o of["transcript_full.jsonl","transcript.jsonl"]){let n=Go(r,"brain",t,".system_generated","logs",o);try{return await TO(n),n}catch{}}return null}var jb,kO=$(()=>{"use strict";Yt();jb=class{name="agy";baseDir;constructor(t={}){this.baseDir=t.agyDir||Go(He,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:Go(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let t=Go(this.baseDir,"conversations"),r;try{r=await R3(t)}catch{return[]}let o=[];for(let n of r){if(!n.endsWith(".db"))continue;let s=SO(n,".db");try{let i=await this.extractSummary(s);i&&o.push(i)}catch{}}return o}conversationPath(t){return Go(this.baseDir,"conversations",`${t}.db`)}transcriptPath(t,r){return Go(this.baseDir,"brain",t,".system_generated","logs",r?"transcript_full.jsonl":"transcript.jsonl")}async existingTranscriptPath(t){for(let r of[this.transcriptPath(t,!0),this.transcriptPath(t,!1)])try{return await TO(r),r}catch{}return null}async extractSummary(t){let r=this.conversationPath(t),o=await this.existingTranscriptPath(t),n=o??r,s=await P0e([r,o].filter(Boolean)),i=await this.resolveCwd(t,o),a,l,c,u=0;if(o)for await(let d of Ot(o)){let f=P3(d.content);if(f&&(a=f),M3(d)){let p=D3(d.content).trim();p&&(l||(l=ge(p,80)),c=ge(p,80)),u++}else L3(d)&&d.content&&u++}return{provider:"agy",sessionId:t,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:n,filePaths:o?[r,o]:[r]}}async loadSession(t){let r=await this.resolveSessionPath(t);if(!r)return null;let o=IO(r);if(!o)return null;let n=await this.extractSummary(o);if(!n)return null;let s=await this.existingTranscriptPath(o),i=[],a=n.model,l=n.firstUserMessage,c=n.lastUserMessage,u=[],d=[];if(s)for await(let f of Ot(s)){let p=U0e(f.created_at,n.modifiedAt),m=P3(f.content);if(m&&(a=m),M3(f)){let h=D3(f.content),g=h.trim();g&&(l||(l=ge(g,80)),c=ge(g,80)),i.push({role:"user",timestamp:p,content:h});continue}if(Array.isArray(f.tool_calls))for(let h of f.tool_calls){let g=h.name||"tool",_=F0e(h.args),w=ro(h.args),y={role:"tool_use",timestamp:p,content:_,toolName:g,toolInput:_,toolInputData:w};i.push(y),u.push({name:g,stepIndex:f.step_index,input:w,message:y})}if(L3(f)&&f.content)i.push({role:"assistant",timestamp:p,content:f.content,model:a});else if(j0e(f)&&f.content){let h=q0e(f,o),g=h===void 0?null:await this.readTaskLog(o,h),_={role:"tool_result",timestamp:g?.modifiedAt??p,content:f.content,toolName:f.type?.toLowerCase(),backgroundTaskId:h,...g===null?{}:{toolDetailedContent:g.content}};i.push(_),d.push({event:f,message:_})}f.thinking&&i.push({role:"thinking",timestamp:p,content:f.thinking})}return H0e(u,d),{...n,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:i.filter(f=>f.role==="user"||f.role==="assistant").length,messages:i}}async resolveSessionPath(t){let r=this.conversationPath(t);try{return await TO(r),r}catch{}let o=Go(this.baseDir,"conversations");try{let n=[];for(let s of await R3(o)){if(!s.endsWith(".db"))continue;SO(s,".db").startsWith(t)&&n.push(Go(o,s))}if(n.length===1)return n[0]}catch{}return null}async resolveTailTranscriptPath(t){let r=await this.resolveSessionPath(t);return r?Fb(r):null}async deleteSession(t){let r=await this.resolveSessionPath(t);if(!r)return!1;let o=IO(r);return o?(await C3(this.conversationPath(o),{force:!0}),await C3(Go(this.baseDir,"brain",o),{recursive:!0,force:!0}),!0):!1}async resolveCwd(t,r){let o=await this.cwdFromLastConversationCache(t);if(o)return o;if(r){let n=await z0e(r);if(n)return n}return"(unknown)"}async cwdFromLastConversationCache(t){let r=Go(this.baseDir,"cache","last_conversations.json");try{let o=JSON.parse(await N3(r,"utf8"));for(let[n,s]of Object.entries(o))if(s===t)return n}catch{}return null}async readTaskLog(t,r){if(!/^task-\d+$/.test(r))return null;let o=Go(this.baseDir,"brain",t,".system_generated","tasks",`${r}.log`);try{let[n,s]=await Promise.all([N3(o,"utf8"),Zt(o)]);return{content:n,modifiedAt:s.modifiedAt}}catch{return null}}}});import{spawn as Y0e}from"node:child_process";import{StringDecoder as F3}from"node:string_decoder";function zb(e){return async(t,r)=>{let o=Date.now(),n=e.buildArgs(t,r);e.assertArgs?.(n,r),r.onProgress?.({kind:"system",summary:`${e.label} -p one-shot started (no streaming events)`});let{stdout:s}=await Q0e(e.label,r.binary,n,{cwd:r.cwd,env:ar(r.env,r.cwd,r.sessionId),signal:r.signal});return r.onProgress?.({kind:"system",summary:`${e.label} -p one-shot completed`}),{text:s.trimEnd(),sessionId:r.sessionId,durationMs:Date.now()-o}}}function Q0e(e,t,r,o){return new Promise((n,s)=>{if(o.signal?.aborted){s(new Error(`${e} turn aborted`));return}let i;try{i=Y0e(t,r,{cwd:o.cwd,env:o.env,stdio:["ignore","pipe","pipe"]})}catch(f){s(f);return}let a="",l="",c=new F3("utf8"),u=new F3("utf8");i.stdout?.on("data",f=>{a+=c.write(f)}),i.stderr?.on("data",f=>{l+=u.write(f)});let d=()=>{i.kill("SIGTERM"),s(new Error(`${e} turn aborted`))};i.on("error",f=>{o.signal?.removeEventListener("abort",d),s(f)}),i.on("close",(f,p)=>{if(o.signal?.removeEventListener("abort",d),a+=c.end(),l+=u.end(),f===0){n({stdout:a,stderr:l});return}let m=p?`signal ${p}`:`exit code ${f}`,h=l.trim()||a.trim();s(new Error(_u(`${e} failed (${m})`,h?Ht(h,{provider:e}):"")))}),o.signal?.aborted?d():o.signal?.addEventListener("abort",d,{once:!0})})}var xO=$(()=>{"use strict";Do();Wn()});import{basename as eAe}from"node:path";import{randomUUID as tAe}from"node:crypto";function AO(e){return new $O(e)}function nAe(e){return e!==void 0&&e<=0||e===void 0?"0":`${Math.max(1,Math.ceil(e/1e3))}s`}var $O,rAe,RO=$(()=>{"use strict";kO();on();br();hs();xO();$O=class extends mt{constructor(t){super({provider:new jb(t),protocol:{transport:"print",perTurnCancellation:"process"},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",De,"--dangerously-skip-permissions","--print-timeout","0"],resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:rAe})}async sendTurn(t,r){if(r.requireResume){let n=await this.resolvePath(r.sessionId);if(n===null||eAe(n)!==`${r.sessionId}.db`)throw new Error(`agy cannot resume missing conversation "${r.sessionId}"`)}let o=await super.sendTurn(t,r);return r.permissionMode==="plan"?{...o,warnings:[...o.warnings??[],"agy does not enforce plan mode; this turn used full permissions"]}:o}seedArgsFor(t){let r=[...super.seedArgsFor(t)];return t?.model&&r.push("--model",t.model),r}async seed(t,r){let o=tAe(),n=`[lmctl-seed:${o}]`,s=await super.seed(t,{...r,prompt:oy({flightToken:o,prompt:r?.prompt})});if(!s.success&&(s.errorCode==="ENOENT"||s.errorCode==="ABORT_ERR"))return s;let i=(await this.provider.discoverSessions()).filter(a=>a.firstUserMessage?.startsWith(n));if(s.success&&i.length===1)return{...s,sessionId:i[0].sessionId};for(let a of i)await this.provider.deleteSession(a.sessionId);return{...s,success:!1,error:s.error??`agy seed created ${i.length} identifiable sessions; expected one`}}manualSeedHint(t){return{launchCommand:`cd ${t} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${t}`}}},rAe=zb({label:"agy",buildArgs:(e,t)=>{let r=[...t.sessionId?["--conversation",t.sessionId]:[],"-p",e,"--dangerously-skip-permissions","--print-timeout",nAe(t.timeoutMs)];return t.model&&r.push("--model",t.model),r},assertArgs:(e,t)=>dr("agy",e,t.permissionMode??"yolo")})});import{existsSync as Eh,readdirSync as oAe,statSync as z3}from"node:fs";import{readdir as NO,rm as sAe}from"node:fs/promises";import B3,{join as xs}from"node:path";function iAe(e){if(e.length===0)throw new Error("cannot encode an empty project path");let t="",r=!1;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n),i=String.fromCharCode(s);i==="/"||i==="\\"||i===":"?(r||(t+="-"),r=!0):i!=="~"&&/^[A-Za-z0-9._-]$/.test(i)?(t+=i,r=!1):(t+="~"+s.toString(16).toUpperCase().padStart(4,"0"),r=!1)}return`--${(t.replace(/^-+/,"")||"root").slice(0,251)}--`}function aAe(e){return"--"+e.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function jd(e,t){let r=t??(process.platform==="win32"?B3.win32:B3.posix),o=e,n="session.jsonl.zstd";if((e.endsWith(".jsonl.zstd")||e.endsWith(".jsonl"))&&(o=r.dirname(e),n=r.basename(e)),!Eh(o))return e.endsWith(".jsonl.zstd")||e.endsWith(".jsonl")?e:r.join(e,n);try{let s=oAe(o),i=[];for(let a of s){let l=/^session(?:\.v(\d+))?\.jsonl\.zstd$/.exec(a);if(l){let c=l[1]?parseInt(l[1],10):0;if(Number.isSafeInteger(c))try{let u=r.join(o,a);z3(u).isFile()&&i.push({name:a,version:c})}catch{}}}if(i.length>0)return i.sort((a,l)=>l.version-a.version),r.join(o,i[0].name)}catch{}try{if(Eh(e)&&z3(e).isFile())return e}catch{}return r.join(o,n)}function CO(e){if(typeof e=="string")return e;if(!Array.isArray(e))return"";let t=[];for(let r of e)r&&typeof r=="object"&&r.type==="text"&&typeof r.text=="string"&&t.push(r.text);return t.join("")}function lAe(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)r&&typeof r=="object"&&r.type==="reasoning"&&typeof r.text=="string"&&t.push(r.text);return t}function W3(e){let t=[];for(let r of e){let o=r.data??{},n=r.time?new Date(r.time):new Date(0);if(r.type==="user/message"){let s=o;if(s.source?.kind!==void 0&&s.source.kind!=="user")continue;t.push({role:"user",timestamp:n,content:CO(s.content)})}else if(r.type==="assistant/message"){let s=o.message;for(let i of lAe(s?.content))t.push({role:"thinking",timestamp:n,content:i});t.push({role:"assistant",timestamp:n,content:CO(s?.content),model:s?.source?.model})}else if(r.type==="tool/call"){let s=o,i;if(typeof s.arguments=="string")try{i=JSON.parse(s.arguments)}catch{}else s.arguments&&typeof s.arguments=="object"&&(i=s.arguments);t.push({role:"tool_use",timestamp:n,content:typeof s.arguments=="string"?s.arguments:JSON.stringify(s.arguments??{}),toolName:s.name,toolCallId:s.callId,toolInputData:i})}else if(r.type==="tool/result"){let s=o,a=(Array.isArray(s.message?.content)?s.message.content:[])[0];t.push({role:"tool_result",timestamp:n,content:CO(a?.content??s.message?.content),toolCallId:a?.toolCallId??s.message?.source?.callId})}}return t}function cAe(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.type==="turn/end")return r.data?.reason?.kind==="completed"?"complete":"aborted";if(r.type==="turn/start")return"in_progress"}}function q3(e,t,r){let o=e.find(p=>p.type==="session");if(!o)return null;let n=o,s=o.data,i=n.id??s?.id;if(!i)return null;let a;for(let p of e)if(p.type==="request/header"){let m=p.data?.header;m?.config?.model&&(a=m.config.model)}let l=e.map(p=>p.time).filter(p=>typeof p=="number"),c=n.createdAt??s?.createdAt,u=c?new Date(c):new Date(0),d=l.length>0?new Date(Math.max(...l)):u,f=r.filter(p=>p.role==="user");return{provider:"dsh",sessionId:i,cwd:n.cwd??s?.cwd??"",createdAt:u,modifiedAt:d,model:a,firstUserMessage:f[0]?.content,lastUserMessage:f.at(-1)?.content,messageCount:r.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:t,...uAe(e)}}function uAe(e){let t=new Map;for(let i of e){let a=i.data?.turn??null,l=t.get(a)??[];l.push(i),t.set(a,l)}let r=[],o=[];for(let i of t.values()){let a=new Cu("",-1,new Set);a.update(i);let l=a.usage();l&&(r.push(l),o.push(a.lastUsage()))}if(!r.length)return{};let n=i=>{if(r.some(l=>l.invalidCounters||l[i]===null))return;let a=r.reduce((l,c)=>l+c[i],0);return Number.isSafeInteger(a)?a:void 0},s=o.at(-1);return{totalInputTokens:n("inputUncached"),totalCachedInputTokens:n("cacheRead"),totalOutputTokens:n("output"),totalReasoningOutputTokens:n("reasoning"),lastInputTokens:s.inputUncached!==null&&s.cacheRead!==null?s.inputUncached+s.cacheRead:void 0,lastTokenUsage:{totalTokens:s.inputUncached!==null&&s.cacheRead!==null&&s.output!==null?s.inputUncached+s.cacheRead+s.output:void 0,inputTokens:s.inputUncached??void 0,cachedInputTokens:s.cacheRead??void 0,outputTokens:s.output??void 0,reasoningOutputTokens:s.reasoning??void 0}}}var Bb,H3=$(()=>{"use strict";ay();Yt();Xg();Bb=class{name="dsh";sessionsDir;constructor(t={}){let r=t.dshHome||process.env.DSH_HOME||xs(He,".dsh");this.sessionsDir=xs(r,"sessions")}async discoverSessions(){let t=[],r;try{r=await NO(this.sessionsDir)}catch{return[]}for(let o of r){let n;try{n=await NO(xs(this.sessionsDir,o))}catch{continue}for(let s of n)if(s.startsWith("session-"))try{let i=await this.readSummary(o,s);i&&t.push(i)}catch{}}return t}async loadSession(t){let r=await this.findSessionDir(t);if(!r)return null;let o=await this.readRecords(r.cwdDir,r.sessionDir);if(o.length===0)return null;let n=W3(o),s=q3(o,r.filePath,n);return s?{...s,turnStatus:cAe(o),messages:n}:null}async resolveSessionPath(t){return(await this.findSessionDir(t))?.filePath??null}async deleteSession(t){let r=await this.findSessionDir(t);return r?(await sAe(xs(this.sessionsDir,r.cwdDir,r.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(t,r){let o=iAe(t),n=aAe(t),s=o,i=xs(this.sessionsDir,o,r),a=xs(this.sessionsDir,n,r);!Eh(i)&&Eh(a)&&(s=n);let l=xs(this.sessionsDir,s,r);return jd(l)}async findSessionDir(t){let r;try{r=await NO(this.sessionsDir)}catch{return null}for(let o of r){let n=t,s=xs(this.sessionsDir,o,n);try{let i=jd(s);if(Eh(i))return{cwdDir:o,sessionDir:n,filePath:i}}catch{}}return null}async readRecords(t,r){let{readFile:o}=await import("node:fs/promises"),n=xs(this.sessionsDir,t,r),s=jd(n),i=await o(s),a=Gg(i),l=[];for(let c of a.split(`
|
|
2158
2158
|
`))if(c.trim())try{let u=JSON.parse(c);if(u.type?.endsWith("-chunks")||u.type==="assistant/chunk"&&u.data?.chunk?.type!=="usage")continue;l.push(u)}catch{}return l}async readSummary(t,r){let o=xs(this.sessionsDir,t,r),n=jd(o),s=await this.readRecords(t,r);return s.length===0?null:q3(s,n,W3(s))}}});import{spawn as dAe}from"node:child_process";import{randomUUID as fAe}from"node:crypto";function OO(e,t=[]){if(e==null)return e;if(typeof e=="string"){let r=e;for(let o of t)o&&typeof o=="string"&&o.length>=8&&r.includes(o)&&(r=r.replaceAll(o,"[REDACTED]"));return r=r.replace(/(?:sk-|dsh-)[A-Za-z0-9_\-\.]+/gi,"[REDACTED]"),r=r.replace(/(?:token=)[A-Za-z0-9_\-\.]+/gi,"token=[REDACTED]"),r=r.replace(/bearer\s+[A-Za-z0-9_\-\.]+/gi,"Bearer [REDACTED]"),r}if(Array.isArray(e))return e.map(r=>OO(r,t));if(typeof e=="object"){let r={};for(let[o,n]of Object.entries(e))/api[_-]?key|secret|token|password|auth|authorization|credential|cookie/i.test(o)?r[o]="[REDACTED]":r[o]=OO(n,t);return r}return e}function mAe(e){let t;try{t=new URL(e)}catch{throw new Error("invalid dsh boot URL: malformed URL")}if(t.protocol!=="http:")throw new Error(`invalid dsh boot URL scheme "${t.protocol}": must be http:`);if(t.username||t.password)throw new Error("invalid dsh boot URL: userinfo credentials are not allowed");let r=t.hostname;if(!(r==="127.0.0.1"||r==="localhost"||r==="::1"||r==="[::1]"))throw new Error(`invalid dsh boot URL host "${r}": loopback host (127.0.0.1 or localhost) required`);return t}function V3(e,t=2e3){if(!e||e.exitCode!==null||e.signalCode!==null)return;try{e.kill("SIGTERM")}catch{}let r,o=()=>{r!==void 0&&(clearTimeout(r),r=void 0)};if(e.once("exit",o),e.exitCode!==null||e.signalCode!==null){o();return}r=setTimeout(()=>{r=void 0;try{e.exitCode===null&&e.signalCode===null&&e.kill("SIGKILL")}catch{}},t),r.unref()}async function Wb(e,t=r=>MO.spawn(r)){if(Ka){let r=await Ka.catch(()=>{});if(r?.alive)return r;Ka=void 0}return Ka=t(e),Ka}async function Fd(){if(!Ka)return;(await Ka.catch(()=>{}))?.shutdown(),Ka=void 0}var pAe,Ti,MO,Ka,G3=$(()=>{"use strict";Wn();pAe=/dsh web:\s*(https?:\/\/\S+)/;Ti=class e extends Error{method;detail;constructor(t,r,o=[]){let n=OO(r,o),s=typeof n=="string"?n:JSON.stringify(n);super(`dsh RPC ${t} failed: ${s}`),this.name="DshRpcCallError",this.method=t,this.detail=n,Object.setPrototypeOf(this,e.prototype)}};MO=class e{baseUrl;child;cookie;isV2;tokenUrl;static MAX_RETAINED_SECRETS=8;cookieExchangePromise;knownSecrets=[];constructor(t,r,o,n=!1,s){if(this.baseUrl=t,this.child=r,this.cookie=o,this.isV2=n,this.tokenUrl=s,this.cookie&&this.recordSecret(this.cookie),this.tokenUrl){this.recordSecret(this.tokenUrl);try{let a=new URL(this.tokenUrl).searchParams.get("token");a&&this.recordSecret(a)}catch{}}}recordSecret(t){if(!t||typeof t!="string"||t.length<8)return;let r=o=>{if(o.length<8)return;let n=this.knownSecrets.indexOf(o);for(n!==-1&&this.knownSecrets.splice(n,1),this.knownSecrets.push(o);this.knownSecrets.length>e.MAX_RETAINED_SECRETS;)this.knownSecrets.shift()};if(r(t),t.includes("=")){let o=t.split("=")[1];o&&o.length>=8&&r(o)}}getSecretsToRedact(t=[]){let r=new Set;for(let o of this.knownSecrets)o&&o.length>=8&&r.add(o);if(this.cookie&&this.cookie.length>=8){r.add(this.cookie);let o=this.cookie.split("=")[1];o&&o.length>=8&&r.add(o)}if(this.tokenUrl)try{let n=new URL(this.tokenUrl).searchParams.get("token");n&&n.length>=8&&r.add(n)}catch{}for(let o of t)if(o&&o.length>=8&&(r.add(o),o.includes("="))){let n=o.split("=")[1];n&&n.length>=8&&r.add(n)}return Array.from(r)}static forTesting(t,r){let o=t,n=r?.isV2??!1,s=r?.cookie;try{let i=new URL(t);i.searchParams.has("token")&&(n=!0,o=i.origin)}catch{}return new e(o,void 0,s,n,t)}static async fromBootUrl(t,r,o){let n=mAe(t),s=n.searchParams.has("token"),i;if(s)for(let a=0;a<5;a++){if(o?.aborted)throw new Error("dsh web boot aborted");try{let c=(await fetch(t,{redirect:"manual",signal:o})).headers.get("set-cookie");if(c){i=c.split(";")[0];break}}catch(l){if(o?.aborted)throw l;await new Promise(c=>setTimeout(c,100))}}return new e(n.origin,r,i,s,t)}async ensureCookie(t=!1){return this.tokenUrl?this.cookie&&!t?this.cookie:(this.cookieExchangePromise||(this.cookieExchangePromise=(async()=>{for(let r=0;r<5;r++)try{let n=(await fetch(this.tokenUrl,{redirect:"manual"})).headers.get("set-cookie");if(n)return this.cookie=n.split(";")[0],this.recordSecret(this.cookie),this.cookie}catch{await new Promise(o=>setTimeout(o,100))}return this.cookie})().finally(()=>{this.cookieExchangePromise=void 0})),this.cookieExchangePromise):this.cookie}async rpc(t,r){this.isV2&&await this.ensureCookie();let o=this.cookie,n=o?[o]:[],s=`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,i=this.isV2?t.includes("/")?t:t.replace(/\./g,"/"):t.includes(".")?t:t.replace(/\//g,"."),a=r;if(this.isV2){let f=r;if(i==="session/prompt"&&f&&typeof f=="object"){let p=f;p.requestId||(f={...p,requestId:fAe()})}f&&typeof f=="object"&&"args"in f?a=f:a={args:{request:f}}}let l={"content-type":"application/json"};this.cookie&&(l.cookie=this.cookie);let c;try{c=await fetch(`${this.baseUrl}/api/${i}`,{method:"POST",headers:l,body:JSON.stringify({type:"client-request",rpcId:s,method:i,payload:a}),redirect:"manual"})}catch(f){throw new Ti(t,`transport error: ${f instanceof Error?f.message:String(f)}`,this.getSecretsToRedact(n))}if(c.status>=300&&c.status<400)throw new Ti(t,`redirects are not permitted (HTTP ${c.status})`,this.getSecretsToRedact(n));if((c.status===401||c.status===403)&&this.isV2&&this.tokenUrl){let f=await this.ensureCookie(!0);if(f&&f!==l.cookie){l.cookie=f,n.push(f);try{c=await fetch(`${this.baseUrl}/api/${i}`,{method:"POST",headers:l,body:JSON.stringify({type:"client-request",rpcId:s,method:i,payload:a}),redirect:"manual"})}catch(p){throw new Ti(t,`transport error: ${p instanceof Error?p.message:String(p)}`,this.getSecretsToRedact(n))}if(c.status>=300&&c.status<400)throw new Ti(t,`redirects are not permitted (HTTP ${c.status})`,this.getSecretsToRedact(n))}}let u;try{u=await c.json()}catch{u=void 0}if(!c.ok)throw new Ti(t,u??c.statusText,this.getSecretsToRedact(n));let d=u&&typeof u=="object"?u.result:void 0;if(!d||typeof d!="object"||typeof d.ok!="boolean")throw new Ti(t,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope",this.getSecretsToRedact(n));if(d.ok===!1)throw new Ti(t,d.error??d,this.getSecretsToRedact(n));return"value"in d?d.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&&V3(this.child,2e3)}static spawn(t){return new Promise((r,o)=>{let n=dAe("dsh",["web","--no-open","--port","0"],{env:t,stdio:["ignore","pipe","pipe"]}),s=!1,i=!1,a="",l="",c="",u=new AbortController,d=f=>{s||(s=!0,u.abort(),V3(n,2e3),o(f))};n.stdout?.on("data",f=>{let p=f.toString();if(l+=p,a+=p,s||i)return;let m=a.split(`
|
|
2159
2159
|
`);a=m.pop()??"";for(let h of m){let g=pAe.exec(h);if(g){i=!0,e.fromBootUrl(g[1],n,u.signal).then(_=>{s||(s=!0,r(_))},_=>{d(_ instanceof Error?_:new Error(String(_)))});return}}}),n.stderr?.on("data",f=>{c+=f.toString()}),n.on("error",f=>{d(f)}),n.on("exit",(f,p)=>{let m=p?`signal ${p}`:`exit code ${f}`;d(new Error(_u(`dsh web exited before reporting a boot URL (${m})`,c.trim()?Ht(c,{provider:"dsh"}):"")))})})}}});import{randomUUID as LO}from"node:crypto";import{existsSync as X3,statSync as hAe}from"node:fs";import{readFile as gAe,mkdir as _Ae}from"node:fs/promises";function FO(e){return new jO(e)}function UO(e){return{...e,DSH_PERMISSION_MODE:e.DSH_PERMISSION_MODE??"danger-full-access"}}function vAe(e){let t=e?.kind??"unknown",r=e?.error?.message;return r?`dsh turn ended with reason=${t}: ${r}`:`dsh turn ended with reason=${t} and no assistant text`}function Th(e){return e instanceof Error?e.message:String(e)}async function J3(e,t){let r;try{r=await gAe(e)}catch{return t?.(),[]}t&&Ff(r).reduce((s,i)=>s+i.length,0)!==r.length&&t?.();let o=Gg(r),n=[];for(let s of o.split(`
|
|
2160
|
-
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{t?.()}return n}function wAe(e){let r=e.data?.message?.content;if(typeof r=="string")return r;if(!Array.isArray(r))return"";let o=[];for(let n of r)n&&typeof n=="object"&&n.type==="text"&&typeof n.text=="string"&&o.push(n.text);return o.join("")}function qb(e,t){return jd(e,t)}var DO,yAe,PO,jO,zO=$(()=>{"use strict";ay();Au();on();H3();Xg();G3();br();hs();DO=new Map,yAe=500,PO=0;jO=class extends mt{dshProvider;usageSeen=new Set;constructor(t){let r=new Bb(t);super({provider:r,protocol:{transport:"dsh-rpc",perTurnCancellation:"unsupported",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"dsh has no in-session leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"dsh",seedArgs:[],resumeTemplate:"dsh web --no-open --port 0 # continuity is via the RPC sidecar, not a resume flag",startTemplate:"dsh web --no-open --port 0",transport:(o,n)=>this.dshPromptTurn(o,n)}),this.dshProvider=r}manualSeedHint(t){return{launchCommand:`cd ${t} && dsh web`,postLaunchNote:"dsh has no interactive terminal session to seed into \u2014 continuity lives in the web profile's session store, not a TTY. Boot the sidecar with the command above, open the printed http:// URL, and start a session rooted at this directory in the web UI; lmctl's managed sidecar can then cold-resume it by id (cross-profile session sharing is verified). Send lmctl's seed instruction there, wait for the reply, then find the new session id with the ls command below and register it manually.",lsCommand:`lmctl ls --provider dsh --sessiondir ${t}`}}async seed(t,r){await _Ae(t,{recursive:!0});let o=`session-${LO()}`,n=UO(r?.env??process.env);dr("dsh",[],"yolo");try{let s;try{s=await Wb(n)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${Th(a)}`}}try{await s.rpc("session.create",{sessionId:o,cwd:t})}catch(a){return{success:!1,error:`session.create failed: ${Th(a)}`}}if(r?.model)try{await s.rpc("session.selectModel",{sessionId:o,provider:"deepseek-official",model:r.model})}catch(a){return{success:!1,error:`session.selectModel("${r.model}") failed: ${Th(a)}`}}let i=r?.prompt??De;try{r?.signal?.throwIfAborted();try{r?.onDispatch?.()}catch{}let a=await this.promptAndWait(s,t,o,i,PO,r?.signal);return{success:!0,sessionId:o,usage:a.usage}}catch(a){return{success:!1,sessionId:o,usage:a?.usage,error:`seed turn failed: ${Th(a)}`}}}finally{await Fd()}}async dshPromptTurn(t,r){let o=Date.now();if(r.bundleSession!==void 0)return ri(r.bundleSession,"dsh",r.sessionId,t,{onDelta:r.onDelta,onProgress:r.onProgress,signal:r.signal});let n=UO(r.env??process.env);dr("dsh",[],r.permissionMode??"yolo");let s=!r.sessionId,i=s?`session-${LO()}`:r.sessionId,a;try{let l=await Wb(n);s&&await l.rpc("session.create",{sessionId:i,cwd:r.cwd}),r.model&&(await l.rpc("session.selectModel",{sessionId:i,provider:"deepseek-official",model:r.model}),r.onProgress?.({kind:"system",summary:`dsh model set to ${r.model}`})),r.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),a=await this.promptAndWait(l,r.cwd,i,t,r.timeoutMs??PO,r.signal)}finally{await Fd()}return r.onProgress?.({kind:"system",summary:"dsh turn completed"}),{...a,sessionId:i,durationMs:Date.now()-o}}async openSession(t){let r=UO(t.env??process.env);dr("dsh",[],t.permissionMode??"yolo");let o=await Wb(r),n=!t.sessionId,s=n?`session-${LO()}`:t.sessionId;if(n)try{await o.rpc("session.create",{sessionId:s,cwd:t.cwd})}catch(g){throw await Fd(),new Error(`dsh bundle: session.create failed: ${Th(g)}`)}let i=qb(this.dshProvider.sessionFilePath(t.cwd,s)),a=!1;try{a=X3(i)&&hAe(i).isFile()}catch{a=!1}let l=a;if(!a&&!n)throw await Fd(),new Error(`dsh bundle: session file does not exist for session "${s}" (${i}) \u2014 the session must exist before a bundle can resume it`);t.model&&await o.rpc("session.selectModel",{sessionId:s,provider:"deepseek-official",model:t.model});let c=this,u=0,d=!1,f=null,p=!1,m=!1,h=async()=>{m||(m=!0,await Fd())};return{provider:"dsh",sessionId:s,get completedTurns(){return u},async sendTurn(g,_={}){if(d||f!==null)throw new Error("dsh bundle session is closed");if(p)throw new Error("dsh bundle session has a turn still in flight");if(_.signal?.aborted)throw new Error("Aborted");if(i=qb(i),l&&!X3(i))throw new Error(`dsh bundle: session file for session "${s}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);p=!0;let w=Date.now();try{let y,b=c.promptAndWait(o,t.cwd,s,g,PO,_.signal,I=>{y=I});b.catch(()=>{});let E=()=>{},T=new Promise((I,R)=>{E=()=>{(async()=>{d=!0,await h()})().finally(()=>R(Object.assign(new Error("Aborted"),{usage:y,sessionId:s})))},_.signal?.addEventListener("abort",E,{once:!0})}),k;try{k=await Promise.race([b,T])}finally{_.signal?.removeEventListener("abort",E)}return u+=1,l=!0,{...k,sessionId:s,durationMs:Date.now()-w}}finally{p=!1}},close(){return f!==null||(f=(async()=>{d=!0,await h()})()),f}}}async promptAndWait(t,r,o,n,s,i,a){let l=Date.now(),c=qb(this.dshProvider.sessionFilePath(r,o)),u=!1,d=await J3(c,()=>{u=!0}),f=d.reduce((w,y)=>typeof y.seq=="number"&&Number.isSafeInteger(y.seq)?Math.max(w,y.seq):w,-1),p=new Cu(o,f,this.usageSeen);u&&p.invalidateOwnership();let m=JSON.stringify([c,o]),h=DO.get(m)??new Set;if(h.size){p.invalidateOwnership();for(let w of h)w.invalidateOwnership()}h.add(p),DO.set(m,h),d.filter(w=>w.type==="turn/start"||w.type==="turn/end").at(-1)?.type==="turn/start"&&p.invalidateOwnership();let _;try{await t.rpc("session.prompt",{sessionId:o,mode:"queue",content:[{type:"text",text:n}]});let w=s>0?Date.now()+s:1/0;for(;;){c=qb(c);let y=await J3(c),b=y.find(E=>E.type==="turn/end"&&(E.seq??-1)>f);if(y.length&&p.update(y,b?.seq??1/0),a?.(p.usage()),i?.aborted)throw new Error("Aborted");if(b){let E=b.data?.reason;E?.kind!=="completed"&&(_=E?.kind==="aborted"?"cancelled":"error");let T=[...y].reverse().find(R=>R.type==="assistant/message"&&(R.seq??-1)>f&&(R.seq??1/0)<=(b.seq??1/0)),k=T?wAe(T):"";if(E?.kind!=="completed"&&!k)throw new Error(vAe(E));p.finish();let I=p.usage();return{text:k,sessionId:o,durationMs:Date.now()-l,usage:I?{...I,...E?.kind==="completed"?{}:{outcome:E?.kind==="aborted"?"cancelled":"error"}}:void 0}}if(Date.now()>w)throw new Error(`dsh turn timed out after ${s}ms waiting for turn/end`);await new Promise(E=>
|
|
2160
|
+
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{t?.()}return n}function wAe(e){let r=e.data?.message?.content;if(typeof r=="string")return r;if(!Array.isArray(r))return"";let o=[];for(let n of r)n&&typeof n=="object"&&n.type==="text"&&typeof n.text=="string"&&o.push(n.text);return o.join("")}function qb(e,t){return jd(e,t)}var DO,yAe,PO,jO,zO=$(()=>{"use strict";ay();Au();on();H3();Xg();G3();br();hs();DO=new Map,yAe=500,PO=0;jO=class extends mt{dshProvider;usageSeen=new Set;constructor(t){let r=new Bb(t);super({provider:r,protocol:{transport:"dsh-rpc",perTurnCancellation:"unsupported",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"dsh has no in-session leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"dsh",seedArgs:[],resumeTemplate:"dsh web --no-open --port 0 # continuity is via the RPC sidecar, not a resume flag",startTemplate:"dsh web --no-open --port 0",transport:(o,n)=>this.dshPromptTurn(o,n)}),this.dshProvider=r}manualSeedHint(t){return{launchCommand:`cd ${t} && dsh web`,postLaunchNote:"dsh has no interactive terminal session to seed into \u2014 continuity lives in the web profile's session store, not a TTY. Boot the sidecar with the command above, open the printed http:// URL, and start a session rooted at this directory in the web UI; lmctl's managed sidecar can then cold-resume it by id (cross-profile session sharing is verified). Send lmctl's seed instruction there, wait for the reply, then find the new session id with the ls command below and register it manually.",lsCommand:`lmctl ls --provider dsh --sessiondir ${t}`}}async seed(t,r){await _Ae(t,{recursive:!0});let o=`session-${LO()}`,n=UO(r?.env??process.env);dr("dsh",[],"yolo");try{let s;try{s=await Wb(n)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${Th(a)}`}}try{await s.rpc("session.create",{sessionId:o,cwd:t})}catch(a){return{success:!1,error:`session.create failed: ${Th(a)}`}}if(r?.model)try{await s.rpc("session.selectModel",{sessionId:o,provider:"deepseek-official",model:r.model})}catch(a){return{success:!1,error:`session.selectModel("${r.model}") failed: ${Th(a)}`}}let i=r?.prompt??De;try{r?.signal?.throwIfAborted();try{r?.onDispatch?.()}catch{}let a=await this.promptAndWait(s,t,o,i,PO,r?.signal);return{success:!0,sessionId:o,usage:a.usage}}catch(a){return{success:!1,sessionId:o,usage:a?.usage,error:`seed turn failed: ${Th(a)}`}}}finally{await Fd()}}async dshPromptTurn(t,r){let o=Date.now();if(r.bundleSession!==void 0)return ri(r.bundleSession,"dsh",r.sessionId,t,{onDelta:r.onDelta,onProgress:r.onProgress,signal:r.signal});let n=UO(r.env??process.env);dr("dsh",[],r.permissionMode??"yolo");let s=!r.sessionId,i=s?`session-${LO()}`:r.sessionId,a;try{let l=await Wb(n);s&&await l.rpc("session.create",{sessionId:i,cwd:r.cwd}),r.model&&(await l.rpc("session.selectModel",{sessionId:i,provider:"deepseek-official",model:r.model}),r.onProgress?.({kind:"system",summary:`dsh model set to ${r.model}`})),r.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),a=await this.promptAndWait(l,r.cwd,i,t,r.timeoutMs??PO,r.signal)}finally{await Fd()}return r.onProgress?.({kind:"system",summary:"dsh turn completed"}),{...a,sessionId:i,durationMs:Date.now()-o}}async openSession(t){let r=UO(t.env??process.env);dr("dsh",[],t.permissionMode??"yolo");let o=await Wb(r),n=!t.sessionId,s=n?`session-${LO()}`:t.sessionId;if(n)try{await o.rpc("session.create",{sessionId:s,cwd:t.cwd})}catch(g){throw await Fd(),new Error(`dsh bundle: session.create failed: ${Th(g)}`)}let i=qb(this.dshProvider.sessionFilePath(t.cwd,s)),a=!1;try{a=X3(i)&&hAe(i).isFile()}catch{a=!1}let l=a;if(!a&&!n)throw await Fd(),new Error(`dsh bundle: session file does not exist for session "${s}" (${i}) \u2014 the session must exist before a bundle can resume it`);t.model&&await o.rpc("session.selectModel",{sessionId:s,provider:"deepseek-official",model:t.model});let c=this,u=0,d=!1,f=null,p=!1,m=!1,h=async()=>{m||(m=!0,await Fd())};return{provider:"dsh",sessionId:s,get completedTurns(){return u},async sendTurn(g,_={}){if(d||f!==null)throw new Error("dsh bundle session is closed");if(p)throw new Error("dsh bundle session has a turn still in flight");if(_.signal?.aborted)throw new Error("Aborted");if(i=qb(i),l&&!X3(i))throw new Error(`dsh bundle: session file for session "${s}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);p=!0;let w=Date.now();try{let y,b=c.promptAndWait(o,t.cwd,s,g,PO,_.signal,I=>{y=I});b.catch(()=>{});let E=()=>{},T=new Promise((I,R)=>{E=()=>{(async()=>{d=!0,await h()})().finally(()=>{b.then(()=>{},A=>A?.usage).then(A=>R(Object.assign(new Error("Aborted"),{usage:A??y,sessionId:s})))})},_.signal?.addEventListener("abort",E,{once:!0})}),k;try{k=await Promise.race([b,T])}finally{_.signal?.removeEventListener("abort",E)}return u+=1,l=!0,{...k,sessionId:s,durationMs:Date.now()-w}}finally{p=!1}},close(){return f!==null||(f=(async()=>{d=!0,await h()})()),f}}}async promptAndWait(t,r,o,n,s,i,a){let l=Date.now(),c=qb(this.dshProvider.sessionFilePath(r,o)),u=!1,d=await J3(c,()=>{u=!0}),f=d.reduce((w,y)=>typeof y.seq=="number"&&Number.isSafeInteger(y.seq)?Math.max(w,y.seq):w,-1),p=new Cu(o,f,this.usageSeen);u&&p.invalidateOwnership();let m=JSON.stringify([c,o]),h=DO.get(m)??new Set;if(h.size){p.invalidateOwnership();for(let w of h)w.invalidateOwnership()}h.add(p),DO.set(m,h),d.filter(w=>w.type==="turn/start"||w.type==="turn/end").at(-1)?.type==="turn/start"&&p.invalidateOwnership();let _;try{await t.rpc("session.prompt",{sessionId:o,mode:"queue",content:[{type:"text",text:n}]});let w=s>0?Date.now()+s:1/0;for(;;){c=qb(c);let y=await J3(c),b=y.find(E=>E.type==="turn/end"&&(E.seq??-1)>f);if(y.length&&p.update(y,b?.seq??1/0),a?.(p.usage()),i?.aborted)throw new Error("Aborted");if(b){let E=b.data?.reason;E?.kind!=="completed"&&(_=E?.kind==="aborted"?"cancelled":"error");let T=[...y].reverse().find(R=>R.type==="assistant/message"&&(R.seq??-1)>f&&(R.seq??1/0)<=(b.seq??1/0)),k=T?wAe(T):"";if(E?.kind!=="completed"&&!k)throw new Error(vAe(E));p.finish();let I=p.usage();return{text:k,sessionId:o,durationMs:Date.now()-l,usage:I?{...I,...E?.kind==="completed"?{}:{outcome:E?.kind==="aborted"?"cancelled":"error"}}:void 0}}if(Date.now()>w)throw new Error(`dsh turn timed out after ${s}ms waiting for turn/end`);await new Promise(E=>{let T=()=>{clearTimeout(k),i?.removeEventListener("abort",T),E()},k=setTimeout(T,yAe);i?.addEventListener("abort",T,{once:!0})})}}catch(w){if(p.finish(),w instanceof Error){let y=p.usage();Object.assign(w,{usage:y?{...y,outcome:_}:void 0,sessionId:o})}throw w}finally{h.delete(p),h.size||DO.delete(m)}}}});import{existsSync as bAe}from"node:fs";import{join as e8,resolve as EAe}from"node:path";import{createRequire as TAe}from"node:module";function SAe(){return BO===null&&(BO=TAe(import.meta.url)("node:sqlite").DatabaseSync),BO}function WO(e={}){return EAe(e.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||e8(He,".hermes"))}function IAe(e={}){return e8(WO(e),"state.db")}function Sh(e){let t=typeof e=="number"&&Number.isFinite(e)?e:0;return new Date(t*1e3)}function Nn(e){return typeof e=="string"&&e.length>0?e:void 0}function kAe(e){if(!e)return{};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Y3(e){return Nn(e.cwd)??Nn(kAe(e.model_config).cwd)??"(unknown)"}function xAe(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function $Ae(e){if(e!==null&&typeof e=="object"&&!Array.isArray(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Q3(e){let t=e.input_tokens??0,r=e.output_tokens??0,o=e.cache_read_tokens??0,n=e.cache_write_tokens??0,s=e.reasoning_tokens??0;return(e.message_count??0)>0&&t+r+o+n+s>0?{totalInputTokens:t,totalCachedInputTokens:o,totalCacheWriteInputTokens:n,totalOutputTokens:r,totalReasoningOutputTokens:s}:{}}var BO,K3,Z3,Hb,t8=$(()=>{"use strict";Yt();Ke();BO=null;K3="acp";Z3=`id, source, model, model_config, started_at,
|
|
2161
2161
|
last_activity_at, message_count, input_tokens, output_tokens,
|
|
2162
2162
|
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;Hb=class{name="hermes";dbPath;busyTimeoutMs;discoverLimit;constructor(t){this.dbPath=IAe(t),this.busyTimeoutMs=t?.busyTimeoutMs??5e3,this.discoverLimit=t?.discoverLimit??-1}get stateDbPath(){return this.dbPath}openDb(){if(!bAe(this.dbPath))return null;let t=null;try{return t=new(SAe())(this.dbPath,{open:!0,readOnly:!0}),t.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),t}catch(r){return t?.close(),Z({event:"hermes_store_unavailable",provider:this.name,db_path:this.dbPath,error_message:r instanceof Error?r.message:String(r)}),null}}selectSessionRow(t,r){return t.prepare(`SELECT ${Z3} FROM sessions WHERE id = ? AND source = ?`).get(r,K3)??null}async discoverSessions(){let t=this.openDb();if(!t)return[];try{let r=t.prepare(`SELECT ${Z3} FROM sessions
|
|
2163
2163
|
WHERE source = ?
|
|
@@ -2486,7 +2486,7 @@ ${s}`)}function sl(e,t,r=[]){let o;try{let s=JSON.parse(t);o=typeof s?.error=="s
|
|
|
2486
2486
|
`),wMe(d)}finally{bMe(d)}r.assertOwned(),EMe(u,e.path)}finally{TMe(u,{force:!0})}return c}finally{r.release()}}var N9,HL,AMe,C9,j9=$(()=>{"use strict";Wt();N9="https://api.kimi.com/coding/v1",HL="https://auth.kimi.com",AMe="17e5f671-d194-4dfb-9706-5516cb48c098",C9=e=>$r(e.trim())});function F9(e){let t=i=>{if(typeof i!="number"&&typeof i!="string"||typeof i=="string"&&i.trim()==="")return;let a=Number(i);return Number.isFinite(a)&&a>=0?a:void 0},r=t(e.limit),o=t(e.used),n=t(e.remaining);if(r===void 0||r<=0||o===void 0&&(n===void 0||n>r))return;let s=o??r-n;return{used:s,limit:r,remaining:Math.max(0,r-s)}}async function z9({timeoutSeconds:e,env:t,debug:r,onRawResponse:o}){let n;try{n=P9(t)}catch(h){let g=h instanceof Error&&/^(credentials_missing|credentials_malformed|credentials_revoked|config_unreadable|config_malformed|config_format_unsupported|credential_storage_unsupported)$/.test(h.message)?h.message:"credentials_unreadable";return nr("kimi",g==="credentials_revoked"?"auth_expired":"provider_unavailable",g,g==="credentials_revoked"?"Kimi login was revoked; run kimi login":g.replaceAll("_"," "),"kimi_http")}let s=n.token,i=new AbortController,a=e>0?setTimeout(()=>i.abort(),e*1e3):void 0,l,c;try{let h=!1,g=async()=>{s=await U9({...n,token:s},i.signal),h=!0};qE(s)&&await g();let _=()=>fetch(`${n.baseUrl}/usages`,{headers:{Authorization:`Bearer ${s.access_token}`,Accept:"application/json"},signal:i.signal});l=await _(),c=await l.text(),fn({debug:r,onRawResponse:o},"kimi_http",c,[s.access_token,s.refresh_token],l.status),l.status===401&&!h&&s.refresh_token&&(await g(),l=await _(),c=await l.text(),fn({debug:r,onRawResponse:o},"kimi_http",c,[s.access_token,s.refresh_token],l.status))}catch(h){let g=h instanceof Error&&/^(no_refresh_token|credentials_changed|credentials_revoked|invalid_refresh_response|refresh_locked|refresh_lock_stale|refresh_lock_failed|refresh_lock_lost|refresh_request_failed|refresh_http_\d+)$/.test(h.message)?h.message:"request_failed",_=g==="credentials_revoked"||g==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(g),w=g==="refresh_lock_stale"?"Kimi refresh lock is stale; run the native Kimi CLI to recover its lock, or verify no refresh is active before removing the .lock directory":_?`Kimi credential renewal failed (${g}); run kimi login`:`Kimi quota request failed (${g})`;return nr("kimi",_?"auth_expired":"provider_unavailable",g,w,"kimi_http")}finally{clearTimeout(a)}let u=(h,g,_)=>sl(nr("kimi",h,g,g,"kimi_http",[],_),c,[s.access_token]);if(l.status===401)return u("auth_expired","HTTP 401 from Kimi usage endpoint");if(l.status===403)return u("not_applicable","HTTP 403 from Kimi usage endpoint");if(l.status===429){let h=FE(l.headers);return u("reader_throttled","HTTP 429 from Kimi usage endpoint",h)}if(l.status!==200)return u("provider_unavailable",`HTTP ${l.status} from Kimi usage endpoint`);let d;try{d=JSON.parse(c)}catch{return nr("kimi","provider_unavailable","malformed_response","SyntaxError: malformed JSON")}if(!d||typeof d!="object")return nr("kimi","provider_unavailable","malformed_response","response was not an object");let f=[],p=new Set;function m(h){let g=String(h.bucket_id),_=g,w=2;for(;p.has(g);)g=`${_}-${w}`,w++;p.add(g),h.bucket_id=g,f.push(qr(h))}if(Array.isArray(d.limits))for(let h of d.limits){if(!h||typeof h!="object")continue;let g=h.window,_=h.detail;if(!g||typeof g!="object"||!_||typeof _!="object")continue;let w=0;if(g.timeUnit==="TIME_UNIT_MINUTE")w=Number(g.duration);else if(g.timeUnit==="TIME_UNIT_HOUR")w=Number(g.duration)*60;else if(g.timeUnit==="TIME_UNIT_DAY")w=Number(g.duration)*1440;else if(g.timeUnit==="TIME_UNIT_WEEK")w=Number(g.duration)*10080;else if(g.timeUnit==="TIME_UNIT_MONTH")w=Number(g.duration)*43200;else continue;let y=QY(w),b="window";y==="five_hour"&&(b="5h"),y==="weekly"&&(b="weekly"),y==="monthly"&&(b="monthly");let E=F9(_);if(!E)continue;let{used:T,limit:k,remaining:I}=E;m({bucket_id:`kimi-${b}`,window_type:y,used_fraction:Ir(T/k),remaining_fraction:Ir(I/k),resets_at_iso:_.resetTime,raw_value:T,raw_scale:"count"})}if(d.usage&&typeof d.usage=="object"){let h=F9(d.usage);h&&m({bucket_id:"kimi-weekly",window_type:"weekly",used_fraction:Ir(h.used/h.limit),remaining_fraction:Ir(h.remaining/h.limit),resets_at_iso:d.usage.resetTime,raw_value:h.used,raw_scale:"count"})}if(d.usages&&typeof d.usages=="object"){let h=[{key:"limit_5h",id:"kimi-5h",type:"five_hour"},{key:"limit_7d",id:"kimi-weekly",type:"weekly"},{key:"limit_month_total",id:"kimi-monthly",type:"monthly"},{key:"limit_month_code",id:"kimi-monthly-code",type:"monthly"}];for(let{key:g,id:_,type:w}of h){let y=d.usages[g];if(!y||typeof y!="object"||y.used_ratio==null||y.used_ratio===""||typeof y.used_ratio=="boolean")continue;let b=Number(y.used_ratio);!Number.isFinite(b)||b<0||p.has(_)||(p.add(_),f.push(qr({bucket_id:_,window_type:w,used_fraction:Ir(b),resets_at_iso:typeof y.reset_time=="string"&&y.reset_time?y.reset_time:null,raw_value:b,raw_scale:"ratio"})))}}return gr("kimi","ok",{source:"kimi_http",buckets:f})}var B9=$(()=>{"use strict";Os();j9();Os()});function Yh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function HE(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""){let t=Number(e);if(Number.isFinite(t))return t}}async function W9(e){let{timeoutSeconds:t,env:r,debug:o,onRawResponse:n,fetchFn:s=fetch}=e,i=r.OLLAMA_API_KEY?.trim();if(!i)return nr("ollama-cloud","provider_unavailable","credentials_missing","$OLLAMA_API_KEY is missing","ollama_http");let a="https://ollama.com/api/balance",l=new AbortController,c=t>0?setTimeout(()=>l.abort(),Math.ceil(t*1e3)):void 0,u,d="";try{u=await s(a,{method:"GET",redirect:"error",headers:{Authorization:`Bearer ${i}`,Accept:"application/json"},signal:l.signal}),d=await u.text();let g=d;try{g=JSON.stringify(JSON.parse(d))}catch{}fn({debug:o,onRawResponse:n},"ollama_http",g,[i],u.status)}catch(g){let _=g instanceof Error&&g.name==="AbortError",w=_?`Ollama quota request timed out after ${t}s`:`Ollama quota request failed (${g instanceof Error?g.message:String(g)})`;return nr("ollama-cloud","provider_unavailable",_?"request_timeout":"request_failed",w,"ollama_http",[i])}finally{clearTimeout(c)}let f=(g,_,w)=>sl(nr("ollama-cloud",g,_,_,"ollama_http",[i],w),d,[i]);if(u.status===401)return f("auth_expired","HTTP 401 from Ollama balance endpoint");if(u.status===403)return f("not_applicable","HTTP 403 from Ollama balance endpoint");if(u.status===429){let g=FE(u.headers);return f("reader_throttled","HTTP 429 from Ollama balance endpoint",g)}if(u.status!==200)return f("provider_unavailable",`HTTP ${u.status} from Ollama balance endpoint`);let p;try{p=JSON.parse(d)}catch{return nr("ollama-cloud","provider_unavailable","malformed_response","SyntaxError: malformed JSON","ollama_http")}if(!Yh(p))return nr("ollama-cloud","provider_unavailable","malformed_response","response was not an object","ollama_http");let m=[];if(Yh(p.included)){let g=p.included,_=HE(g.allowance_usd),w=HE(g.balance_usd),y=Yh(g.period)?g.period:void 0,b=typeof y?.from=="string"?Date.parse(y.from):NaN,E=typeof y?.until=="string"?Date.parse(y.until):NaN,T=Number.isFinite(b)&&Number.isFinite(E)&&E>b,k=T?new Date(E).toISOString():null;if(_!==void 0&&_>0&&w!==void 0){let I=Math.max(0,_-w);m.push({...qr({bucket_id:"ollama-cloud-monthly",group_name:"ollama-cloud",window_type:"monthly",used_fraction:Ir(I/_),remaining_fraction:Ir(w/_),resets_at_iso:k,is_exhausted:w<=0,raw_value:w,raw_scale:"balance_usd"}),window_start_iso:T?new Date(Math.floor(b/1e3)*1e3).toISOString().replace(".000Z","Z"):null})}if(_===void 0&&w===void 0)for(let[I,R,A]of[["session","five_hour","5h"],["weekly","weekly","weekly"]]){let N=g[I];if(!Yh(N))continue;let x=HE(N.remaining_percent);x===void 0||x<0||x>100||m.push(qr({bucket_id:`ollama-cloud-${A}`,group_name:"ollama-cloud",window_type:R,remaining_fraction:x/100,resets_at_iso:typeof N.resets_at=="string"?N.resets_at:null,raw_value:x,raw_scale:"remaining_percent"}))}}let h;if(Yh(p.purchased)){let g=p.purchased,_=HE(g.balance_usd);_!==void 0&&(h={has_credits:_>0,balance:_})}return m.length===0&&h===void 0?nr("ollama-cloud","provider_unavailable","malformed_response","response has no usable included allowance or purchased balance","ollama_http"):gr("ollama-cloud","ok",{source:"ollama_http",buckets:m,...h?{credits:h}:{}})}var q9=$(()=>{"use strict";Os()});async function GE(e={}){let t=e.targets??e.providers??["all"];if(!Array.isArray(t)||t.length===0||t.some(d=>typeof d!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let d of t)if(!VE.includes(d))return{status:"error",error:`unknown provider: ${d} (valid targets: ${VE.join(", ")})`,readings:[]};let r=e.timeoutSeconds??CMe;if(!Number.isFinite(r)||r<0)return{status:"error",error:"timeoutSeconds must be a nonnegative finite number (0 disables the deadline)",readings:[]};let o=e.env??process.env,n=["codex","agy","claude","kimi"];(o.OLLAMA_API_KEY?.trim()||t.includes("ollama-cloud"))&&n.push("ollama-cloud");let s=new Set(t.includes("all")?n:t);e.progress?.(`querying ${t.join(" ")} live (${r>0?`timeout ${r}s per provider`:"no deadline"}) ...`);let a=Object.entries({codex:$9,agy:o9,claude:_9,kimi:z9,"ollama-cloud":W9}).filter(([d])=>s.has(d)).map(async([,d])=>{let f=[],p=await d({timeoutSeconds:r,env:o,...e.debug?{debug:e.debug}:{},...e.includeRaw?{onRawResponse:h=>f.push(h)}:{}}),m=e.includeRaw?{...p,raw_responses:f}:p;return m&&e.onReading?.(m),m}),l=await Promise.allSettled(a),c=l.find(d=>d.status==="rejected");return c?{status:"error",error:String(c.reason),readings:[]}:{status:"ok",readings:l.filter(d=>d.status==="fulfilled").map(d=>d.value).filter(Boolean)}}var VE,CMe,VL=$(()=>{"use strict";s9();y9();A9();B9();q9();VE=["all","codex","agy","claude","kimi","ollama-cloud"],CMe=0});import{createHash as OMe}from"node:crypto";import{existsSync as H9,mkdirSync as MMe,readFileSync as LMe,renameSync as DMe,writeFileSync as PMe}from"node:fs";import{dirname as UMe,join as jMe}from"node:path";function FMe(e,t,r,o=200){return e.prepare(`SELECT u.*, t.rate_input_1m, t.rate_output_1m, t.rate_cache_read_1m, t.rate_cache_write_1m
|
|
2487
2487
|
FROM turn_usage u JOIN team_chat_log t ON t.id=u.id
|
|
2488
2488
|
WHERE u.ended_at IS NOT NULL AND u.ended_at <= ? AND (u.ended_at > ? OR (u.ended_at = ? AND u.id > ?))
|
|
2489
|
-
ORDER BY u.ended_at,u.id LIMIT ?`).all(new Date(r-6e4).toISOString(),t.ended_at,t.ended_at,t.id,o)}function zMe(e,t){let r=(c,u)=>c===null?null:c===0?0:u===null?null:c*u/1e6,o=r(e.tok_input_uncached,e.rate_input_1m),n=r(e.tok_cache_read,e.rate_cache_read_1m),s=r(e.tok_output,e.rate_output_1m),i=r(e.tok_cache_write,e.rate_cache_write_1m??e.rate_input_1m),a=e.usage_source!==null&&e.cost_reason===null&&[o,n,s,i].every(c=>c!==null),l=a?null:e.cost_reason||e.usage_reason||"usage_unavailable";return{attempt_key:e.attempt_key,sessionid:null,session_key:V9(JSON.stringify([t,e.provider,e.native_session_id??e.attempt_key])),timestamp:e.started_at,ended_at:e.ended_at,status:e.status,provider:e.provider,model_id:e.model,teamfile:e.team,alias:e.alias,input_uncached_tokens:e.tok_input_uncached,input_cached_tokens:e.tok_cache_read,output_tokens:e.tok_output,cache_write_tokens:e.tok_cache_write,reasoning_tokens:e.tok_reasoning,input_uncached_cost:a?o:null,input_cached_cost:a?n:null,output_cost:a?s:null,cache_write_cost:a?i:null,cost_usd:a?o+n+s+i:null,cost_reason:l,usage_source:e.usage_source,usage_reason:e.usage_reason,price_record_id:e.price_record_id,rates:{input_1m:e.rate_input_1m,output_1m:e.rate_output_1m,cache_read_1m:e.rate_cache_read_1m,cache_write_1m:e.rate_cache_write_1m??e.rate_input_1m}}}function G9(e){let t=jMe(e.directory,`monitor-${V9(e.identity)}.json`),r={ended_at:new Date(e.now()-48*36e5).toISOString(),id:0};if(H9(t)){let o=JSON.parse(LMe(t,"utf8"));if(typeof o.ended_at!="string"||!Number.isFinite(Date.parse(o.ended_at))||!Number.isSafeInteger(o.id)||o.id<0)throw new Error("invalid monitor cursor; repair the site monitor cursor file");r=o}return{prepare(){if(!H9(e.dbPath))return null;let o=Ro(e.dbPath),n;try{n=FMe(o,r,e.now())}finally{o.close()}let s={schema:"lmctl-site-monitor/1",turns:[]},i=r;for(let a of n){if(s.turns.push(zMe(a,e.site)),Buffer.byteLength(JSON.stringify(s))>56*1024){s.turns.pop();break}i={ended_at:a.ended_at,id:a.id}}return{monitor:s,acknowledge(a){let l=a?.monitor;!l||
|
|
2489
|
+
ORDER BY u.ended_at,u.id LIMIT ?`).all(new Date(r-6e4).toISOString(),t.ended_at,t.ended_at,t.id,o)}function zMe(e,t){let r=(c,u)=>c===null?null:c===0?0:u===null?null:c*u/1e6,o=r(e.tok_input_uncached,e.rate_input_1m),n=r(e.tok_cache_read,e.rate_cache_read_1m),s=r(e.tok_output,e.rate_output_1m),i=r(e.tok_cache_write,e.rate_cache_write_1m??e.rate_input_1m),a=e.usage_source!==null&&e.cost_reason===null&&[o,n,s,i].every(c=>c!==null),l=a?null:e.cost_reason||e.usage_reason||"usage_unavailable";return{attempt_key:e.attempt_key,sessionid:null,session_key:V9(JSON.stringify([t,e.provider,e.native_session_id??e.attempt_key])),timestamp:e.started_at,ended_at:e.ended_at,status:e.status,provider:e.provider,model_id:e.model,teamfile:e.team,alias:e.alias,input_uncached_tokens:e.tok_input_uncached,input_cached_tokens:e.tok_cache_read,output_tokens:e.tok_output,cache_write_tokens:e.tok_cache_write,reasoning_tokens:e.tok_reasoning,input_uncached_cost:a?o:null,input_cached_cost:a?n:null,output_cost:a?s:null,cache_write_cost:a?i:null,cost_usd:a?o+n+s+i:null,cost_reason:l,usage_source:e.usage_source,usage_reason:e.usage_reason,price_record_id:e.price_record_id,rates:{input_1m:e.rate_input_1m,output_1m:e.rate_output_1m,cache_read_1m:e.rate_cache_read_1m,cache_write_1m:e.rate_cache_write_1m??e.rate_input_1m}}}function G9(e){let t=jMe(e.directory,`monitor-${V9(e.identity)}.json`),r={ended_at:new Date(e.now()-48*36e5).toISOString(),id:0};if(H9(t)){let o=JSON.parse(LMe(t,"utf8"));if(typeof o.ended_at!="string"||!Number.isFinite(Date.parse(o.ended_at))||!Number.isSafeInteger(o.id)||o.id<0)throw new Error("invalid monitor cursor; repair the site monitor cursor file");r=o}return{prepare(){if(!H9(e.dbPath))return null;let o=Ro(e.dbPath),n;try{n=FMe(o,r,e.now())}finally{o.close()}let s={schema:"lmctl-site-monitor/1",turns:[]},i=r;for(let a of n){if(s.turns.push(zMe(a,e.site)),Buffer.byteLength(JSON.stringify(s))>56*1024){s.turns.pop();break}i={ended_at:a.ended_at,id:a.id}}return{monitor:s,acknowledge(a){let l=a?.monitor;!l||(l.accepted??0)+(l.duplicate??0)+(l.late??0)+(l.rejected??0)!==s.turns.length||i.ended_at<r.ended_at||i.ended_at===r.ended_at&&i.id<=r.id||(MMe(UMe(t),{recursive:!0,mode:448}),PMe(`${t}.tmp`,JSON.stringify(i)+`
|
|
2490
2490
|
`,{mode:384}),DMe(`${t}.tmp`,t),r=i)}}}}}async function X9(e){return(await GE({providers:["all"],timeoutSeconds:10,env:e})).readings.map(r=>({provider:r.provider,read_at:r.read_at,status:["ok","unavailable","error","unauthenticated","unsupported","rate_limited"].includes(String(r.status))?r.status:"unavailable",buckets:(Array.isArray(r.buckets)?r.buckets:[]).slice(0,10).map(o=>({window_type:["five_hour","weekly","monthly","unknown"].includes(o.window_type)?o.window_type:"unknown",used_fraction:typeof o.used_fraction=="number"?o.used_fraction:null,resets_at:typeof o.resets_at=="number"?o.resets_at:null}))}))}var V9,J9=$(()=>{"use strict";Xc();VL();V9=e=>OMe("sha256").update(e).digest("hex").slice(0,32)});var lg={};Ne(lg,{LmctlRunError:()=>sg,NEW_SESSION_SCHEMA:()=>XL,SEARCH_CAPS:()=>il,SEARCH_SCHEMA:()=>nD,SHELL_CAPS:()=>rg,SITE_SCHEMA:()=>og,TAIL_SCHEMA:()=>tT,afterCursor:()=>_7,answerText:()=>E7,attentionSites:()=>lD,auditShell:()=>ZL,childEnv:()=>p7,consoleTargets:()=>f7,disableSite:()=>A7,enableSite:()=>$7,failureAnswer:()=>Jn,failureText:()=>rT,isNewSessionName:()=>rD,isTranscriptBookkeeping:()=>sD,listOrgs:()=>I7,listSites:()=>b7,liveTailView:()=>g7,lmctlMessage:()=>u7,modelsFrom:()=>QL,newSessionCommands:()=>C7,newSessionTeamfile:()=>w7,nextCursor:()=>y7,parseAllow:()=>oD,parseCursor:()=>iD,promptRefusal:()=>JE,promptSite:()=>T7,readAppkey:()=>ag,redact:()=>Lr,removeSite:()=>k7,resolveTarget:()=>eg,runConfiguredSite:()=>rLe,runShellCommand:()=>d7,runSite:()=>oLe,scheduleSite:()=>N7,searchLocal:()=>v7,searchSites:()=>O7,serveSite:()=>aD,sessionsFrom:()=>YL,siteApiUrl:()=>ig,siteConfigPath:()=>df,siteStatus:()=>nT,tailSite:()=>S7,tailView:()=>h7,takeRepeated:()=>QE,usageCostView:()=>YE});import{spawn as o7}from"node:child_process";import{mkdirSync as BMe,readFileSync as ng,renameSync as WMe,rmSync as qMe,writeFileSync as HMe}from"node:fs";import{appendFile as VMe,chmod as GMe,lstat as XMe,mkdir as tg,mkdtemp as K9,readFile as JMe,rename as s7,rm as Z9,stat as KMe,writeFile as Qh}from"node:fs/promises";import{homedir as eD,hostname as ZMe,tmpdir as Y9}from"node:os";import{basename as uf,join as Bt,resolve as tD}from"node:path";import{createHash as Q9}from"node:crypto";function ig(e){return $r(e.LMCTL_SITE_API_URL?.trim()||"https://lmctl.ai")}function ag(e,t=r=>ng(r,"utf8")){let r=e.LMCTL_APPKEY?.trim();if(r&&!r.includes(`
|
|
2491
2491
|
`))return r;let o=[e.LMCTL_APPKEY_FILE?.trim(),Bt(e.XDG_CONFIG_HOME?.trim()||Bt(e.HOME||eD(),".config"),"lmctl","appkey.json")];for(let n of o){if(!n)continue;let s;try{s=t(n).trim()}catch{continue}if(s){if(s.startsWith("{")){try{let i=JSON.parse(s).appkey;if(typeof i=="string"&&i.trim())return i.trim()}catch{}continue}if(!s.includes(`
|
|
2492
2492
|
`))return s}}return null}function Ls(e,t){let r=e.env??process.env,o=ag(r);if(!o)return null;let n=ig(r);async function s(i,a,l,c=!0,u={}){let d=await t.fetch(n+a,{method:i,headers:{authorization:`Bearer ${o}`,...l===void 0?{}:{"content-type":"application/json"},...u},...l===void 0?{}:{body:JSON.stringify(l)},...c&&t.signal?{signal:t.signal}:{}}),f=await d.text(),p=null;try{p=f?JSON.parse(f):null}catch{p=null}if(d.status>=400){let m=p?.error;throw new bo(d.status,typeof m=="string"?m:"request_failed")}return{status:d.status,json:p}}return{call:s,base:n}}function ut(e){return e instanceof bo||e instanceof Error?e.message:String(e)}function u7(e){for(let t of e.trim().split(`
|
package/dist/cli/lmscript.js
CHANGED
|
@@ -2861,7 +2861,7 @@ ${A}`:C.message,R,S,u),{usage:M.usage.usage(),sessionId:a}))}for(let A of y.spli
|
|
|
2861
2861
|
`):"":""}function W7(t){return t.model||t.message?.model}function P0e(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:z7(t).filter(n=>!n.thought&&n.type!=="thinking"&&typeof n.text=="string"&&n.text.length>0).length}function Bh(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 D0e(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return Bh(e.output??e.error??t)}return Bh(t)}function z7(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function q7(t,e,n){let r=t.name||"tool";return{role:"tool_use",timestamp:e,content:r,toolName:r,toolInput:Bh(t.args,!0),toolInputData:ps(t.args),toolCallId:t.id,model:n}}var dS,X7=P(()=>{"use strict";nn();dS=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||bl(Ke,".qwen")}async discoverSessions(){let e=bl(this.baseDir,"projects"),n;try{n=await uS(e)}catch{return[]}let r=[];for(let s of n){let i=bl(e,s,"chats"),o;try{o=await uS(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=bl(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 tn(e),i="(unknown)",o,a,l,c,u=0;for await(let d of Mt(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)),F7(d)){let p=H7(d).trim();p&&(l||(l=ye(p,80)),c=ye(p,80),u++)}if(B7(d)){let p=W7(d);p&&(o=p),u+=P0e(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=U7(n,".jsonl");return this.loadFromFile(n,r)}async loadFromFile(e,n){let r=await tn(e),s="(unknown)",i,o,a,l,c,u,d=[],p=N0e();for await(let f of Mt(e)){if(L0e(p,f.usageMetadata),f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.gitBranch&&(a=f.gitBranch)),f.type==="system"&&f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.model&&(i=f.model),f.gitBranch&&(a=f.gitBranch)),!f.message)continue;let m=f.message,g=f.timestamp?new Date(f.timestamp):r.modifiedAt;if(f.type==="tool_result"){let y=z7(f).filter(h=>h.functionResponse!==void 0);y.length===0&&f.toolCallResult?.callId&&d.push({role:"tool_result",timestamp:g,content:Bh(f.toolCallResult.resultDisplay??f.toolCallResult.error??f.toolCallResult.status)??"tool result",toolCallId:f.toolCallResult.callId});for(let h of y){let v=h.functionResponse,_=D0e(v.response),b=Bh(f.toolCallResult?.resultDisplay);d.push({role:"tool_result",timestamp:g,content:b??_??f.toolCallResult?.status??"tool result",toolName:v.name,toolCallId:f.toolCallResult?.callId??v.id,..._!==void 0?{toolDetailedContent:_}:{}})}}else if(F7(f)){let y=H7(f);y.trim()&&(c||(c=ye(y.trim(),80)),u=ye(y.trim(),80)),d.push({role:"user",timestamp:g,content:y})}else if(B7(f)){let y=W7(f);if(y&&(i=y),Array.isArray(m.content))for(let h of m.content)h.type==="text"&&h.text?d.push({role:"assistant",timestamp:g,content:h.text,model:y}):h.type==="thinking"&&h.thinking?d.push({role:"thinking",timestamp:g,content:h.thinking}):h.functionCall&&d.push(q7(h.functionCall,g,y));else if(typeof m.content=="string")d.push({role:"assistant",timestamp:g,content:m.content,model:y});else if(Array.isArray(m.parts))for(let h of m.parts)if(h.thought||h.type==="thinking"){let v=h.thinking||h.text;v&&d.push({role:"thinking",timestamp:g,content:v})}else h.functionCall?d.push(q7(h.functionCall,g,y)):h.text&&d.push({role:"assistant",timestamp:g,content:h.text,model:y})}}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(f=>f.role==="user"||f.role==="assistant").length,filePath:e,...M0e(p),messages:d}}async resolveSessionPath(e){let n=bl(this.baseDir,"projects");try{let r=await uS(n),s=[];for(let i of r){let o=bl(n,i,"chats",`${e}.jsonl`);try{return await C0e(o,{flag:"r"}),o}catch{continue}}for(let i of r){let o=bl(n,i,"chats"),a;try{a=await uS(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;U7(l,".jsonl").startsWith(e)&&s.push(bl(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 O0e(n),!0}catch{return!1}}}});function _$(t){return new y$(t)}var y$,v$=P(()=>{"use strict";X7();ar();vl();jn();y$=class extends gt{constructor(e){super({provider:new dS(e),protocol:{transport:"stream-json",perTurnCancellation:"process",persistentCancellation:"session",persistentResume:!0},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",ze,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:QT})}openSession(e){return eS({...e,binary:"qwen"})}seedArgsFor(e){let n=super.seedArgsFor(e);return e?.model?[...n,"--model",e.model]:n}}});import{readdir as G7,readFile as V7,rm as J7,stat as b$}from"node:fs/promises";import{basename as w$,dirname as K7,join as ri}from"node:path";import{fileURLToPath as $0e}from"node:url";async function j0e(t){let e=await Promise.all(t.map(n=>tn(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 U0e(t,e){if(!t)return e;let n=new Date(t);return Number.isNaN(n.getTime())?e:n}function Z7(t){return t.type==="USER_INPUT"}function Y7(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function F0e(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function Q7(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function eQ(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 B0e(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function H0e(t){for await(let e of Mt(t)){let n=e.tool_calls?.map(s=>s.args)??[];for(let s of n){let i=W0e(s);if(i)return i}let r=q0e(e.content);if(r)return r}return null}function W0e(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 q0e(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function z0e(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 X0e(t,e){let n=new Set;for(let r of e){let s=G0e(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 G0e(t,e,n){let r=n.message.backgroundTaskId===void 0?void 0:Z0e(n.event.content);if(r!==void 0)return tQ(t.filter(i=>!e.has(i)&&Y0e(i)===r),n.event.step_index);let s=K0e(n.event);if(s!==void 0)return tQ(t.filter(i=>!e.has(i)&&V0e(i.name,n.event.type)&&nQ(J0e(i))===s),n.event.step_index)}function tQ(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 V0e(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 J0e(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function K0e(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]),nQ(e)}function nQ(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return $0e(e)}catch{return}}function Z0e(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function Y0e(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 E$(t){if(t.endsWith(".db"))return w$(t,".db");let e="/brain/",n=t.indexOf(e);return n===-1?null:t.slice(n+e.length).split("/")[0]||null}async function rQ(t){if(t.endsWith(".jsonl"))return t;let e=E$(t);if(!e||!t.endsWith(".db"))return null;let n=K7(K7(t));for(let r of["transcript_full.jsonl","transcript.jsonl"]){let s=ri(n,"brain",e,".system_generated","logs",r);try{return await b$(s),s}catch{}}return null}var pS,T$=P(()=>{"use strict";nn();pS=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||ri(Ke,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:ri(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=ri(this.baseDir,"conversations"),n;try{n=await G7(e)}catch{return[]}let r=[];for(let s of n){if(!s.endsWith(".db"))continue;let i=w$(s,".db");try{let o=await this.extractSummary(i);o&&r.push(o)}catch{}}return r}conversationPath(e){return ri(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,n){return ri(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 b$(n),n}catch{}return null}async extractSummary(e){let n=this.conversationPath(e),r=await this.existingTranscriptPath(e),s=r??n,i=await j0e([n,r].filter(Boolean)),o=await this.resolveCwd(e,r),a,l,c,u=0;if(r)for await(let d of Mt(r)){let p=eQ(d.content);if(p&&(a=p),Z7(d)){let f=Q7(d.content).trim();f&&(l||(l=ye(f,80)),c=ye(f,80)),u++}else Y7(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=E$(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 p of Mt(i)){let f=U0e(p.created_at,s.modifiedAt),m=eQ(p.content);if(m&&(a=m),Z7(p)){let g=Q7(p.content),y=g.trim();y&&(l||(l=ye(y,80)),c=ye(y,80)),o.push({role:"user",timestamp:f,content:g});continue}if(Array.isArray(p.tool_calls))for(let g of p.tool_calls){let y=g.name||"tool",h=B0e(g.args),v=ps(g.args),_={role:"tool_use",timestamp:f,content:h,toolName:y,toolInput:h,toolInputData:v};o.push(_),u.push({name:y,stepIndex:p.step_index,input:v,message:_})}if(Y7(p)&&p.content)o.push({role:"assistant",timestamp:f,content:p.content,model:a});else if(F0e(p)&&p.content){let g=z0e(p,r),y=g===void 0?null:await this.readTaskLog(r,g),h={role:"tool_result",timestamp:y?.modifiedAt??f,content:p.content,toolName:p.type?.toLowerCase(),backgroundTaskId:g,...y===null?{}:{toolDetailedContent:y.content}};o.push(h),d.push({event:p,message:h})}p.thinking&&o.push({role:"thinking",timestamp:f,content:p.thinking})}return X0e(u,d),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(p=>p.role==="user"||p.role==="assistant").length,messages:o}}async resolveSessionPath(e){let n=this.conversationPath(e);try{return await b$(n),n}catch{}let r=ri(this.baseDir,"conversations");try{let s=[];for(let i of await G7(r)){if(!i.endsWith(".db"))continue;w$(i,".db").startsWith(e)&&s.push(ri(r,i))}if(s.length===1)return s[0]}catch{}return null}async resolveTailTranscriptPath(e){let n=await this.resolveSessionPath(e);return n?rQ(n):null}async deleteSession(e){let n=await this.resolveSessionPath(e);if(!n)return!1;let r=E$(n);return r?(await J7(this.conversationPath(r),{force:!0}),await J7(ri(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 H0e(n);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let n=ri(this.baseDir,"cache","last_conversations.json");try{let r=JSON.parse(await V7(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=ri(this.baseDir,"brain",e,".system_generated","tasks",`${n}.log`);try{let[s,i]=await Promise.all([V7(r,"utf8"),tn(r)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as Q0e}from"node:child_process";import{StringDecoder as sQ}from"node:string_decoder";function fS(t){return async(e,n)=>{let r=Date.now(),s=t.buildArgs(e,n);t.assertArgs?.(s,n),n.onProgress?.({kind:"system",summary:`${t.label} -p one-shot started (no streaming events)`});let{stdout:i}=await eMe(t.label,n.binary,s,{cwd:n.cwd,env:un(n.env,n.cwd,n.sessionId),signal:n.signal});return n.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:n.sessionId,durationMs:Date.now()-r}}}function eMe(t,e,n,r){return new Promise((s,i)=>{if(r.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=Q0e(e,n,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(p){i(p);return}let a="",l="",c=new sQ("utf8"),u=new sQ("utf8");o.stdout?.on("data",p=>{a+=c.write(p)}),o.stderr?.on("data",p=>{l+=u.write(p)});let d=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",p=>{r.signal?.removeEventListener("abort",d),i(p)}),o.on("close",(p,f)=>{if(r.signal?.removeEventListener("abort",d),a+=c.end(),l+=u.end(),p===0){s({stdout:a,stderr:l});return}let m=f?`signal ${f}`:`exit code ${p}`,g=l.trim()||a.trim();i(new Error(xd(`${t} failed (${m})`,g?Gt(g,{provider:t}):"")))}),r.signal?.aborted?d():r.signal?.addEventListener("abort",d,{once:!0})})}var S$=P(()=>{"use strict";Xs();zs()});import{basename as tMe}from"node:path";import{randomUUID as nMe}from"node:crypto";function x$(t){return new k$(t)}function sMe(t){return t!==void 0&&t<=0||t===void 0?"0":`${Math.max(1,Math.ceil(t/1e3))}s`}var k$,rMe,I$=P(()=>{"use strict";T$();ar();jn();Ci();S$();k$=class extends gt{constructor(e){super({provider:new pS(e),protocol:{transport:"print",perTurnCancellation:"process"},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",ze,"--dangerously-skip-permissions","--print-timeout","0"],resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:rMe})}async sendTurn(e,n){if(n.requireResume){let s=await this.resolvePath(n.sessionId);if(s===null||tMe(s)!==`${n.sessionId}.db`)throw new Error(`agy cannot resume missing conversation "${n.sessionId}"`)}let r=await super.sendTurn(e,n);return n.permissionMode==="plan"?{...r,warnings:[...r.warnings??[],"agy does not enforce plan mode; this turn used full permissions"]}:r}seedArgsFor(e){let n=[...super.seedArgsFor(e)];return e?.model&&n.push("--model",e.model),n}async seed(e,n){let r=nMe(),s=`[lmctl-seed:${r}]`,i=await super.seed(e,{...n,prompt:Db({flightToken:r,prompt:n?.prompt})});if(!i.success&&(i.errorCode==="ENOENT"||i.errorCode==="ABORT_ERR"))return i;let o=(await this.provider.discoverSessions()).filter(a=>a.firstUserMessage?.startsWith(s));if(i.success&&o.length===1)return{...i,sessionId:o[0].sessionId};for(let a of o)await this.provider.deleteSession(a.sessionId);return{...i,success:!1,error:i.error??`agy seed created ${o.length} identifiable sessions; expected one`}}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}`}}},rMe=fS({label:"agy",buildArgs:(t,e)=>{let n=[...e.sessionId?["--conversation",e.sessionId]:[],"-p",t,"--dangerously-skip-permissions","--print-timeout",sMe(e.timeoutMs)];return e.model&&n.push("--model",e.model),n},assertArgs:(t,e)=>_n("agy",t,e.permissionMode??"yolo")})});import{existsSync as Hh,readdirSync as iMe,statSync as iQ}from"node:fs";import{readdir as R$,rm as oMe}from"node:fs/promises";import oQ,{join as Bi}from"node:path";function aMe(t){if(t.length===0)throw new Error("cannot encode an empty project path");let e="",n=!1;for(let s=0;s<t.length;s++){let i=t.charCodeAt(s),o=String.fromCharCode(i);o==="/"||o==="\\"||o===":"?(n||(e+="-"),n=!0):o!=="~"&&/^[A-Za-z0-9._-]$/.test(o)?(e+=o,n=!1):(e+="~"+i.toString(16).toUpperCase().padStart(4,"0"),n=!1)}return`--${(e.replace(/^-+/,"")||"root").slice(0,251)}--`}function lMe(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function jp(t,e){let n=e??(process.platform==="win32"?oQ.win32:oQ.posix),r=t,s="session.jsonl.zstd";if((t.endsWith(".jsonl.zstd")||t.endsWith(".jsonl"))&&(r=n.dirname(t),s=n.basename(t)),!Hh(r))return t.endsWith(".jsonl.zstd")||t.endsWith(".jsonl")?t:n.join(t,s);try{let i=iMe(r),o=[];for(let a of i){let l=/^session(?:\.v(\d+))?\.jsonl\.zstd$/.exec(a);if(l){let c=l[1]?parseInt(l[1],10):0;if(Number.isSafeInteger(c))try{let u=n.join(r,a);iQ(u).isFile()&&o.push({name:a,version:c})}catch{}}}if(o.length>0)return o.sort((a,l)=>l.version-a.version),n.join(r,o[0].name)}catch{}try{if(Hh(t)&&iQ(t).isFile())return t}catch{}return n.join(r,s)}function A$(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 cMe(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 aQ(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:A$(i.content)})}else if(n.type==="assistant/message"){let i=r.message;for(let o of cMe(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:A$(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:A$(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function uMe(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 lQ(t,e,n){let r=t.find(f=>f.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 f of t)if(f.type==="request/header"){let m=f.data?.header;m?.config?.model&&(a=m.config.model)}let l=t.map(f=>f.time).filter(f=>typeof f=="number"),c=s.createdAt??i?.createdAt,u=c?new Date(c):new Date(0),d=l.length>0?new Date(Math.max(...l)):u,p=n.filter(f=>f.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:u,modifiedAt:d,model:a,firstUserMessage:p[0]?.content,lastUserMessage:p.at(-1)?.content,messageCount:n.filter(f=>f.role==="user"||f.role==="assistant").length,filePath:e,...dMe(t)}}function dMe(t){let e=new Map;for(let o of t){let a=o.data?.turn??null,l=e.get(a)??[];l.push(o),e.set(a,l)}let n=[],r=[];for(let o of e.values()){let a=new Nd("",-1,new Set);a.update(o);let l=a.usage();l&&(n.push(l),r.push(a.lastUsage()))}if(!n.length)return{};let s=o=>{if(n.some(l=>l.invalidCounters||l[o]===null))return;let a=n.reduce((l,c)=>l+c[o],0);return Number.isSafeInteger(a)?a:void 0},i=r.at(-1);return{totalInputTokens:s("inputUncached"),totalCachedInputTokens:s("cacheRead"),totalOutputTokens:s("output"),totalReasoningOutputTokens:s("reasoning"),lastInputTokens:i.inputUncached!==null&&i.cacheRead!==null?i.inputUncached+i.cacheRead:void 0,lastTokenUsage:{totalTokens:i.inputUncached!==null&&i.cacheRead!==null&&i.output!==null?i.inputUncached+i.cacheRead+i.output:void 0,inputTokens:i.inputUncached??void 0,cachedInputTokens:i.cacheRead??void 0,outputTokens:i.output??void 0,reasoningOutputTokens:i.reasoning??void 0}}}var mS,cQ=P(()=>{"use strict";jb();nn();bv();mS=class{name="dsh";sessionsDir;constructor(e={}){let n=e.dshHome||process.env.DSH_HOME||Bi(Ke,".dsh");this.sessionsDir=Bi(n,"sessions")}async discoverSessions(){let e=[],n;try{n=await R$(this.sessionsDir)}catch{return[]}for(let r of n){let s;try{s=await R$(Bi(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=aQ(r),i=lQ(r,n.filePath,s);return i?{...i,turnStatus:uMe(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 oMe(Bi(this.sessionsDir,n.cwdDir,n.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,n){let r=aMe(e),s=lMe(e),i=r,o=Bi(this.sessionsDir,r,n),a=Bi(this.sessionsDir,s,n);!Hh(o)&&Hh(a)&&(i=s);let l=Bi(this.sessionsDir,i,n);return jp(l)}async findSessionDir(e){let n;try{n=await R$(this.sessionsDir)}catch{return null}for(let r of n){let s=e,i=Bi(this.sessionsDir,r,s);try{let o=jp(i);if(Hh(o))return{cwdDir:r,sessionDir:s,filePath:o}}catch{}}return null}async readRecords(e,n){let{readFile:r}=await import("node:fs/promises"),s=Bi(this.sessionsDir,e,n),i=jp(s),o=await r(i),a=vv(o),l=[];for(let c of a.split(`
|
|
2862
2862
|
`))if(c.trim())try{let u=JSON.parse(c);if(u.type?.endsWith("-chunks")||u.type==="assistant/chunk"&&u.data?.chunk?.type!=="usage")continue;l.push(u)}catch{}return l}async readSummary(e,n){let r=Bi(this.sessionsDir,e,n),s=jp(r),i=await this.readRecords(e,n);return i.length===0?null:lQ(i,s,aQ(i))}}});import{spawn as pMe}from"node:child_process";import{randomUUID as fMe}from"node:crypto";function C$(t,e=[]){if(t==null)return t;if(typeof t=="string"){let n=t;for(let r of e)r&&typeof r=="string"&&r.length>=8&&n.includes(r)&&(n=n.replaceAll(r,"[REDACTED]"));return n=n.replace(/(?:sk-|dsh-)[A-Za-z0-9_\-\.]+/gi,"[REDACTED]"),n=n.replace(/(?:token=)[A-Za-z0-9_\-\.]+/gi,"token=[REDACTED]"),n=n.replace(/bearer\s+[A-Za-z0-9_\-\.]+/gi,"Bearer [REDACTED]"),n}if(Array.isArray(t))return t.map(n=>C$(n,e));if(typeof t=="object"){let n={};for(let[r,s]of Object.entries(t))/api[_-]?key|secret|token|password|auth|authorization|credential|cookie/i.test(r)?n[r]="[REDACTED]":n[r]=C$(s,e);return n}return t}function gMe(t){let e;try{e=new URL(t)}catch{throw new Error("invalid dsh boot URL: malformed URL")}if(e.protocol!=="http:")throw new Error(`invalid dsh boot URL scheme "${e.protocol}": must be http:`);if(e.username||e.password)throw new Error("invalid dsh boot URL: userinfo credentials are not allowed");let n=e.hostname;if(!(n==="127.0.0.1"||n==="localhost"||n==="::1"||n==="[::1]"))throw new Error(`invalid dsh boot URL host "${n}": loopback host (127.0.0.1 or localhost) required`);return e}function uQ(t,e=2e3){if(!t||t.exitCode!==null||t.signalCode!==null)return;try{t.kill("SIGTERM")}catch{}let n,r=()=>{n!==void 0&&(clearTimeout(n),n=void 0)};if(t.once("exit",r),t.exitCode!==null||t.signalCode!==null){r();return}n=setTimeout(()=>{n=void 0;try{t.exitCode===null&&t.signalCode===null&&t.kill("SIGKILL")}catch{}},e),n.unref()}async function gS(t,e=n=>O$.spawn(n)){if(wl){let n=await wl.catch(()=>{});if(n?.alive)return n;wl=void 0}return wl=e(t),wl}async function Up(){if(!wl)return;(await wl.catch(()=>{}))?.shutdown(),wl=void 0}var mMe,Wo,O$,wl,dQ=P(()=>{"use strict";zs();mMe=/dsh web:\s*(https?:\/\/\S+)/;Wo=class t extends Error{method;detail;constructor(e,n,r=[]){let s=C$(n,r),i=typeof s=="string"?s:JSON.stringify(s);super(`dsh RPC ${e} failed: ${i}`),this.name="DshRpcCallError",this.method=e,this.detail=s,Object.setPrototypeOf(this,t.prototype)}};O$=class t{constructor(e,n,r,s=!1,i){this.baseUrl=e;this.child=n;this.cookie=r;this.isV2=s;this.tokenUrl=i;if(this.cookie&&this.recordSecret(this.cookie),this.tokenUrl){this.recordSecret(this.tokenUrl);try{let a=new URL(this.tokenUrl).searchParams.get("token");a&&this.recordSecret(a)}catch{}}}static MAX_RETAINED_SECRETS=8;cookieExchangePromise;knownSecrets=[];recordSecret(e){if(!e||typeof e!="string"||e.length<8)return;let n=r=>{if(r.length<8)return;let s=this.knownSecrets.indexOf(r);for(s!==-1&&this.knownSecrets.splice(s,1),this.knownSecrets.push(r);this.knownSecrets.length>t.MAX_RETAINED_SECRETS;)this.knownSecrets.shift()};if(n(e),e.includes("=")){let r=e.split("=")[1];r&&r.length>=8&&n(r)}}getSecretsToRedact(e=[]){let n=new Set;for(let r of this.knownSecrets)r&&r.length>=8&&n.add(r);if(this.cookie&&this.cookie.length>=8){n.add(this.cookie);let r=this.cookie.split("=")[1];r&&r.length>=8&&n.add(r)}if(this.tokenUrl)try{let s=new URL(this.tokenUrl).searchParams.get("token");s&&s.length>=8&&n.add(s)}catch{}for(let r of e)if(r&&r.length>=8&&(n.add(r),r.includes("="))){let s=r.split("=")[1];s&&s.length>=8&&n.add(s)}return Array.from(n)}static forTesting(e,n){let r=e,s=n?.isV2??!1,i=n?.cookie;try{let o=new URL(e);o.searchParams.has("token")&&(s=!0,r=o.origin)}catch{}return new t(r,void 0,i,s,e)}static async fromBootUrl(e,n,r){let s=gMe(e),i=s.searchParams.has("token"),o;if(i)for(let a=0;a<5;a++){if(r?.aborted)throw new Error("dsh web boot aborted");try{let c=(await fetch(e,{redirect:"manual",signal:r})).headers.get("set-cookie");if(c){o=c.split(";")[0];break}}catch(l){if(r?.aborted)throw l;await new Promise(c=>setTimeout(c,100))}}return new t(s.origin,n,o,i,e)}async ensureCookie(e=!1){return this.tokenUrl?this.cookie&&!e?this.cookie:(this.cookieExchangePromise||(this.cookieExchangePromise=(async()=>{for(let n=0;n<5;n++)try{let s=(await fetch(this.tokenUrl,{redirect:"manual"})).headers.get("set-cookie");if(s)return this.cookie=s.split(";")[0],this.recordSecret(this.cookie),this.cookie}catch{await new Promise(r=>setTimeout(r,100))}return this.cookie})().finally(()=>{this.cookieExchangePromise=void 0})),this.cookieExchangePromise):this.cookie}async rpc(e,n){this.isV2&&await this.ensureCookie();let r=this.cookie,s=r?[r]:[],i=`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=this.isV2?e.includes("/")?e:e.replace(/\./g,"/"):e.includes(".")?e:e.replace(/\//g,"."),a=n;if(this.isV2){let p=n;if(o==="session/prompt"&&p&&typeof p=="object"){let f=p;f.requestId||(p={...f,requestId:fMe()})}p&&typeof p=="object"&&"args"in p?a=p:a={args:{request:p}}}let l={"content-type":"application/json"};this.cookie&&(l.cookie=this.cookie);let c;try{c=await fetch(`${this.baseUrl}/api/${o}`,{method:"POST",headers:l,body:JSON.stringify({type:"client-request",rpcId:i,method:o,payload:a}),redirect:"manual"})}catch(p){throw new Wo(e,`transport error: ${p instanceof Error?p.message:String(p)}`,this.getSecretsToRedact(s))}if(c.status>=300&&c.status<400)throw new Wo(e,`redirects are not permitted (HTTP ${c.status})`,this.getSecretsToRedact(s));if((c.status===401||c.status===403)&&this.isV2&&this.tokenUrl){let p=await this.ensureCookie(!0);if(p&&p!==l.cookie){l.cookie=p,s.push(p);try{c=await fetch(`${this.baseUrl}/api/${o}`,{method:"POST",headers:l,body:JSON.stringify({type:"client-request",rpcId:i,method:o,payload:a}),redirect:"manual"})}catch(f){throw new Wo(e,`transport error: ${f instanceof Error?f.message:String(f)}`,this.getSecretsToRedact(s))}if(c.status>=300&&c.status<400)throw new Wo(e,`redirects are not permitted (HTTP ${c.status})`,this.getSecretsToRedact(s))}}let u;try{u=await c.json()}catch{u=void 0}if(!c.ok)throw new Wo(e,u??c.statusText,this.getSecretsToRedact(s));let d=u&&typeof u=="object"?u.result:void 0;if(!d||typeof d!="object"||typeof d.ok!="boolean")throw new Wo(e,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope",this.getSecretsToRedact(s));if(d.ok===!1)throw new Wo(e,d.error??d,this.getSecretsToRedact(s));return"value"in d?d.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&&uQ(this.child,2e3)}static spawn(e){return new Promise((n,r)=>{let s=pMe("dsh",["web","--no-open","--port","0"],{env:e,stdio:["ignore","pipe","pipe"]}),i=!1,o=!1,a="",l="",c="",u=new AbortController,d=p=>{i||(i=!0,u.abort(),uQ(s,2e3),r(p))};s.stdout?.on("data",p=>{let f=p.toString();if(l+=f,a+=f,i||o)return;let m=a.split(`
|
|
2863
2863
|
`);a=m.pop()??"";for(let g of m){let y=mMe.exec(g);if(y){o=!0,t.fromBootUrl(y[1],s,u.signal).then(h=>{i||(i=!0,n(h))},h=>{d(h instanceof Error?h:new Error(String(h)))});return}}}),s.stderr?.on("data",p=>{c+=p.toString()}),s.on("error",p=>{d(p)}),s.on("exit",(p,f)=>{let m=f?`signal ${f}`:`exit code ${p}`;d(new Error(xd(`dsh web exited before reporting a boot URL (${m})`,c.trim()?Gt(c,{provider:"dsh"}):"")))})})}}});import{randomUUID as N$}from"node:crypto";import{existsSync as pQ,statSync as hMe}from"node:fs";import{readFile as yMe,mkdir as _Me}from"node:fs/promises";function $$(t){return new D$(t)}function P$(t){return{...t,DSH_PERMISSION_MODE:t.DSH_PERMISSION_MODE??"danger-full-access"}}function bMe(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 Wh(t){return t instanceof Error?t.message:String(t)}async function fQ(t,e){let n;try{n=await yMe(t)}catch{return e?.(),[]}e&&um(n).reduce((i,o)=>i+o.length,0)!==n.length&&e?.();let r=vv(n),s=[];for(let i of r.split(`
|
|
2864
|
-
`))if(i.trim())try{let o=JSON.parse(i);o!==null&&typeof o=="object"&&!Array.isArray(o)&&s.push(o)}catch{e?.()}return s}function wMe(t){let n=t.data?.message?.content;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=[];for(let s of n)s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string"&&r.push(s.text);return r.join("")}function hS(t,e){return jp(t,e)}var L$,vMe,M$,D$,j$=P(()=>{"use strict";jb();Cd();ar();cQ();bv();dQ();jn();Ci();L$=new Map,vMe=500,M$=0;D$=class extends gt{dshProvider;usageSeen=new Set;constructor(e){let n=new mS(e);super({provider:n,protocol:{transport:"dsh-rpc",perTurnCancellation:"unsupported",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"dsh has no in-session leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"dsh",seedArgs:[],resumeTemplate:"dsh web --no-open --port 0 # continuity is via the RPC sidecar, not a resume flag",startTemplate:"dsh web --no-open --port 0",transport:(r,s)=>this.dshPromptTurn(r,s)}),this.dshProvider=n}manualSeedHint(e){return{launchCommand:`cd ${e} && dsh web`,postLaunchNote:"dsh has no interactive terminal session to seed into \u2014 continuity lives in the web profile's session store, not a TTY. Boot the sidecar with the command above, open the printed http:// URL, and start a session rooted at this directory in the web UI; lmctl's managed sidecar can then cold-resume it by id (cross-profile session sharing is verified). Send lmctl's seed instruction there, wait for the reply, then find the new session id with the ls command below and register it manually.",lsCommand:`lmctl ls --provider dsh --sessiondir ${e}`}}async seed(e,n){await _Me(e,{recursive:!0});let r=`session-${N$()}`,s=P$(n?.env??process.env);_n("dsh",[],"yolo");try{let i;try{i=await gS(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${Wh(a)}`}}try{await i.rpc("session.create",{sessionId:r,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${Wh(a)}`}}if(n?.model)try{await i.rpc("session.selectModel",{sessionId:r,provider:"deepseek-official",model:n.model})}catch(a){return{success:!1,error:`session.selectModel("${n.model}") failed: ${Wh(a)}`}}let o=n?.prompt??ze;try{n?.signal?.throwIfAborted();try{n?.onDispatch?.()}catch{}let a=await this.promptAndWait(i,e,r,o,M$,n?.signal);return{success:!0,sessionId:r,usage:a.usage}}catch(a){return{success:!1,sessionId:r,usage:a?.usage,error:`seed turn failed: ${Wh(a)}`}}}finally{await Up()}}async dshPromptTurn(e,n){let r=Date.now();if(n.bundleSession!==void 0)return Eo(n.bundleSession,"dsh",n.sessionId,e,{onDelta:n.onDelta,onProgress:n.onProgress,signal:n.signal});let s=P$(n.env??process.env);_n("dsh",[],n.permissionMode??"yolo");let i=!n.sessionId,o=i?`session-${N$()}`:n.sessionId,a;try{let l=await gS(s);i&&await l.rpc("session.create",{sessionId:o,cwd:n.cwd}),n.model&&(await l.rpc("session.selectModel",{sessionId:o,provider:"deepseek-official",model:n.model}),n.onProgress?.({kind:"system",summary:`dsh model set to ${n.model}`})),n.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),a=await this.promptAndWait(l,n.cwd,o,e,n.timeoutMs??M$,n.signal)}finally{await Up()}return n.onProgress?.({kind:"system",summary:"dsh turn completed"}),{...a,sessionId:o,durationMs:Date.now()-r}}async openSession(e){let n=P$(e.env??process.env);_n("dsh",[],e.permissionMode??"yolo");let r=await gS(n),s=!e.sessionId,i=s?`session-${N$()}`:e.sessionId;if(s)try{await r.rpc("session.create",{sessionId:i,cwd:e.cwd})}catch(y){throw await Up(),new Error(`dsh bundle: session.create failed: ${Wh(y)}`)}let o=hS(this.dshProvider.sessionFilePath(e.cwd,i)),a=!1;try{a=pQ(o)&&hMe(o).isFile()}catch{a=!1}let l=a;if(!a&&!s)throw await Up(),new Error(`dsh bundle: session file does not exist for session "${i}" (${o}) \u2014 the session must exist before a bundle can resume it`);e.model&&await r.rpc("session.selectModel",{sessionId:i,provider:"deepseek-official",model:e.model});let c=this,u=0,d=!1,p=null,f=!1,m=!1,g=async()=>{m||(m=!0,await Up())};return{provider:"dsh",sessionId:i,get completedTurns(){return u},async sendTurn(y,h={}){if(d||p!==null)throw new Error("dsh bundle session is closed");if(f)throw new Error("dsh bundle session has a turn still in flight");if(h.signal?.aborted)throw new Error("Aborted");if(o=hS(o),l&&!pQ(o))throw new Error(`dsh bundle: session file for session "${i}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);f=!0;let v=Date.now();try{let _,b=c.promptAndWait(r,e.cwd,i,y,M$,h.signal,x=>{_=x});b.catch(()=>{});let w=()=>{},T=new Promise((x,N)=>{w=()=>{(async()=>{d=!0,await g()})().finally(()=>N(Object.assign(new Error("Aborted"),{usage:_,sessionId:i})))},h.signal?.addEventListener("abort",w,{once:!0})}),k;try{k=await Promise.race([b,T])}finally{h.signal?.removeEventListener("abort",w)}return u+=1,l=!0,{...k,sessionId:i,durationMs:Date.now()-v}}finally{f=!1}},close(){return p!==null||(p=(async()=>{d=!0,await g()})()),p}}}async promptAndWait(e,n,r,s,i,o,a){let l=Date.now(),c=hS(this.dshProvider.sessionFilePath(n,r)),u=!1,d=await fQ(c,()=>{u=!0}),p=d.reduce((v,_)=>typeof _.seq=="number"&&Number.isSafeInteger(_.seq)?Math.max(v,_.seq):v,-1),f=new Nd(r,p,this.usageSeen);u&&f.invalidateOwnership();let m=JSON.stringify([c,r]),g=L$.get(m)??new Set;if(g.size){f.invalidateOwnership();for(let v of g)v.invalidateOwnership()}g.add(f),L$.set(m,g),d.filter(v=>v.type==="turn/start"||v.type==="turn/end").at(-1)?.type==="turn/start"&&f.invalidateOwnership();let h;try{await e.rpc("session.prompt",{sessionId:r,mode:"queue",content:[{type:"text",text:s}]});let v=i>0?Date.now()+i:1/0;for(;;){c=hS(c);let _=await fQ(c),b=_.find(w=>w.type==="turn/end"&&(w.seq??-1)>p);if(_.length&&f.update(_,b?.seq??1/0),a?.(f.usage()),o?.aborted)throw new Error("Aborted");if(b){let w=b.data?.reason;w?.kind!=="completed"&&(h=w?.kind==="aborted"?"cancelled":"error");let T=[..._].reverse().find(N=>N.type==="assistant/message"&&(N.seq??-1)>p&&(N.seq??1/0)<=(b.seq??1/0)),k=T?wMe(T):"";if(w?.kind!=="completed"&&!k)throw new Error(bMe(w));f.finish();let x=f.usage();return{text:k,sessionId:r,durationMs:Date.now()-l,usage:x?{...x,...w?.kind==="completed"?{}:{outcome:w?.kind==="aborted"?"cancelled":"error"}}:void 0}}if(Date.now()>v)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(w=>
|
|
2864
|
+
`))if(i.trim())try{let o=JSON.parse(i);o!==null&&typeof o=="object"&&!Array.isArray(o)&&s.push(o)}catch{e?.()}return s}function wMe(t){let n=t.data?.message?.content;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=[];for(let s of n)s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string"&&r.push(s.text);return r.join("")}function hS(t,e){return jp(t,e)}var L$,vMe,M$,D$,j$=P(()=>{"use strict";jb();Cd();ar();cQ();bv();dQ();jn();Ci();L$=new Map,vMe=500,M$=0;D$=class extends gt{dshProvider;usageSeen=new Set;constructor(e){let n=new mS(e);super({provider:n,protocol:{transport:"dsh-rpc",perTurnCancellation:"unsupported",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"dsh has no in-session leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"dsh",seedArgs:[],resumeTemplate:"dsh web --no-open --port 0 # continuity is via the RPC sidecar, not a resume flag",startTemplate:"dsh web --no-open --port 0",transport:(r,s)=>this.dshPromptTurn(r,s)}),this.dshProvider=n}manualSeedHint(e){return{launchCommand:`cd ${e} && dsh web`,postLaunchNote:"dsh has no interactive terminal session to seed into \u2014 continuity lives in the web profile's session store, not a TTY. Boot the sidecar with the command above, open the printed http:// URL, and start a session rooted at this directory in the web UI; lmctl's managed sidecar can then cold-resume it by id (cross-profile session sharing is verified). Send lmctl's seed instruction there, wait for the reply, then find the new session id with the ls command below and register it manually.",lsCommand:`lmctl ls --provider dsh --sessiondir ${e}`}}async seed(e,n){await _Me(e,{recursive:!0});let r=`session-${N$()}`,s=P$(n?.env??process.env);_n("dsh",[],"yolo");try{let i;try{i=await gS(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${Wh(a)}`}}try{await i.rpc("session.create",{sessionId:r,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${Wh(a)}`}}if(n?.model)try{await i.rpc("session.selectModel",{sessionId:r,provider:"deepseek-official",model:n.model})}catch(a){return{success:!1,error:`session.selectModel("${n.model}") failed: ${Wh(a)}`}}let o=n?.prompt??ze;try{n?.signal?.throwIfAborted();try{n?.onDispatch?.()}catch{}let a=await this.promptAndWait(i,e,r,o,M$,n?.signal);return{success:!0,sessionId:r,usage:a.usage}}catch(a){return{success:!1,sessionId:r,usage:a?.usage,error:`seed turn failed: ${Wh(a)}`}}}finally{await Up()}}async dshPromptTurn(e,n){let r=Date.now();if(n.bundleSession!==void 0)return Eo(n.bundleSession,"dsh",n.sessionId,e,{onDelta:n.onDelta,onProgress:n.onProgress,signal:n.signal});let s=P$(n.env??process.env);_n("dsh",[],n.permissionMode??"yolo");let i=!n.sessionId,o=i?`session-${N$()}`:n.sessionId,a;try{let l=await gS(s);i&&await l.rpc("session.create",{sessionId:o,cwd:n.cwd}),n.model&&(await l.rpc("session.selectModel",{sessionId:o,provider:"deepseek-official",model:n.model}),n.onProgress?.({kind:"system",summary:`dsh model set to ${n.model}`})),n.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),a=await this.promptAndWait(l,n.cwd,o,e,n.timeoutMs??M$,n.signal)}finally{await Up()}return n.onProgress?.({kind:"system",summary:"dsh turn completed"}),{...a,sessionId:o,durationMs:Date.now()-r}}async openSession(e){let n=P$(e.env??process.env);_n("dsh",[],e.permissionMode??"yolo");let r=await gS(n),s=!e.sessionId,i=s?`session-${N$()}`:e.sessionId;if(s)try{await r.rpc("session.create",{sessionId:i,cwd:e.cwd})}catch(y){throw await Up(),new Error(`dsh bundle: session.create failed: ${Wh(y)}`)}let o=hS(this.dshProvider.sessionFilePath(e.cwd,i)),a=!1;try{a=pQ(o)&&hMe(o).isFile()}catch{a=!1}let l=a;if(!a&&!s)throw await Up(),new Error(`dsh bundle: session file does not exist for session "${i}" (${o}) \u2014 the session must exist before a bundle can resume it`);e.model&&await r.rpc("session.selectModel",{sessionId:i,provider:"deepseek-official",model:e.model});let c=this,u=0,d=!1,p=null,f=!1,m=!1,g=async()=>{m||(m=!0,await Up())};return{provider:"dsh",sessionId:i,get completedTurns(){return u},async sendTurn(y,h={}){if(d||p!==null)throw new Error("dsh bundle session is closed");if(f)throw new Error("dsh bundle session has a turn still in flight");if(h.signal?.aborted)throw new Error("Aborted");if(o=hS(o),l&&!pQ(o))throw new Error(`dsh bundle: session file for session "${i}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);f=!0;let v=Date.now();try{let _,b=c.promptAndWait(r,e.cwd,i,y,M$,h.signal,x=>{_=x});b.catch(()=>{});let w=()=>{},T=new Promise((x,N)=>{w=()=>{(async()=>{d=!0,await g()})().finally(()=>{b.then(()=>{},L=>L?.usage).then(L=>N(Object.assign(new Error("Aborted"),{usage:L??_,sessionId:i})))})},h.signal?.addEventListener("abort",w,{once:!0})}),k;try{k=await Promise.race([b,T])}finally{h.signal?.removeEventListener("abort",w)}return u+=1,l=!0,{...k,sessionId:i,durationMs:Date.now()-v}}finally{f=!1}},close(){return p!==null||(p=(async()=>{d=!0,await g()})()),p}}}async promptAndWait(e,n,r,s,i,o,a){let l=Date.now(),c=hS(this.dshProvider.sessionFilePath(n,r)),u=!1,d=await fQ(c,()=>{u=!0}),p=d.reduce((v,_)=>typeof _.seq=="number"&&Number.isSafeInteger(_.seq)?Math.max(v,_.seq):v,-1),f=new Nd(r,p,this.usageSeen);u&&f.invalidateOwnership();let m=JSON.stringify([c,r]),g=L$.get(m)??new Set;if(g.size){f.invalidateOwnership();for(let v of g)v.invalidateOwnership()}g.add(f),L$.set(m,g),d.filter(v=>v.type==="turn/start"||v.type==="turn/end").at(-1)?.type==="turn/start"&&f.invalidateOwnership();let h;try{await e.rpc("session.prompt",{sessionId:r,mode:"queue",content:[{type:"text",text:s}]});let v=i>0?Date.now()+i:1/0;for(;;){c=hS(c);let _=await fQ(c),b=_.find(w=>w.type==="turn/end"&&(w.seq??-1)>p);if(_.length&&f.update(_,b?.seq??1/0),a?.(f.usage()),o?.aborted)throw new Error("Aborted");if(b){let w=b.data?.reason;w?.kind!=="completed"&&(h=w?.kind==="aborted"?"cancelled":"error");let T=[..._].reverse().find(N=>N.type==="assistant/message"&&(N.seq??-1)>p&&(N.seq??1/0)<=(b.seq??1/0)),k=T?wMe(T):"";if(w?.kind!=="completed"&&!k)throw new Error(bMe(w));f.finish();let x=f.usage();return{text:k,sessionId:r,durationMs:Date.now()-l,usage:x?{...x,...w?.kind==="completed"?{}:{outcome:w?.kind==="aborted"?"cancelled":"error"}}:void 0}}if(Date.now()>v)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(w=>{let T=()=>{clearTimeout(k),o?.removeEventListener("abort",T),w()},k=setTimeout(T,vMe);o?.addEventListener("abort",T,{once:!0})})}}catch(v){if(f.finish(),v instanceof Error){let _=f.usage();Object.assign(v,{usage:_?{..._,outcome:h}:void 0,sessionId:r})}throw v}finally{g.delete(f),g.size||L$.delete(m)}}}});import{existsSync as EMe}from"node:fs";import{join as _Q,resolve as TMe}from"node:path";import{createRequire as SMe}from"node:module";function kMe(){return U$===null&&(U$=SMe(import.meta.url)("node:sqlite").DatabaseSync),U$}function F$(t={}){return TMe(t.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||_Q(Ke,".hermes"))}function xMe(t={}){return _Q(F$(t),"state.db")}function qh(t){let e=typeof t=="number"&&Number.isFinite(t)?t:0;return new Date(e*1e3)}function jr(t){return typeof t=="string"&&t.length>0?t:void 0}function IMe(t){if(!t)return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function hQ(t){return jr(t.cwd)??jr(IMe(t.model_config).cwd)??"(unknown)"}function RMe(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function AMe(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t!="string")return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function yQ(t){let e=t.input_tokens??0,n=t.output_tokens??0,r=t.cache_read_tokens??0,s=t.cache_write_tokens??0,i=t.reasoning_tokens??0;return(t.message_count??0)>0&&e+n+r+s+i>0?{totalInputTokens:e,totalCachedInputTokens:r,totalCacheWriteInputTokens:s,totalOutputTokens:n,totalReasoningOutputTokens:i}:{}}var U$,mQ,gQ,yS,vQ=P(()=>{"use strict";nn();vt();U$=null;mQ="acp";gQ=`id, source, model, model_config, started_at,
|
|
2865
2865
|
last_activity_at, message_count, input_tokens, output_tokens,
|
|
2866
2866
|
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;yS=class{name="hermes";dbPath;busyTimeoutMs;discoverLimit;constructor(e){this.dbPath=xMe(e),this.busyTimeoutMs=e?.busyTimeoutMs??5e3,this.discoverLimit=e?.discoverLimit??-1}get stateDbPath(){return this.dbPath}openDb(){if(!EMe(this.dbPath))return null;let e=null;try{return e=new(kMe())(this.dbPath,{open:!0,readOnly:!0}),e.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),e}catch(n){return e?.close(),ie({event:"hermes_store_unavailable",provider:this.name,db_path:this.dbPath,error_message:n instanceof Error?n.message:String(n)}),null}}selectSessionRow(e,n){return e.prepare(`SELECT ${gQ} FROM sessions WHERE id = ? AND source = ?`).get(n,mQ)??null}async discoverSessions(){let e=this.openDb();if(!e)return[];try{let n=e.prepare(`SELECT ${gQ} FROM sessions
|
|
2867
2867
|
WHERE source = ?
|
package/dist/dsl.js
CHANGED
|
@@ -2312,7 +2312,7 @@ ${A}`:C.message,R,S,u),{usage:M.usage.usage(),sessionId:a}))}for(let A of y.spli
|
|
|
2312
2312
|
`):"":""}function S9(t){return t.model||t.message?.model}function kLe(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:x9(t).filter(n=>!n.thought&&n.type!=="thinking"&&typeof n.text=="string"&&n.text.length>0).length}function Ih(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 xLe(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return Ih(e.output??e.error??t)}return Ih(t)}function x9(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function k9(t,e,n){let r=t.name||"tool";return{role:"tool_use",timestamp:e,content:r,toolName:r,toolInput:Ih(t.args,!0),toolInputData:us(t.args),toolCallId:t.id,model:n}}var RT,I9=P(()=>{"use strict";nn();RT=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||vl(Ke,".qwen")}async discoverSessions(){let e=vl(this.baseDir,"projects"),n;try{n=await IT(e)}catch{return[]}let r=[];for(let s of n){let i=vl(e,s,"chats"),o;try{o=await IT(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=vl(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 tn(e),i="(unknown)",o,a,l,c,u=0;for await(let d of Lt(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)),w9(d)){let p=T9(d).trim();p&&(l||(l=ye(p,80)),c=ye(p,80),u++)}if(E9(d)){let p=S9(d);p&&(o=p),u+=kLe(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=b9(n,".jsonl");return this.loadFromFile(n,r)}async loadFromFile(e,n){let r=await tn(e),s="(unknown)",i,o,a,l,c,u,d=[],p=ELe();for await(let f of Lt(e)){if(TLe(p,f.usageMetadata),f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.gitBranch&&(a=f.gitBranch)),f.type==="system"&&f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.model&&(i=f.model),f.gitBranch&&(a=f.gitBranch)),!f.message)continue;let m=f.message,g=f.timestamp?new Date(f.timestamp):r.modifiedAt;if(f.type==="tool_result"){let y=x9(f).filter(h=>h.functionResponse!==void 0);y.length===0&&f.toolCallResult?.callId&&d.push({role:"tool_result",timestamp:g,content:Ih(f.toolCallResult.resultDisplay??f.toolCallResult.error??f.toolCallResult.status)??"tool result",toolCallId:f.toolCallResult.callId});for(let h of y){let v=h.functionResponse,_=xLe(v.response),b=Ih(f.toolCallResult?.resultDisplay);d.push({role:"tool_result",timestamp:g,content:b??_??f.toolCallResult?.status??"tool result",toolName:v.name,toolCallId:f.toolCallResult?.callId??v.id,..._!==void 0?{toolDetailedContent:_}:{}})}}else if(w9(f)){let y=T9(f);y.trim()&&(c||(c=ye(y.trim(),80)),u=ye(y.trim(),80)),d.push({role:"user",timestamp:g,content:y})}else if(E9(f)){let y=S9(f);if(y&&(i=y),Array.isArray(m.content))for(let h of m.content)h.type==="text"&&h.text?d.push({role:"assistant",timestamp:g,content:h.text,model:y}):h.type==="thinking"&&h.thinking?d.push({role:"thinking",timestamp:g,content:h.thinking}):h.functionCall&&d.push(k9(h.functionCall,g,y));else if(typeof m.content=="string")d.push({role:"assistant",timestamp:g,content:m.content,model:y});else if(Array.isArray(m.parts))for(let h of m.parts)if(h.thought||h.type==="thinking"){let v=h.thinking||h.text;v&&d.push({role:"thinking",timestamp:g,content:v})}else h.functionCall?d.push(k9(h.functionCall,g,y)):h.text&&d.push({role:"assistant",timestamp:g,content:h.text,model:y})}}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(f=>f.role==="user"||f.role==="assistant").length,filePath:e,...SLe(p),messages:d}}async resolveSessionPath(e){let n=vl(this.baseDir,"projects");try{let r=await IT(n),s=[];for(let i of r){let o=vl(n,i,"chats",`${e}.jsonl`);try{return await bLe(o,{flag:"r"}),o}catch{continue}}for(let i of r){let o=vl(n,i,"chats"),a;try{a=await IT(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;b9(l,".jsonl").startsWith(e)&&s.push(vl(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 wLe(n),!0}catch{return!1}}}});function TD(t){return new ED(t)}var ED,SD=P(()=>{"use strict";I9();or();_l();jn();ED=class extends gt{constructor(e){super({provider:new RT(e),protocol:{transport:"stream-json",perTurnCancellation:"process",persistentCancellation:"session",persistentResume:!0},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",ze,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:hT})}openSession(e){return yT({...e,binary:"qwen"})}seedArgsFor(e){let n=super.seedArgsFor(e);return e?.model?[...n,"--model",e.model]:n}}});import{readdir as R9,readFile as A9,rm as C9,stat as kD}from"node:fs/promises";import{basename as xD,dirname as O9,join as ri}from"node:path";import{fileURLToPath as ILe}from"node:url";async function RLe(t){let e=await Promise.all(t.map(n=>tn(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 ALe(t,e){if(!t)return e;let n=new Date(t);return Number.isNaN(n.getTime())?e:n}function N9(t){return t.type==="USER_INPUT"}function L9(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function CLe(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function M9(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function P9(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 OLe(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function NLe(t){for await(let e of Lt(t)){let n=e.tool_calls?.map(s=>s.args)??[];for(let s of n){let i=LLe(s);if(i)return i}let r=MLe(e.content);if(r)return r}return null}function LLe(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 MLe(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function PLe(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 DLe(t,e){let n=new Set;for(let r of e){let s=$Le(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 $Le(t,e,n){let r=n.message.backgroundTaskId===void 0?void 0:BLe(n.event.content);if(r!==void 0)return D9(t.filter(i=>!e.has(i)&&HLe(i)===r),n.event.step_index);let s=FLe(n.event);if(s!==void 0)return D9(t.filter(i=>!e.has(i)&&jLe(i.name,n.event.type)&&$9(ULe(i))===s),n.event.step_index)}function D9(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 jLe(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 ULe(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function FLe(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]),$9(e)}function $9(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return ILe(e)}catch{return}}function BLe(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function HLe(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 ID(t){if(t.endsWith(".db"))return xD(t,".db");let e="/brain/",n=t.indexOf(e);return n===-1?null:t.slice(n+e.length).split("/")[0]||null}async function j9(t){if(t.endsWith(".jsonl"))return t;let e=ID(t);if(!e||!t.endsWith(".db"))return null;let n=O9(O9(t));for(let r of["transcript_full.jsonl","transcript.jsonl"]){let s=ri(n,"brain",e,".system_generated","logs",r);try{return await kD(s),s}catch{}}return null}var AT,RD=P(()=>{"use strict";nn();AT=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||ri(Ke,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:ri(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=ri(this.baseDir,"conversations"),n;try{n=await R9(e)}catch{return[]}let r=[];for(let s of n){if(!s.endsWith(".db"))continue;let i=xD(s,".db");try{let o=await this.extractSummary(i);o&&r.push(o)}catch{}}return r}conversationPath(e){return ri(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,n){return ri(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 kD(n),n}catch{}return null}async extractSummary(e){let n=this.conversationPath(e),r=await this.existingTranscriptPath(e),s=r??n,i=await RLe([n,r].filter(Boolean)),o=await this.resolveCwd(e,r),a,l,c,u=0;if(r)for await(let d of Lt(r)){let p=P9(d.content);if(p&&(a=p),N9(d)){let f=M9(d.content).trim();f&&(l||(l=ye(f,80)),c=ye(f,80)),u++}else L9(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=ID(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 p of Lt(i)){let f=ALe(p.created_at,s.modifiedAt),m=P9(p.content);if(m&&(a=m),N9(p)){let g=M9(p.content),y=g.trim();y&&(l||(l=ye(y,80)),c=ye(y,80)),o.push({role:"user",timestamp:f,content:g});continue}if(Array.isArray(p.tool_calls))for(let g of p.tool_calls){let y=g.name||"tool",h=OLe(g.args),v=us(g.args),_={role:"tool_use",timestamp:f,content:h,toolName:y,toolInput:h,toolInputData:v};o.push(_),u.push({name:y,stepIndex:p.step_index,input:v,message:_})}if(L9(p)&&p.content)o.push({role:"assistant",timestamp:f,content:p.content,model:a});else if(CLe(p)&&p.content){let g=PLe(p,r),y=g===void 0?null:await this.readTaskLog(r,g),h={role:"tool_result",timestamp:y?.modifiedAt??f,content:p.content,toolName:p.type?.toLowerCase(),backgroundTaskId:g,...y===null?{}:{toolDetailedContent:y.content}};o.push(h),d.push({event:p,message:h})}p.thinking&&o.push({role:"thinking",timestamp:f,content:p.thinking})}return DLe(u,d),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(p=>p.role==="user"||p.role==="assistant").length,messages:o}}async resolveSessionPath(e){let n=this.conversationPath(e);try{return await kD(n),n}catch{}let r=ri(this.baseDir,"conversations");try{let s=[];for(let i of await R9(r)){if(!i.endsWith(".db"))continue;xD(i,".db").startsWith(e)&&s.push(ri(r,i))}if(s.length===1)return s[0]}catch{}return null}async resolveTailTranscriptPath(e){let n=await this.resolveSessionPath(e);return n?j9(n):null}async deleteSession(e){let n=await this.resolveSessionPath(e);if(!n)return!1;let r=ID(n);return r?(await C9(this.conversationPath(r),{force:!0}),await C9(ri(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 NLe(n);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let n=ri(this.baseDir,"cache","last_conversations.json");try{let r=JSON.parse(await A9(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=ri(this.baseDir,"brain",e,".system_generated","tasks",`${n}.log`);try{let[s,i]=await Promise.all([A9(r,"utf8"),tn(r)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as WLe}from"node:child_process";import{StringDecoder as U9}from"node:string_decoder";function CT(t){return async(e,n)=>{let r=Date.now(),s=t.buildArgs(e,n);t.assertArgs?.(s,n),n.onProgress?.({kind:"system",summary:`${t.label} -p one-shot started (no streaming events)`});let{stdout:i}=await qLe(t.label,n.binary,s,{cwd:n.cwd,env:cn(n.env,n.cwd,n.sessionId),signal:n.signal});return n.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:n.sessionId,durationMs:Date.now()-r}}}function qLe(t,e,n,r){return new Promise((s,i)=>{if(r.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=WLe(e,n,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(p){i(p);return}let a="",l="",c=new U9("utf8"),u=new U9("utf8");o.stdout?.on("data",p=>{a+=c.write(p)}),o.stderr?.on("data",p=>{l+=u.write(p)});let d=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",p=>{r.signal?.removeEventListener("abort",d),i(p)}),o.on("close",(p,f)=>{if(r.signal?.removeEventListener("abort",d),a+=c.end(),l+=u.end(),p===0){s({stdout:a,stderr:l});return}let m=f?`signal ${f}`:`exit code ${p}`,g=l.trim()||a.trim();i(new Error(bd(`${t} failed (${m})`,g?Gt(g,{provider:t}):"")))}),r.signal?.aborted?d():r.signal?.addEventListener("abort",d,{once:!0})})}var AD=P(()=>{"use strict";Xs();zs()});import{basename as zLe}from"node:path";import{randomUUID as XLe}from"node:crypto";function OD(t){return new CD(t)}function VLe(t){return t!==void 0&&t<=0||t===void 0?"0":`${Math.max(1,Math.ceil(t/1e3))}s`}var CD,GLe,ND=P(()=>{"use strict";RD();or();jn();xi();AD();CD=class extends gt{constructor(e){super({provider:new AT(e),protocol:{transport:"print",perTurnCancellation:"process"},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",ze,"--dangerously-skip-permissions","--print-timeout","0"],resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:GLe})}async sendTurn(e,n){if(n.requireResume){let s=await this.resolvePath(n.sessionId);if(s===null||zLe(s)!==`${n.sessionId}.db`)throw new Error(`agy cannot resume missing conversation "${n.sessionId}"`)}let r=await super.sendTurn(e,n);return n.permissionMode==="plan"?{...r,warnings:[...r.warnings??[],"agy does not enforce plan mode; this turn used full permissions"]}:r}seedArgsFor(e){let n=[...super.seedArgsFor(e)];return e?.model&&n.push("--model",e.model),n}async seed(e,n){let r=XLe(),s=`[lmctl-seed:${r}]`,i=await super.seed(e,{...n,prompt:Qv({flightToken:r,prompt:n?.prompt})});if(!i.success&&(i.errorCode==="ENOENT"||i.errorCode==="ABORT_ERR"))return i;let o=(await this.provider.discoverSessions()).filter(a=>a.firstUserMessage?.startsWith(s));if(i.success&&o.length===1)return{...i,sessionId:o[0].sessionId};for(let a of o)await this.provider.deleteSession(a.sessionId);return{...i,success:!1,error:i.error??`agy seed created ${o.length} identifiable sessions; expected one`}}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}`}}},GLe=CT({label:"agy",buildArgs:(t,e)=>{let n=[...e.sessionId?["--conversation",e.sessionId]:[],"-p",t,"--dangerously-skip-permissions","--print-timeout",VLe(e.timeoutMs)];return e.model&&n.push("--model",e.model),n},assertArgs:(t,e)=>gn("agy",t,e.permissionMode??"yolo")})});import{existsSync as Rh,readdirSync as JLe,statSync as F9}from"node:fs";import{readdir as LD,rm as KLe}from"node:fs/promises";import B9,{join as $i}from"node:path";function ZLe(t){if(t.length===0)throw new Error("cannot encode an empty project path");let e="",n=!1;for(let s=0;s<t.length;s++){let i=t.charCodeAt(s),o=String.fromCharCode(i);o==="/"||o==="\\"||o===":"?(n||(e+="-"),n=!0):o!=="~"&&/^[A-Za-z0-9._-]$/.test(o)?(e+=o,n=!1):(e+="~"+i.toString(16).toUpperCase().padStart(4,"0"),n=!1)}return`--${(e.replace(/^-+/,"")||"root").slice(0,251)}--`}function YLe(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function Np(t,e){let n=e??(process.platform==="win32"?B9.win32:B9.posix),r=t,s="session.jsonl.zstd";if((t.endsWith(".jsonl.zstd")||t.endsWith(".jsonl"))&&(r=n.dirname(t),s=n.basename(t)),!Rh(r))return t.endsWith(".jsonl.zstd")||t.endsWith(".jsonl")?t:n.join(t,s);try{let i=JLe(r),o=[];for(let a of i){let l=/^session(?:\.v(\d+))?\.jsonl\.zstd$/.exec(a);if(l){let c=l[1]?parseInt(l[1],10):0;if(Number.isSafeInteger(c))try{let u=n.join(r,a);F9(u).isFile()&&o.push({name:a,version:c})}catch{}}}if(o.length>0)return o.sort((a,l)=>l.version-a.version),n.join(r,o[0].name)}catch{}try{if(Rh(t)&&F9(t).isFile())return t}catch{}return n.join(r,s)}function MD(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 QLe(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 H9(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:MD(i.content)})}else if(n.type==="assistant/message"){let i=r.message;for(let o of QLe(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:MD(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:MD(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function e0e(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 W9(t,e,n){let r=t.find(f=>f.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 f of t)if(f.type==="request/header"){let m=f.data?.header;m?.config?.model&&(a=m.config.model)}let l=t.map(f=>f.time).filter(f=>typeof f=="number"),c=s.createdAt??i?.createdAt,u=c?new Date(c):new Date(0),d=l.length>0?new Date(Math.max(...l)):u,p=n.filter(f=>f.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:u,modifiedAt:d,model:a,firstUserMessage:p[0]?.content,lastUserMessage:p.at(-1)?.content,messageCount:n.filter(f=>f.role==="user"||f.role==="assistant").length,filePath:e,...t0e(t)}}function t0e(t){let e=new Map;for(let o of t){let a=o.data?.turn??null,l=e.get(a)??[];l.push(o),e.set(a,l)}let n=[],r=[];for(let o of e.values()){let a=new xd("",-1,new Set);a.update(o);let l=a.usage();l&&(n.push(l),r.push(a.lastUsage()))}if(!n.length)return{};let s=o=>{if(n.some(l=>l.invalidCounters||l[o]===null))return;let a=n.reduce((l,c)=>l+c[o],0);return Number.isSafeInteger(a)?a:void 0},i=r.at(-1);return{totalInputTokens:s("inputUncached"),totalCachedInputTokens:s("cacheRead"),totalOutputTokens:s("output"),totalReasoningOutputTokens:s("reasoning"),lastInputTokens:i.inputUncached!==null&&i.cacheRead!==null?i.inputUncached+i.cacheRead:void 0,lastTokenUsage:{totalTokens:i.inputUncached!==null&&i.cacheRead!==null&&i.output!==null?i.inputUncached+i.cacheRead+i.output:void 0,inputTokens:i.inputUncached??void 0,cachedInputTokens:i.cacheRead??void 0,outputTokens:i.output??void 0,reasoningOutputTokens:i.reasoning??void 0}}}var OT,q9=P(()=>{"use strict";tb();nn();$_();OT=class{name="dsh";sessionsDir;constructor(e={}){let n=e.dshHome||process.env.DSH_HOME||$i(Ke,".dsh");this.sessionsDir=$i(n,"sessions")}async discoverSessions(){let e=[],n;try{n=await LD(this.sessionsDir)}catch{return[]}for(let r of n){let s;try{s=await LD($i(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=H9(r),i=W9(r,n.filePath,s);return i?{...i,turnStatus:e0e(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 KLe($i(this.sessionsDir,n.cwdDir,n.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,n){let r=ZLe(e),s=YLe(e),i=r,o=$i(this.sessionsDir,r,n),a=$i(this.sessionsDir,s,n);!Rh(o)&&Rh(a)&&(i=s);let l=$i(this.sessionsDir,i,n);return Np(l)}async findSessionDir(e){let n;try{n=await LD(this.sessionsDir)}catch{return null}for(let r of n){let s=e,i=$i(this.sessionsDir,r,s);try{let o=Np(i);if(Rh(o))return{cwdDir:r,sessionDir:s,filePath:o}}catch{}}return null}async readRecords(e,n){let{readFile:r}=await import("node:fs/promises"),s=$i(this.sessionsDir,e,n),i=Np(s),o=await r(i),a=D_(o),l=[];for(let c of a.split(`
|
|
2313
2313
|
`))if(c.trim())try{let u=JSON.parse(c);if(u.type?.endsWith("-chunks")||u.type==="assistant/chunk"&&u.data?.chunk?.type!=="usage")continue;l.push(u)}catch{}return l}async readSummary(e,n){let r=$i(this.sessionsDir,e,n),s=Np(r),i=await this.readRecords(e,n);return i.length===0?null:W9(i,s,H9(i))}}});import{spawn as n0e}from"node:child_process";import{randomUUID as r0e}from"node:crypto";function PD(t,e=[]){if(t==null)return t;if(typeof t=="string"){let n=t;for(let r of e)r&&typeof r=="string"&&r.length>=8&&n.includes(r)&&(n=n.replaceAll(r,"[REDACTED]"));return n=n.replace(/(?:sk-|dsh-)[A-Za-z0-9_\-\.]+/gi,"[REDACTED]"),n=n.replace(/(?:token=)[A-Za-z0-9_\-\.]+/gi,"token=[REDACTED]"),n=n.replace(/bearer\s+[A-Za-z0-9_\-\.]+/gi,"Bearer [REDACTED]"),n}if(Array.isArray(t))return t.map(n=>PD(n,e));if(typeof t=="object"){let n={};for(let[r,s]of Object.entries(t))/api[_-]?key|secret|token|password|auth|authorization|credential|cookie/i.test(r)?n[r]="[REDACTED]":n[r]=PD(s,e);return n}return t}function i0e(t){let e;try{e=new URL(t)}catch{throw new Error("invalid dsh boot URL: malformed URL")}if(e.protocol!=="http:")throw new Error(`invalid dsh boot URL scheme "${e.protocol}": must be http:`);if(e.username||e.password)throw new Error("invalid dsh boot URL: userinfo credentials are not allowed");let n=e.hostname;if(!(n==="127.0.0.1"||n==="localhost"||n==="::1"||n==="[::1]"))throw new Error(`invalid dsh boot URL host "${n}": loopback host (127.0.0.1 or localhost) required`);return e}function z9(t,e=2e3){if(!t||t.exitCode!==null||t.signalCode!==null)return;try{t.kill("SIGTERM")}catch{}let n,r=()=>{n!==void 0&&(clearTimeout(n),n=void 0)};if(t.once("exit",r),t.exitCode!==null||t.signalCode!==null){r();return}n=setTimeout(()=>{n=void 0;try{t.exitCode===null&&t.signalCode===null&&t.kill("SIGKILL")}catch{}},e),n.unref()}async function NT(t,e=n=>DD.spawn(n)){if(bl){let n=await bl.catch(()=>{});if(n?.alive)return n;bl=void 0}return bl=e(t),bl}async function Lp(){if(!bl)return;(await bl.catch(()=>{}))?.shutdown(),bl=void 0}var s0e,Ho,DD,bl,X9=P(()=>{"use strict";zs();s0e=/dsh web:\s*(https?:\/\/\S+)/;Ho=class t extends Error{method;detail;constructor(e,n,r=[]){let s=PD(n,r),i=typeof s=="string"?s:JSON.stringify(s);super(`dsh RPC ${e} failed: ${i}`),this.name="DshRpcCallError",this.method=e,this.detail=s,Object.setPrototypeOf(this,t.prototype)}};DD=class t{constructor(e,n,r,s=!1,i){this.baseUrl=e;this.child=n;this.cookie=r;this.isV2=s;this.tokenUrl=i;if(this.cookie&&this.recordSecret(this.cookie),this.tokenUrl){this.recordSecret(this.tokenUrl);try{let a=new URL(this.tokenUrl).searchParams.get("token");a&&this.recordSecret(a)}catch{}}}static MAX_RETAINED_SECRETS=8;cookieExchangePromise;knownSecrets=[];recordSecret(e){if(!e||typeof e!="string"||e.length<8)return;let n=r=>{if(r.length<8)return;let s=this.knownSecrets.indexOf(r);for(s!==-1&&this.knownSecrets.splice(s,1),this.knownSecrets.push(r);this.knownSecrets.length>t.MAX_RETAINED_SECRETS;)this.knownSecrets.shift()};if(n(e),e.includes("=")){let r=e.split("=")[1];r&&r.length>=8&&n(r)}}getSecretsToRedact(e=[]){let n=new Set;for(let r of this.knownSecrets)r&&r.length>=8&&n.add(r);if(this.cookie&&this.cookie.length>=8){n.add(this.cookie);let r=this.cookie.split("=")[1];r&&r.length>=8&&n.add(r)}if(this.tokenUrl)try{let s=new URL(this.tokenUrl).searchParams.get("token");s&&s.length>=8&&n.add(s)}catch{}for(let r of e)if(r&&r.length>=8&&(n.add(r),r.includes("="))){let s=r.split("=")[1];s&&s.length>=8&&n.add(s)}return Array.from(n)}static forTesting(e,n){let r=e,s=n?.isV2??!1,i=n?.cookie;try{let o=new URL(e);o.searchParams.has("token")&&(s=!0,r=o.origin)}catch{}return new t(r,void 0,i,s,e)}static async fromBootUrl(e,n,r){let s=i0e(e),i=s.searchParams.has("token"),o;if(i)for(let a=0;a<5;a++){if(r?.aborted)throw new Error("dsh web boot aborted");try{let c=(await fetch(e,{redirect:"manual",signal:r})).headers.get("set-cookie");if(c){o=c.split(";")[0];break}}catch(l){if(r?.aborted)throw l;await new Promise(c=>setTimeout(c,100))}}return new t(s.origin,n,o,i,e)}async ensureCookie(e=!1){return this.tokenUrl?this.cookie&&!e?this.cookie:(this.cookieExchangePromise||(this.cookieExchangePromise=(async()=>{for(let n=0;n<5;n++)try{let s=(await fetch(this.tokenUrl,{redirect:"manual"})).headers.get("set-cookie");if(s)return this.cookie=s.split(";")[0],this.recordSecret(this.cookie),this.cookie}catch{await new Promise(r=>setTimeout(r,100))}return this.cookie})().finally(()=>{this.cookieExchangePromise=void 0})),this.cookieExchangePromise):this.cookie}async rpc(e,n){this.isV2&&await this.ensureCookie();let r=this.cookie,s=r?[r]:[],i=`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=this.isV2?e.includes("/")?e:e.replace(/\./g,"/"):e.includes(".")?e:e.replace(/\//g,"."),a=n;if(this.isV2){let p=n;if(o==="session/prompt"&&p&&typeof p=="object"){let f=p;f.requestId||(p={...f,requestId:r0e()})}p&&typeof p=="object"&&"args"in p?a=p:a={args:{request:p}}}let l={"content-type":"application/json"};this.cookie&&(l.cookie=this.cookie);let c;try{c=await fetch(`${this.baseUrl}/api/${o}`,{method:"POST",headers:l,body:JSON.stringify({type:"client-request",rpcId:i,method:o,payload:a}),redirect:"manual"})}catch(p){throw new Ho(e,`transport error: ${p instanceof Error?p.message:String(p)}`,this.getSecretsToRedact(s))}if(c.status>=300&&c.status<400)throw new Ho(e,`redirects are not permitted (HTTP ${c.status})`,this.getSecretsToRedact(s));if((c.status===401||c.status===403)&&this.isV2&&this.tokenUrl){let p=await this.ensureCookie(!0);if(p&&p!==l.cookie){l.cookie=p,s.push(p);try{c=await fetch(`${this.baseUrl}/api/${o}`,{method:"POST",headers:l,body:JSON.stringify({type:"client-request",rpcId:i,method:o,payload:a}),redirect:"manual"})}catch(f){throw new Ho(e,`transport error: ${f instanceof Error?f.message:String(f)}`,this.getSecretsToRedact(s))}if(c.status>=300&&c.status<400)throw new Ho(e,`redirects are not permitted (HTTP ${c.status})`,this.getSecretsToRedact(s))}}let u;try{u=await c.json()}catch{u=void 0}if(!c.ok)throw new Ho(e,u??c.statusText,this.getSecretsToRedact(s));let d=u&&typeof u=="object"?u.result:void 0;if(!d||typeof d!="object"||typeof d.ok!="boolean")throw new Ho(e,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope",this.getSecretsToRedact(s));if(d.ok===!1)throw new Ho(e,d.error??d,this.getSecretsToRedact(s));return"value"in d?d.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&&z9(this.child,2e3)}static spawn(e){return new Promise((n,r)=>{let s=n0e("dsh",["web","--no-open","--port","0"],{env:e,stdio:["ignore","pipe","pipe"]}),i=!1,o=!1,a="",l="",c="",u=new AbortController,d=p=>{i||(i=!0,u.abort(),z9(s,2e3),r(p))};s.stdout?.on("data",p=>{let f=p.toString();if(l+=f,a+=f,i||o)return;let m=a.split(`
|
|
2314
2314
|
`);a=m.pop()??"";for(let g of m){let y=s0e.exec(g);if(y){o=!0,t.fromBootUrl(y[1],s,u.signal).then(h=>{i||(i=!0,n(h))},h=>{d(h instanceof Error?h:new Error(String(h)))});return}}}),s.stderr?.on("data",p=>{c+=p.toString()}),s.on("error",p=>{d(p)}),s.on("exit",(p,f)=>{let m=f?`signal ${f}`:`exit code ${p}`;d(new Error(bd(`dsh web exited before reporting a boot URL (${m})`,c.trim()?Gt(c,{provider:"dsh"}):"")))})})}}});import{randomUUID as $D}from"node:crypto";import{existsSync as G9,statSync as o0e}from"node:fs";import{readFile as a0e,mkdir as l0e}from"node:fs/promises";function HD(t){return new BD(t)}function FD(t){return{...t,DSH_PERMISSION_MODE:t.DSH_PERMISSION_MODE??"danger-full-access"}}function u0e(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 Ah(t){return t instanceof Error?t.message:String(t)}async function V9(t,e){let n;try{n=await a0e(t)}catch{return e?.(),[]}e&&Kf(n).reduce((i,o)=>i+o.length,0)!==n.length&&e?.();let r=D_(n),s=[];for(let i of r.split(`
|
|
2315
|
-
`))if(i.trim())try{let o=JSON.parse(i);o!==null&&typeof o=="object"&&!Array.isArray(o)&&s.push(o)}catch{e?.()}return s}function d0e(t){let n=t.data?.message?.content;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=[];for(let s of n)s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string"&&r.push(s.text);return r.join("")}function LT(t,e){return Np(t,e)}var jD,c0e,UD,BD,WD=P(()=>{"use strict";tb();Sd();or();q9();$_();X9();jn();xi();jD=new Map,c0e=500,UD=0;BD=class extends gt{dshProvider;usageSeen=new Set;constructor(e){let n=new OT(e);super({provider:n,protocol:{transport:"dsh-rpc",perTurnCancellation:"unsupported",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"dsh has no in-session leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"dsh",seedArgs:[],resumeTemplate:"dsh web --no-open --port 0 # continuity is via the RPC sidecar, not a resume flag",startTemplate:"dsh web --no-open --port 0",transport:(r,s)=>this.dshPromptTurn(r,s)}),this.dshProvider=n}manualSeedHint(e){return{launchCommand:`cd ${e} && dsh web`,postLaunchNote:"dsh has no interactive terminal session to seed into \u2014 continuity lives in the web profile's session store, not a TTY. Boot the sidecar with the command above, open the printed http:// URL, and start a session rooted at this directory in the web UI; lmctl's managed sidecar can then cold-resume it by id (cross-profile session sharing is verified). Send lmctl's seed instruction there, wait for the reply, then find the new session id with the ls command below and register it manually.",lsCommand:`lmctl ls --provider dsh --sessiondir ${e}`}}async seed(e,n){await l0e(e,{recursive:!0});let r=`session-${$D()}`,s=FD(n?.env??process.env);gn("dsh",[],"yolo");try{let i;try{i=await NT(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${Ah(a)}`}}try{await i.rpc("session.create",{sessionId:r,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${Ah(a)}`}}if(n?.model)try{await i.rpc("session.selectModel",{sessionId:r,provider:"deepseek-official",model:n.model})}catch(a){return{success:!1,error:`session.selectModel("${n.model}") failed: ${Ah(a)}`}}let o=n?.prompt??ze;try{n?.signal?.throwIfAborted();try{n?.onDispatch?.()}catch{}let a=await this.promptAndWait(i,e,r,o,UD,n?.signal);return{success:!0,sessionId:r,usage:a.usage}}catch(a){return{success:!1,sessionId:r,usage:a?.usage,error:`seed turn failed: ${Ah(a)}`}}}finally{await Lp()}}async dshPromptTurn(e,n){let r=Date.now();if(n.bundleSession!==void 0)return wo(n.bundleSession,"dsh",n.sessionId,e,{onDelta:n.onDelta,onProgress:n.onProgress,signal:n.signal});let s=FD(n.env??process.env);gn("dsh",[],n.permissionMode??"yolo");let i=!n.sessionId,o=i?`session-${$D()}`:n.sessionId,a;try{let l=await NT(s);i&&await l.rpc("session.create",{sessionId:o,cwd:n.cwd}),n.model&&(await l.rpc("session.selectModel",{sessionId:o,provider:"deepseek-official",model:n.model}),n.onProgress?.({kind:"system",summary:`dsh model set to ${n.model}`})),n.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),a=await this.promptAndWait(l,n.cwd,o,e,n.timeoutMs??UD,n.signal)}finally{await Lp()}return n.onProgress?.({kind:"system",summary:"dsh turn completed"}),{...a,sessionId:o,durationMs:Date.now()-r}}async openSession(e){let n=FD(e.env??process.env);gn("dsh",[],e.permissionMode??"yolo");let r=await NT(n),s=!e.sessionId,i=s?`session-${$D()}`:e.sessionId;if(s)try{await r.rpc("session.create",{sessionId:i,cwd:e.cwd})}catch(y){throw await Lp(),new Error(`dsh bundle: session.create failed: ${Ah(y)}`)}let o=LT(this.dshProvider.sessionFilePath(e.cwd,i)),a=!1;try{a=G9(o)&&o0e(o).isFile()}catch{a=!1}let l=a;if(!a&&!s)throw await Lp(),new Error(`dsh bundle: session file does not exist for session "${i}" (${o}) \u2014 the session must exist before a bundle can resume it`);e.model&&await r.rpc("session.selectModel",{sessionId:i,provider:"deepseek-official",model:e.model});let c=this,u=0,d=!1,p=null,f=!1,m=!1,g=async()=>{m||(m=!0,await Lp())};return{provider:"dsh",sessionId:i,get completedTurns(){return u},async sendTurn(y,h={}){if(d||p!==null)throw new Error("dsh bundle session is closed");if(f)throw new Error("dsh bundle session has a turn still in flight");if(h.signal?.aborted)throw new Error("Aborted");if(o=LT(o),l&&!G9(o))throw new Error(`dsh bundle: session file for session "${i}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);f=!0;let v=Date.now();try{let _,b=c.promptAndWait(r,e.cwd,i,y,UD,h.signal,x=>{_=x});b.catch(()=>{});let w=()=>{},T=new Promise((x,N)=>{w=()=>{(async()=>{d=!0,await g()})().finally(()=>N(Object.assign(new Error("Aborted"),{usage:_,sessionId:i})))},h.signal?.addEventListener("abort",w,{once:!0})}),k;try{k=await Promise.race([b,T])}finally{h.signal?.removeEventListener("abort",w)}return u+=1,l=!0,{...k,sessionId:i,durationMs:Date.now()-v}}finally{f=!1}},close(){return p!==null||(p=(async()=>{d=!0,await g()})()),p}}}async promptAndWait(e,n,r,s,i,o,a){let l=Date.now(),c=LT(this.dshProvider.sessionFilePath(n,r)),u=!1,d=await V9(c,()=>{u=!0}),p=d.reduce((v,_)=>typeof _.seq=="number"&&Number.isSafeInteger(_.seq)?Math.max(v,_.seq):v,-1),f=new xd(r,p,this.usageSeen);u&&f.invalidateOwnership();let m=JSON.stringify([c,r]),g=jD.get(m)??new Set;if(g.size){f.invalidateOwnership();for(let v of g)v.invalidateOwnership()}g.add(f),jD.set(m,g),d.filter(v=>v.type==="turn/start"||v.type==="turn/end").at(-1)?.type==="turn/start"&&f.invalidateOwnership();let h;try{await e.rpc("session.prompt",{sessionId:r,mode:"queue",content:[{type:"text",text:s}]});let v=i>0?Date.now()+i:1/0;for(;;){c=LT(c);let _=await V9(c),b=_.find(w=>w.type==="turn/end"&&(w.seq??-1)>p);if(_.length&&f.update(_,b?.seq??1/0),a?.(f.usage()),o?.aborted)throw new Error("Aborted");if(b){let w=b.data?.reason;w?.kind!=="completed"&&(h=w?.kind==="aborted"?"cancelled":"error");let T=[..._].reverse().find(N=>N.type==="assistant/message"&&(N.seq??-1)>p&&(N.seq??1/0)<=(b.seq??1/0)),k=T?d0e(T):"";if(w?.kind!=="completed"&&!k)throw new Error(u0e(w));f.finish();let x=f.usage();return{text:k,sessionId:r,durationMs:Date.now()-l,usage:x?{...x,...w?.kind==="completed"?{}:{outcome:w?.kind==="aborted"?"cancelled":"error"}}:void 0}}if(Date.now()>v)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(w=>
|
|
2315
|
+
`))if(i.trim())try{let o=JSON.parse(i);o!==null&&typeof o=="object"&&!Array.isArray(o)&&s.push(o)}catch{e?.()}return s}function d0e(t){let n=t.data?.message?.content;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=[];for(let s of n)s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string"&&r.push(s.text);return r.join("")}function LT(t,e){return Np(t,e)}var jD,c0e,UD,BD,WD=P(()=>{"use strict";tb();Sd();or();q9();$_();X9();jn();xi();jD=new Map,c0e=500,UD=0;BD=class extends gt{dshProvider;usageSeen=new Set;constructor(e){let n=new OT(e);super({provider:n,protocol:{transport:"dsh-rpc",perTurnCancellation:"unsupported",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"dsh has no in-session leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"dsh",seedArgs:[],resumeTemplate:"dsh web --no-open --port 0 # continuity is via the RPC sidecar, not a resume flag",startTemplate:"dsh web --no-open --port 0",transport:(r,s)=>this.dshPromptTurn(r,s)}),this.dshProvider=n}manualSeedHint(e){return{launchCommand:`cd ${e} && dsh web`,postLaunchNote:"dsh has no interactive terminal session to seed into \u2014 continuity lives in the web profile's session store, not a TTY. Boot the sidecar with the command above, open the printed http:// URL, and start a session rooted at this directory in the web UI; lmctl's managed sidecar can then cold-resume it by id (cross-profile session sharing is verified). Send lmctl's seed instruction there, wait for the reply, then find the new session id with the ls command below and register it manually.",lsCommand:`lmctl ls --provider dsh --sessiondir ${e}`}}async seed(e,n){await l0e(e,{recursive:!0});let r=`session-${$D()}`,s=FD(n?.env??process.env);gn("dsh",[],"yolo");try{let i;try{i=await NT(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${Ah(a)}`}}try{await i.rpc("session.create",{sessionId:r,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${Ah(a)}`}}if(n?.model)try{await i.rpc("session.selectModel",{sessionId:r,provider:"deepseek-official",model:n.model})}catch(a){return{success:!1,error:`session.selectModel("${n.model}") failed: ${Ah(a)}`}}let o=n?.prompt??ze;try{n?.signal?.throwIfAborted();try{n?.onDispatch?.()}catch{}let a=await this.promptAndWait(i,e,r,o,UD,n?.signal);return{success:!0,sessionId:r,usage:a.usage}}catch(a){return{success:!1,sessionId:r,usage:a?.usage,error:`seed turn failed: ${Ah(a)}`}}}finally{await Lp()}}async dshPromptTurn(e,n){let r=Date.now();if(n.bundleSession!==void 0)return wo(n.bundleSession,"dsh",n.sessionId,e,{onDelta:n.onDelta,onProgress:n.onProgress,signal:n.signal});let s=FD(n.env??process.env);gn("dsh",[],n.permissionMode??"yolo");let i=!n.sessionId,o=i?`session-${$D()}`:n.sessionId,a;try{let l=await NT(s);i&&await l.rpc("session.create",{sessionId:o,cwd:n.cwd}),n.model&&(await l.rpc("session.selectModel",{sessionId:o,provider:"deepseek-official",model:n.model}),n.onProgress?.({kind:"system",summary:`dsh model set to ${n.model}`})),n.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),a=await this.promptAndWait(l,n.cwd,o,e,n.timeoutMs??UD,n.signal)}finally{await Lp()}return n.onProgress?.({kind:"system",summary:"dsh turn completed"}),{...a,sessionId:o,durationMs:Date.now()-r}}async openSession(e){let n=FD(e.env??process.env);gn("dsh",[],e.permissionMode??"yolo");let r=await NT(n),s=!e.sessionId,i=s?`session-${$D()}`:e.sessionId;if(s)try{await r.rpc("session.create",{sessionId:i,cwd:e.cwd})}catch(y){throw await Lp(),new Error(`dsh bundle: session.create failed: ${Ah(y)}`)}let o=LT(this.dshProvider.sessionFilePath(e.cwd,i)),a=!1;try{a=G9(o)&&o0e(o).isFile()}catch{a=!1}let l=a;if(!a&&!s)throw await Lp(),new Error(`dsh bundle: session file does not exist for session "${i}" (${o}) \u2014 the session must exist before a bundle can resume it`);e.model&&await r.rpc("session.selectModel",{sessionId:i,provider:"deepseek-official",model:e.model});let c=this,u=0,d=!1,p=null,f=!1,m=!1,g=async()=>{m||(m=!0,await Lp())};return{provider:"dsh",sessionId:i,get completedTurns(){return u},async sendTurn(y,h={}){if(d||p!==null)throw new Error("dsh bundle session is closed");if(f)throw new Error("dsh bundle session has a turn still in flight");if(h.signal?.aborted)throw new Error("Aborted");if(o=LT(o),l&&!G9(o))throw new Error(`dsh bundle: session file for session "${i}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);f=!0;let v=Date.now();try{let _,b=c.promptAndWait(r,e.cwd,i,y,UD,h.signal,x=>{_=x});b.catch(()=>{});let w=()=>{},T=new Promise((x,N)=>{w=()=>{(async()=>{d=!0,await g()})().finally(()=>{b.then(()=>{},L=>L?.usage).then(L=>N(Object.assign(new Error("Aborted"),{usage:L??_,sessionId:i})))})},h.signal?.addEventListener("abort",w,{once:!0})}),k;try{k=await Promise.race([b,T])}finally{h.signal?.removeEventListener("abort",w)}return u+=1,l=!0,{...k,sessionId:i,durationMs:Date.now()-v}}finally{f=!1}},close(){return p!==null||(p=(async()=>{d=!0,await g()})()),p}}}async promptAndWait(e,n,r,s,i,o,a){let l=Date.now(),c=LT(this.dshProvider.sessionFilePath(n,r)),u=!1,d=await V9(c,()=>{u=!0}),p=d.reduce((v,_)=>typeof _.seq=="number"&&Number.isSafeInteger(_.seq)?Math.max(v,_.seq):v,-1),f=new xd(r,p,this.usageSeen);u&&f.invalidateOwnership();let m=JSON.stringify([c,r]),g=jD.get(m)??new Set;if(g.size){f.invalidateOwnership();for(let v of g)v.invalidateOwnership()}g.add(f),jD.set(m,g),d.filter(v=>v.type==="turn/start"||v.type==="turn/end").at(-1)?.type==="turn/start"&&f.invalidateOwnership();let h;try{await e.rpc("session.prompt",{sessionId:r,mode:"queue",content:[{type:"text",text:s}]});let v=i>0?Date.now()+i:1/0;for(;;){c=LT(c);let _=await V9(c),b=_.find(w=>w.type==="turn/end"&&(w.seq??-1)>p);if(_.length&&f.update(_,b?.seq??1/0),a?.(f.usage()),o?.aborted)throw new Error("Aborted");if(b){let w=b.data?.reason;w?.kind!=="completed"&&(h=w?.kind==="aborted"?"cancelled":"error");let T=[..._].reverse().find(N=>N.type==="assistant/message"&&(N.seq??-1)>p&&(N.seq??1/0)<=(b.seq??1/0)),k=T?d0e(T):"";if(w?.kind!=="completed"&&!k)throw new Error(u0e(w));f.finish();let x=f.usage();return{text:k,sessionId:r,durationMs:Date.now()-l,usage:x?{...x,...w?.kind==="completed"?{}:{outcome:w?.kind==="aborted"?"cancelled":"error"}}:void 0}}if(Date.now()>v)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(w=>{let T=()=>{clearTimeout(k),o?.removeEventListener("abort",T),w()},k=setTimeout(T,c0e);o?.addEventListener("abort",T,{once:!0})})}}catch(v){if(f.finish(),v instanceof Error){let _=f.usage();Object.assign(v,{usage:_?{..._,outcome:h}:void 0,sessionId:r})}throw v}finally{g.delete(f),g.size||jD.delete(m)}}}});import{existsSync as p0e}from"node:fs";import{join as Q9,resolve as f0e}from"node:path";import{createRequire as m0e}from"node:module";function g0e(){return qD===null&&(qD=m0e(import.meta.url)("node:sqlite").DatabaseSync),qD}function zD(t={}){return f0e(t.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||Q9(Ke,".hermes"))}function h0e(t={}){return Q9(zD(t),"state.db")}function Ch(t){let e=typeof t=="number"&&Number.isFinite(t)?t:0;return new Date(e*1e3)}function Dr(t){return typeof t=="string"&&t.length>0?t:void 0}function y0e(t){if(!t)return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Z9(t){return Dr(t.cwd)??Dr(y0e(t.model_config).cwd)??"(unknown)"}function _0e(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function v0e(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t!="string")return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Y9(t){let e=t.input_tokens??0,n=t.output_tokens??0,r=t.cache_read_tokens??0,s=t.cache_write_tokens??0,i=t.reasoning_tokens??0;return(t.message_count??0)>0&&e+n+r+s+i>0?{totalInputTokens:e,totalCachedInputTokens:r,totalCacheWriteInputTokens:s,totalOutputTokens:n,totalReasoningOutputTokens:i}:{}}var qD,J9,K9,MT,e7=P(()=>{"use strict";nn();vt();qD=null;J9="acp";K9=`id, source, model, model_config, started_at,
|
|
2316
2316
|
last_activity_at, message_count, input_tokens, output_tokens,
|
|
2317
2317
|
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;MT=class{name="hermes";dbPath;busyTimeoutMs;discoverLimit;constructor(e){this.dbPath=h0e(e),this.busyTimeoutMs=e?.busyTimeoutMs??5e3,this.discoverLimit=e?.discoverLimit??-1}get stateDbPath(){return this.dbPath}openDb(){if(!p0e(this.dbPath))return null;let e=null;try{return e=new(g0e())(this.dbPath,{open:!0,readOnly:!0}),e.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),e}catch(n){return e?.close(),ie({event:"hermes_store_unavailable",provider:this.name,db_path:this.dbPath,error_message:n instanceof Error?n.message:String(n)}),null}}selectSessionRow(e,n){return e.prepare(`SELECT ${K9} FROM sessions WHERE id = ? AND source = ?`).get(n,J9)??null}async discoverSessions(){let e=this.openDb();if(!e)return[];try{let n=e.prepare(`SELECT ${K9} FROM sessions
|
|
2318
2318
|
WHERE source = ?
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lmctl-ai/lmctl",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.472",
|
|
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",
|