@phnx-labs/sessions-cli 0.1.0 → 0.1.1
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/CHANGELOG.md +5 -0
- package/dist/index.js +84 -34
- package/package.json +4 -3
- package/dist/commands/sessions.d.ts +0 -6
- package/dist/commands/sessions.js +0 -69
- package/dist/index.d.ts +0 -2
- package/dist/lib/paths.d.ts +0 -7
- package/dist/lib/paths.js +0 -16
- package/dist/lib/query.d.ts +0 -47
- package/dist/lib/query.js +0 -156
- package/dist/lib/version.d.ts +0 -1
- package/dist/lib/version.js +0 -18
- package/dist/protocol-server.d.ts +0 -4
- package/dist/protocol-server.js +0 -69
- package/dist/protocol.d.ts +0 -23
- package/dist/protocol.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.1
|
|
4
|
+
|
|
5
|
+
- npm ships one minified `dist/index.js` (bundle + mangle). TypeScript stays in git.
|
|
6
|
+
- `scripts/release.sh x.y.z` / `x.y.z-pre.n` is the only ship path. CI on `release/…` runs that script.
|
|
7
|
+
|
|
3
8
|
## 0.1.0
|
|
4
9
|
|
|
5
10
|
- First release. Local FTS search, list, and id lookup against `sessions.db`.
|
package/dist/index.js
CHANGED
|
@@ -1,35 +1,85 @@
|
|
|
1
1
|
#!/usr/bin/env -S node --no-warnings=ExperimentalWarning
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
2
|
+
var Ut=Object.defineProperty;var g=(r,t,e)=>()=>{if(e)throw e[0];try{return r&&(t=r(r=0)),t}catch(i){throw e=[i],i}};var ct=(r,t)=>{for(var e in t)Ut(r,e,{get:t[e],enumerable:!0})};import*as P from"fs";import*as S from"path";import{fileURLToPath as Yt}from"url";function Jt(r){let t=r;for(let e=0;e<6;e++){let i=S.join(t,"package.json");if(P.existsSync(i))return i;let n=S.dirname(t);if(n===t)break;t=n}return S.join(r,"..","package.json")}function H(r=Kt){if($)return $;try{let t=JSON.parse(P.readFileSync(r,"utf-8"));$=String(t.version||"")||"unknown"}catch{$="unknown"}return $}var Kt,$,Y=g(()=>{"use strict";Kt=Jt(S.dirname(Yt(import.meta.url))),$=null});var pt=g(()=>{"use strict"});import*as J from"os";import*as mt from"path";function Qt(r=J.homedir()){return mt.join(r,".agents",".history","sessions","sessions.db")}function K(r=process.env,t=J.homedir()){let e=r.SESSIONS_DB?.trim()||r.AGENTS_SESSIONS_DB?.trim();return e||Qt(t)}var dt=g(()=>{"use strict"});import*as F from"fs";import{DatabaseSync as zt}from"node:sqlite";function Xt(r){let t=r.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>=2);return t.length===0?{expr:"",terms:[]}:{expr:t.map(e=>`${e}*`).join(" OR "),terms:t}}function Zt(r=K()){return new zt(r,{readOnly:!0})}function z(r){return{id:String(r.id),shortId:String(r.shortId??""),agent:String(r.agent??""),version:r.version??null,account:r.account??null,timestamp:String(r.timestamp??""),lastActivity:r.lastActivity??null,project:r.project??null,cwd:r.cwd??null,gitBranch:r.gitBranch??null,topic:r.topic??null,label:r.label??null,messageCount:typeof r.messageCount=="number"?r.messageCount:null,tokenCount:typeof r.tokenCount=="number"?r.tokenCount:null,filePath:String(r.filePath??""),origin:r.origin??null,machine:r.machine??null,model:r.model??null,harness:r.harness??null,ticketId:r.ticketId??null,prUrl:r.prUrl??null,durationMs:typeof r.durationMs=="number"?r.durationMs:null,costUsd:typeof r.costUsd=="number"?r.costUsd:null}}function M(r={}){let t=r.dbPath??K(),e=Math.max(1,Math.min(r.limit??20,500));if(!F.existsSync(t)||F.statSync(t).size===0)return[];let i=Zt(t);try{if(r.idPrefix&&ft(r.idPrefix)&&!r.query){let a=i.prepare(`SELECT ${Q} FROM sessions s
|
|
3
|
+
WHERE (s.id = ? OR s.id LIKE ? OR s.short_id = ?)
|
|
4
|
+
AND s.archived_at IS NULL
|
|
5
|
+
LIMIT ?`),h=r.idPrefix;return a.all(h,`${h}%`,h,e).map(z)}if(r.query&&r.query.trim()){let{expr:a}=Xt(r.query);if(!a)return[];let h=i.prepare(`SELECT ${Q}
|
|
6
|
+
FROM sessions s
|
|
7
|
+
JOIN session_text t ON t.session_id = s.id
|
|
8
|
+
WHERE session_text MATCH ?
|
|
9
|
+
AND s.archived_at IS NULL
|
|
10
|
+
${r.agent?"AND s.agent = ?":""}
|
|
11
|
+
ORDER BY rank
|
|
12
|
+
LIMIT ?`),c=r.agent?[a,r.agent,e]:[a,e];return h.all(...c).map(z)}let n=i.prepare(`SELECT ${Q} FROM sessions s
|
|
13
|
+
WHERE s.archived_at IS NULL
|
|
14
|
+
${r.agent?"AND s.agent = ?":""}
|
|
15
|
+
ORDER BY s.last_activity DESC, s.timestamp DESC
|
|
16
|
+
LIMIT ?`),s=r.agent?[r.agent,e]:[e];return n.all(...s).map(z)}finally{i.close()}}function ft(r){return/^[0-9a-f]{8,}$/i.test(r)||/^[0-9a-f-]{8,}$/i.test(r)}function gt(r){let t={},e=[];for(let i=0;i<r.length;i++){let n=r[i];if(!(n==="--json"||n==="--local"||n==="--no-interactive")){if(n==="--limit"&&r[i+1]){t.limit=Number(r[++i]);continue}if(n.startsWith("--limit=")){t.limit=Number(n.slice(8));continue}if(n==="--agent"&&r[i+1]){t.agent=r[++i];continue}n.startsWith("--")||e.push(n)}}return e.length===1&&ft(e[0])&&!e[0].includes(" ")?t.idPrefix=e[0]:e.length>0&&(t.query=e.join(" ")),t}var Q,X=g(()=>{"use strict";dt();Q=`
|
|
17
|
+
s.id,
|
|
18
|
+
s.short_id AS shortId,
|
|
19
|
+
s.agent,
|
|
20
|
+
s.version,
|
|
21
|
+
s.account,
|
|
22
|
+
s.timestamp,
|
|
23
|
+
s.last_activity AS lastActivity,
|
|
24
|
+
s.project,
|
|
25
|
+
s.cwd,
|
|
26
|
+
s.git_branch AS gitBranch,
|
|
27
|
+
s.topic,
|
|
28
|
+
s.label,
|
|
29
|
+
s.message_count AS messageCount,
|
|
30
|
+
s.token_count AS tokenCount,
|
|
31
|
+
s.file_path AS filePath,
|
|
32
|
+
s.origin,
|
|
33
|
+
s.machine,
|
|
34
|
+
s.model,
|
|
35
|
+
s.harness,
|
|
36
|
+
s.ticket_id AS ticketId,
|
|
37
|
+
s.pr_url AS prUrl,
|
|
38
|
+
s.duration_ms AS durationMs,
|
|
39
|
+
s.cost_usd AS costUsd
|
|
40
|
+
`});var bt={};ct(bt,{MAX_REQUEST_BYTES:()=>_t,readFd:()=>Ot,runProtocolServer:()=>te});import*as D from"fs";function Ot(r,t=_t){let e=[],i=0;for(;;){let n=Buffer.alloc(65536),s=D.readSync(r,n,0,n.length,null);if(s===0)break;if(i+=s,i>t)throw new Error(`request exceeds ${t} bytes`);e.push(n.subarray(0,s))}return Buffer.concat(e)}function te(){let r;try{r=Ot(3)}catch(e){process.stderr.write(`sessions __serve: failed to read fd 3: ${e instanceof Error?e.message:String(e)}
|
|
41
|
+
`),process.exit(1);return}let t;try{t=JSON.parse(r.toString("utf8"))}catch{tt({v:1,id:"",ok:!1,error:{code:"INVALID_RESPONSE",message:"request is not JSON"}});return}try{let e=M({query:t.op==="get"?void 0:t.args?.query,idPrefix:(t.op==="get",t.args?.idPrefix),limit:t.args?.limit,agent:t.args?.agent});tt({v:1,id:t.id,ok:!0,result:e})}catch(e){tt({v:1,id:t.id,ok:!1,error:{code:"OPERATION_FAILED",message:e instanceof Error?e.message:String(e)}})}}function tt(r){let t=Buffer.from(JSON.stringify(r),"utf8");D.writeSync(4,t)}var _t,Ct=g(()=>{"use strict";pt();X();_t=1024*1024});var C,A,k=g(()=>{C=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0}},A=class extends C{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}});function G(r){let t=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+t+">":"["+t+"]"}var R,j=g(()=>{k();R=class{constructor(t,e){switch(this.description=e||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new A(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}});import{stripVTControlCharacters as ee}from"node:util";var N,et=g(()=>{j();N=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let e=t.commands.filter(n=>!n._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((n,s)=>n.name().localeCompare(s.name())),e}compareOptions(t,e){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(n=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);!n&&!s?e.push(i):i.long&&!s?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description))}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);e.push(...n)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||""}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>G(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,e,i){return e.length===0?[]:[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[])}),e.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]),n.get(o).push(s)}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function s(u,p){return e.formatItem(u,i,p,e)}let o=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(o=o.concat([e.boxWrap(e.styleCommandDescription(a),n),""]));let h=e.visibleArguments(t).map(u=>s(e.styleArgumentTerm(e.argumentTerm(u)),e.styleArgumentDescription(e.argumentDescription(u))));if(o=o.concat(this.formatItemList("Arguments:",h,e)),this.groupItems(t.options,e.visibleOptions(t),u=>u.helpGroupHeading??"Options:").forEach((u,p)=>{let x=u.map(y=>s(e.styleOptionTerm(e.optionTerm(y)),e.styleOptionDescription(e.optionDescription(y))));o=o.concat(this.formatItemList(p,x,e))}),e.showGlobalOptions){let u=e.visibleGlobalOptions(t).map(p=>s(e.styleOptionTerm(e.optionTerm(p)),e.styleOptionDescription(e.optionDescription(p))));o=o.concat(this.formatItemList("Global Options:",u,e))}return this.groupItems(t.commands,e.visibleCommands(t),u=>u.helpGroup()||"Commands:").forEach((u,p)=>{let x=u.map(y=>s(e.styleSubcommandTerm(e.subcommandTerm(y)),e.styleSubcommandDescription(e.subcommandDescription(y))));o=o.concat(this.formatItemList(p,x,e))}),o.join(`
|
|
42
|
+
`)}displayWidth(t){return ee(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e==="[command]"?this.styleSubcommandText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleCommandText(e)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleSubcommandText(e)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,e,i,n){let o=" ".repeat(2);if(!i)return o+t;let a=t.padEnd(e+t.length-n.displayWidth(t)),h=2,l=(this.helpWidth??80)-e-h-2,u;return l<this.minWidthToWrap||n.preformatted(i)?u=i:u=n.boxWrap(i,l).replace(/\n/g,`
|
|
43
|
+
`+" ".repeat(e+h)),o+a+" ".repeat(h)+u.replace(/\n/g,`
|
|
44
|
+
${o}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,s=[];return i.forEach(o=>{let a=o.match(n);if(a===null){s.push("");return}let h=[a.shift()],c=this.displayWidth(h[0]);a.forEach(l=>{let u=this.displayWidth(l);if(c+u<=e){h.push(l),c+=u;return}s.push(h.join(""));let p=l.trimStart();h=[p],c=this.displayWidth(p)}),s.push(h.join(""))}),s.join(`
|
|
45
|
+
`)}}});function yt(r){return r.split("-").reduce((t,e)=>t+e[0].toUpperCase()+e.slice(1))}function ie(r){let t,e,i=/^-[^-]$/,n=/^--[^-]/,s=r.split(/[ |,]+/).concat("guard");if(i.test(s[0])&&(t=s.shift()),n.test(s[0])&&(e=s.shift()),!t&&i.test(s[0])&&(t=s.shift()),!t&&n.test(s[0])&&(t=e,e=s.shift()),s[0].startsWith("-")){let o=s[0],a=`option creation failed due to '${o}' in option flags '${r}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
|
|
46
|
+
- a short flag is a single dash and a single character
|
|
47
|
+
- either use a single dash and a single character (for a short flag)
|
|
48
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(o)?new Error(`${a}
|
|
49
|
+
- too many short flags`):n.test(o)?new Error(`${a}
|
|
50
|
+
- too many long flags`):new Error(`${a}
|
|
51
|
+
- unrecognised flag format`)}if(t===void 0&&e===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:t,longFlag:e}}var E,W,it=g(()=>{k();E=class{constructor(t,e){this.flags=t,this.description=e||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let i=ie(t);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let e=t;return typeof t=="string"&&(e={[t]:!0}),this.implied=Object.assign(this.implied||{},e),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new A(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?yt(this.name().replace(/^no-/,"")):yt(this.name())}helpGroup(t){return this.helpGroupHeading=t,this}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},W=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(t,e){let i=e.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,s=n!==void 0?n:!1;return e.negate===(s===t)}}});function ne(r,t){if(Math.abs(r.length-t.length)>3)return Math.max(r.length,t.length);let e=[];for(let i=0;i<=r.length;i++)e[i]=[i];for(let i=0;i<=t.length;i++)e[0][i]=i;for(let i=1;i<=t.length;i++)for(let n=1;n<=r.length;n++){let s;r[n-1]===t[i-1]?s=0:s=1,e[n][i]=Math.min(e[n-1][i]+1,e[n][i-1]+1,e[n-1][i-1]+s),n>1&&i>1&&r[n-1]===t[i-2]&&r[n-2]===t[i-1]&&(e[n][i]=Math.min(e[n][i],e[n-2][i-2]+1))}return e[r.length][t.length]}function nt(r,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let e=r.startsWith("--");e&&(r=r.slice(2),t=t.map(o=>o.slice(2)));let i=[],n=3,s=.4;return t.forEach(o=>{if(o.length<=1)return;let a=ne(r,o),h=Math.max(r.length,o.length);(h-a)/h>s&&(a<n?(n=a,i=[o]):a===n&&i.push(o))}),i.sort((o,a)=>o.localeCompare(a)),e&&(i=i.map(o=>`--${o}`)),i.length>1?`
|
|
52
|
+
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
53
|
+
(Did you mean ${i[0]}?)`:""}var At=g(()=>{});import{EventEmitter as se}from"node:events";import st from"node:child_process";import b from"node:path";import L from"node:fs";import m from"node:process";import{stripVTControlCharacters as re}from"node:util";function xt(r){return r.map(t=>{if(!t.startsWith("--inspect"))return t;let e,i="127.0.0.1",n="9229",s;return(s=t.match(/^(--inspect(-brk)?)$/))!==null?e=s[1]:(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=s[1],/^\d+$/.test(s[3])?n=s[3]:i=s[3]):(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=s[1],i=s[3],n=s[4]),e&&n!=="0"?`${e}=${i}:${parseInt(n)+1}`:t})}function St(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return!1;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return!0}var v,Et=g(()=>{j();k();et();it();At();v=class r extends se{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>m.stdout.write(e),writeErr:e=>m.stderr.write(e),outputError:(e,i)=>i(e),getOutHelpWidth:()=>m.stdout.isTTY?m.stdout.columns:void 0,getErrHelpWidth:()=>m.stderr.isTTY?m.stderr.columns:void 0,getOutHasColors:()=>St()??(m.stdout.isTTY&&m.stdout.hasColors?.()),getErrHasColors:()=>St()??(m.stderr.isTTY&&m.stderr.hasColors?.()),stripColor:e=>re(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,i){let n=e,s=i;typeof n=="object"&&n!==null&&(s=n,n=null),s=s||{};let[,o,a]=t.match(/([^ ]+) *(.*)/),h=this.createCommand(o);return n&&(h.description(n),h._executableHandler=!0),s.isDefault&&(this._defaultCommandName=h._name),h._hidden=!!(s.noHelp||s.hidden),h._executableFile=s.executableFile||null,a&&h.arguments(a),this._registerCommand(h),h.parent=this,h.copyInheritedSettings(this),n?this:h}createCommand(t){return new r(t)}createHelp(){return Object.assign(new N,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...t},this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
54
|
+
- specify the name in Command constructor or using .name()`);return e=e||{},e.isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new R(t,e)}argument(t,e,i,n){let s=this.createArgument(t,e);return typeof i=="function"?s.default(n).argParser(i):s.default(i),this.addArgument(s),this}arguments(t){return t.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(t){let e=this.registeredArguments.slice(-1)[0];if(e?.variadic)throw new Error(`only the last argument can be variadic '${e.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,t&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let i=t??"help [command]",[,n,s]=i.match(/([^ ]+) *(.*)/),o=e??"display help for command",a=this.createCommand(n);return a.helpOption(!1),s&&a.arguments(s),o&&a.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=a,(t||e)&&this._initCommandGroup(a),this}addHelpCommand(t,e){return typeof t!="object"?(this.helpCommand(t,e),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this._initCommandGroup(t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,e){let i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
|
|
55
|
+
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=e=>{if(e.code!=="commander.executeSubCommandAsync")throw e},this}_exit(t,e,i){this._exitCallback&&this._exitCallback(new C(t,e,i)),m.exit(t)}action(t){let e=i=>{let n=this.registeredArguments.length,s=i.slice(0,n);return this._storeOptionsAsProperties?s[n]=this:s[n]=this.opts(),s.push(this),t.apply(this,s)};return this._actionHandler=e,this}createOption(t,e){return new E(t,e)}_callParseArg(t,e,i,n){try{return t.parseArg(e,i)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${n} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(t){let e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){let i=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
56
|
+
- already used by option '${e.flags}'`)}this._initOptionGroup(t),this.options.push(t)}_registerCommand(t){let e=n=>[n.name()].concat(n.aliases()),i=e(t).find(n=>this._findCommand(n));if(i){let n=e(this._findCommand(i)).join("|"),s=e(t).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this._initCommandGroup(t),this.commands.push(t)}addOption(t){this._registerOption(t);let e=t.name(),i=t.attributeName();t.defaultValue!==void 0&&this.setOptionValueWithSource(i,t.defaultValue,"default");let n=(s,o,a)=>{s==null&&t.presetArg!==void 0&&(s=t.presetArg);let h=this.getOptionValue(i);s!==null&&t.parseArg?s=this._callParseArg(t,s,h,o):s!==null&&t.variadic&&(s=t._collectValue(s,h)),s==null&&(t.negate?s=!1:t.isBoolean()||t.optional?s=!0:s=""),this.setOptionValueWithSource(i,s,a)};return this.on("option:"+e,s=>{let o=`error: option '${t.flags}' argument '${s}' is invalid.`;n(s,o,"cli")}),t.envVar&&this.on("optionEnv:"+e,s=>{let o=`error: option '${t.flags}' value '${s}' from env '${t.envVar}' is invalid.`;n(s,o,"env")}),this}_optionEx(t,e,i,n,s){if(typeof e=="object"&&e instanceof E)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(e,i);if(o.makeOptionMandatory(!!t.mandatory),typeof n=="function")o.default(s).argParser(n);else if(n instanceof RegExp){let a=n;n=(h,c)=>{let l=a.exec(h);return l?l[0]:c},o.default(s).argParser(n)}else o.default(n);return this.addOption(o)}option(t,e,i,n){return this._optionEx({},t,e,i,n)}requiredOption(t,e,i,n){return this._optionEx({mandatory:!0},t,e,i,n)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,i){return this._storeOptionsAsProperties?this[t]=e:this._optionValues[t]=e,this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(t)!==void 0&&(e=i.getOptionValueSource(t))}),e}_prepareUserArgs(t,e){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(e=e||{},t===void 0&&e.from===void 0){m.versions?.electron&&(e.from="electron");let n=m.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(e.from="eval")}t===void 0&&(t=m.argv),this.rawArgs=t.slice();let i;switch(e.from){case void 0:case"node":this._scriptPath=t[1],i=t.slice(2);break;case"electron":m.defaultApp?(this._scriptPath=t[1],i=t.slice(2)):i=t.slice(1);break;case"user":i=t.slice(0);break;case"eval":i=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return this._parseCommand([],i),this}async parseAsync(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?(this.options.filter(t=>t.negate&&t.defaultValue===void 0&&this.getOptionValue(t.attributeName())===void 0).forEach(t=>{let e=t.long.replace(/^--no-/,"--");this._findOption(e)||this.setOptionValueWithSource(t.attributeName(),!0,"default")}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
57
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,e,i){if(L.existsSync(t))return;let n=e?`searched for local subcommand relative to directory '${e}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${t}' does not exist
|
|
58
|
+
- if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
59
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
60
|
+
- ${n}`;throw new Error(s)}_executeSubCommand(t,e){e=e.slice();let i=[".js",".ts",".tsx",".mjs",".cjs"];function n(l,u){let p=b.resolve(l,u);if(L.existsSync(p))return p;if(i.includes(b.extname(u)))return;let x=i.find(y=>L.existsSync(`${p}${y}`));if(x)return`${p}${x}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=t._executableFile||`${this._name}-${t._name}`,o=this._executableDir||"";if(this._scriptPath){let l;try{l=L.realpathSync(this._scriptPath)}catch{l=this._scriptPath}o=b.resolve(b.dirname(l),o)}if(o){let l=n(o,s);if(!l&&!t._executableFile&&this._scriptPath){let u=b.basename(this._scriptPath,b.extname(this._scriptPath));u!==this._name&&(l=n(o,`${u}-${t._name}`))}s=l||s}let a=i.includes(b.extname(s)),h;m.platform!=="win32"?a?(e.unshift(s),e=xt(m.execArgv).concat(e),h=st.spawn(m.argv[0],e,{stdio:"inherit"})):h=st.spawn(s,e,{stdio:"inherit"}):(this._checkForMissingExecutable(s,o,t._name),e.unshift(s),e=xt(m.execArgv).concat(e),h=st.spawn(m.execPath,e,{stdio:"inherit"})),h.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{m.on(u,()=>{h.killed===!1&&h.exitCode===null&&h.kill(u)})});let c=this._exitCallback;h.on("close",l=>{l=l??1,c?c(new C(l,"commander.executeSubCommandAsync","(close)")):m.exit(l)}),h.on("error",l=>{if(l.code==="ENOENT")this._checkForMissingExecutable(s,o,t._name);else if(l.code==="EACCES")throw new Error(`'${s}' not executable`);if(!c)m.exit(1);else{let u=new C(1,"commander.executeSubCommandAsync","(error)");u.nestedError=l,c(u)}}),this.runningCommand=h}_dispatchSubcommand(t,e,i){let n=this._findCommand(t);n||this.help({error:!0}),n._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,n,"preSubcommand"),s=this._chainOrCall(s,()=>{if(n._executableHandler)this._executeSubCommand(n,e.concat(i));else return n._parseCommand(e,i)}),s}_dispatchHelpCommand(t){t||this.help();let e=this._findCommand(t);return e&&!e._executableHandler&&e.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,e)=>{t.required&&this.args[e]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(i,n,s)=>{let o=n;if(n!==null&&i.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,n,s,a)}return o};this._checkNumberOfArguments();let e=[];this.registeredArguments.forEach((i,n)=>{let s=i.defaultValue;i.variadic?n<this.args.length?(s=this.args.slice(n),i.parseArg&&(s=s.reduce((o,a)=>t(i,a,o),i.defaultValue))):s===void 0&&(s=[]):n<this.args.length&&(s=this.args[n],i.parseArg&&(s=t(i,s,i.defaultValue))),e[n]=s}),this.processedArgs=e}_chainOrCall(t,e){return t?.then&&typeof t.then=="function"?t.then(()=>e()):e()}_chainOrCallHooks(t,e){let i=t,n=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[e]!==void 0).forEach(s=>{s._lifeCycleHooks[e].forEach(o=>{n.push({hookedCommand:s,callback:o})})}),e==="postAction"&&n.reverse(),n.forEach(s=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this))}),i}_chainOrCallSubCommandHook(t,e,i){let n=t;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(s=>{n=this._chainOrCall(n,()=>s(this,e))}),n}_parseCommand(t,e){let i=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),e=i.unknown,this.args=t.concat(e),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),e);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(s,t,e)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent?.listenerCount(s))n(),this._processArguments(),this.parent.emit(s,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);this.listenerCount("command:*")?this.emit("command:*",t,e):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(e=>e._name===t||e._aliases.includes(t))}_findOption(t){return this.options.find(e=>e.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(e=>{e.mandatory&&t.getOptionValue(e.attributeName())===void 0&&t.missingMandatoryOptionValue(e)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});t.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=t.find(s=>i.conflictsWith.includes(s.attributeName()));n&&this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let e=[],i=[],n=e;function s(l){return l.length>1&&l[0]==="-"}let o=l=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(l)?!this._getCommandAndAncestors().some(u=>u.options.map(p=>p.short).some(p=>/^-\d$/.test(p))):!1,a=null,h=null,c=0;for(;c<t.length||h;){let l=h??t[c++];if(h=null,l==="--"){n===i&&n.push(l),n.push(...t.slice(c));break}if(a&&(!s(l)||o(l))){this.emit(`option:${a.name()}`,l);continue}if(a=null,s(l)){let u=this._findOption(l);if(u){if(u.required){let p=t[c++];p===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,p)}else if(u.optional){let p=null;c<t.length&&(!s(t[c])||o(t[c]))&&(p=t[c++]),this.emit(`option:${u.name()}`,p)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),h=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),p=this._findOption(l.slice(0,u));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,l.slice(u+1));continue}}if(n===e&&s(l)&&!(this.commands.length===0&&o(l))&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&i.length===0){if(this._findCommand(l)){e.push(l),i.push(...t.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){e.push(l,...t.slice(c));break}else if(this._defaultCommandName){i.push(l,...t.slice(c));break}}if(this._passThroughOptions){n.push(l,...t.slice(c));break}n.push(l)}return{operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){let t={},e=this.options.length;for(let i=0;i<e;i++){let n=this.options[i].attributeName();t[n]=n===this._versionOptionName?this._version:this[n]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,e)=>Object.assign(t,e.opts()),{})}error(t,e){this._outputConfiguration.outputError(`${t}
|
|
61
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
62
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
63
|
+
`),this.outputHelp({error:!0}));let i=e||{},n=i.exitCode||1,s=i.code||"commander.error";this._exit(n,s,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in m.env){let e=t.attributeName();(this.getOptionValue(e)===void 0||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,m.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new W(this.options),e=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&e(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!e(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){let i=o=>{let a=o.attributeName(),h=this.getOptionValue(a),c=this.options.find(u=>u.negate&&a===u.attributeName()),l=this.options.find(u=>!u.negate&&a===u.attributeName());return c&&(c.presetArg===void 0&&h===!1||c.presetArg!==void 0&&h===c.presetArg)?c:l||o},n=o=>{let a=i(o),h=a.attributeName();return this.getOptionValueSource(h)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${n(t)} cannot be used with ${n(e)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);n=n.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);e=nt(t,n)}let i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,i=e===1?"":"s",n=t.length,s=this.parent?` for '${this.name()}'`:"",o=t.join(", "),a=`error: too many arguments${s}. Expected ${e} argument${i} but got ${n}: ${o}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(s=>{n.push(s.name()),s.alias()&&n.push(s.alias())}),e=nt(t,n)}let i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"})}version(t,e,i){if(t===void 0)return this._version;this._version=t,e=e||"-V, --version",i=i||"output the version number";let n=this.createOption(e,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${t}
|
|
64
|
+
`),this._exit(0,"commander.version",t)}),this}description(t,e){return t===void 0&&e===void 0?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return e._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(e=>this.alias(e)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(i=>G(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup)}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup)}nameFromFilename(t){return this._name=b.basename(t,b.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let e=this.createHelp(),i=this._getOutputContext(t);e.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=e.formatHelp(this,e);return i.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(t){t=t||{};let e=!!t.error,i,n,s;return e?(i=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:e,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:n,helpWidth:s}}outputHelp(t){let e;typeof t=="function"&&(e=t,t=void 0);let i=this._getOutputContext(t),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation({error:i.error});if(e&&(s=e(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n))}helpOption(t,e){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",e??"display help for command"),(t||e)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let e=Number(m.exitCode??0);e===0&&t&&typeof t!="function"&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.
|
|
65
|
+
Expecting one of '${i.join("', '")}'`);let n=`${t}Help`;return this.on(n,s=>{let o;typeof e=="function"?o=e({error:s.error,command:s.command}):o=e,o&&s.write(`${o}
|
|
66
|
+
`)}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(n=>e.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}});var ai,vt=g(()=>{j();Et();k();et();it();ai=new v});function le(){let r=new Map;for(let[t,e]of Object.entries(d)){for(let[i,n]of Object.entries(e))d[i]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},e[i]=d[i],r.set(n[0],n[1]);Object.defineProperty(d,t,{value:e,enumerable:!1})}return Object.defineProperty(d,"codes",{value:r,enumerable:!1}),d.color.close="\x1B[39m",d.bgColor.close="\x1B[49m",d.color.ansi=wt(),d.color.ansi256=Tt(),d.color.ansi16m=$t(),d.bgColor.ansi=wt(10),d.bgColor.ansi256=Tt(10),d.bgColor.ansi16m=$t(10),Object.defineProperties(d,{rgbToAnsi256:{value(t,e,i){return t===e&&e===i?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(e/255*5)+Math.round(i/255*5)},enumerable:!1},hexToRgb:{value(t){let e=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!e)return[0,0,0];let[i]=e;i.length===3&&(i=[...i].map(s=>s+s).join(""));let n=Number.parseInt(i,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:t=>d.rgbToAnsi256(...d.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let e,i,n;if(t>=232)e=((t-232)*10+8)/255,i=e,n=e;else{t-=16;let a=t%36;e=Math.floor(t/36)/5,i=Math.floor(a/6)/5,n=a%6/5}let s=Math.max(e,i,n)*2;if(s===0)return 30;let o=30+(Math.round(n)<<2|Math.round(i)<<1|Math.round(e));return s===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(t,e,i)=>d.ansi256ToAnsi(d.rgbToAnsi256(t,e,i)),enumerable:!1},hexToAnsi:{value:t=>d.ansi256ToAnsi(d.hexToAnsi256(t)),enumerable:!1}}),d}var wt,Tt,$t,d,ui,oe,ae,hi,ue,O,kt=g(()=>{wt=(r=0)=>t=>`\x1B[${t+r}m`,Tt=(r=0)=>t=>`\x1B[${38+r};5;${t}m`,$t=(r=0)=>(t,e,i)=>`\x1B[${38+r};2;${t};${e};${i}m`,d={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},ui=Object.keys(d.modifier),oe=Object.keys(d.color),ae=Object.keys(d.bgColor),hi=[...oe,...ae];ue=le(),O=ue});import rt from"node:process";import he from"node:os";import Rt from"node:tty";function _(r,t=globalThis.Deno?globalThis.Deno.args:rt.argv){let e=r.startsWith("-")?"":r.length===1?"-":"--",i=t.indexOf(e+r),n=t.indexOf("--");return i!==-1&&(n===-1||i<n)}function ce(){if("FORCE_COLOR"in f)return f.FORCE_COLOR==="true"?1:f.FORCE_COLOR==="false"?0:f.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(f.FORCE_COLOR,10),3)}function pe(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function me(r,{streamIsTTY:t,sniffFlags:e=!0}={}){let i=ce();i!==void 0&&(B=i);let n=e?B:i;if(n===0)return 0;if(e){if(_("color=16m")||_("color=full")||_("color=truecolor"))return 3;if(_("color=256"))return 2}if("TF_BUILD"in f&&"AGENT_NAME"in f)return 1;if(r&&!t&&n===void 0)return 0;let s=n||0;if(f.TERM==="dumb")return s;if(rt.platform==="win32"){let o=he.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in f)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in f)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in f)||f.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in f)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(f.TEAMCITY_VERSION)?1:0;if(f.COLORTERM==="truecolor"||f.TERM==="xterm-kitty"||f.TERM==="xterm-ghostty"||f.TERM==="wezterm")return 3;if("TERM_PROGRAM"in f){let o=Number.parseInt((f.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(f.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(f.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(f.TERM)||"COLORTERM"in f?1:s}function Nt(r,t={}){let e=me(r,{streamIsTTY:r&&r.isTTY,...t});return pe(e)}var f,B,de,It,Vt=g(()=>{({env:f}=rt);_("no-color")||_("no-colors")||_("color=false")||_("color=never")?B=0:(_("color")||_("colors")||_("color=true")||_("color=always"))&&(B=1);de={stdout:Nt({isTTY:Rt.isatty(1)}),stderr:Nt({isTTY:Rt.isatty(2)})},It=de});function Pt(r,t,e){let i=r.indexOf(t);if(i===-1)return r;let n=t.length,s=0,o="";do o+=r.slice(s,i)+t+e,s=i+n,i=r.indexOf(t,s);while(i!==-1);return o+=r.slice(s),o}function Ht(r,t,e,i){let n=0,s="";do{let o=r[i-1]==="\r";s+=r.slice(n,o?i-1:i)+t+(o?`\r
|
|
67
|
+
`:`
|
|
68
|
+
`)+e,n=i+1,i=r.indexOf(`
|
|
69
|
+
`,n)}while(i!==-1);return s+=r.slice(n),s}var Ft=g(()=>{});function V(r){return ge(r)}var Mt,Dt,ot,w,I,Gt,T,fe,ge,at,_e,Oe,lt,q,be,Ce,Ci,jt,Wt=g(()=>{kt();Vt();Ft();({stdout:Mt,stderr:Dt}=It),ot=Symbol("GENERATOR"),w=Symbol("STYLER"),I=Symbol("IS_EMPTY"),Gt=["ansi","ansi","ansi256","ansi16m"],T=Object.create(null),fe=(r,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let e=Mt?Mt.level:0;r.level=t.level===void 0?e:t.level},ge=r=>{let t=(...e)=>e.join(" ");return fe(t,r),Object.setPrototypeOf(t,V.prototype),t};Object.setPrototypeOf(V.prototype,Function.prototype);for(let[r,t]of Object.entries(O))T[r]={get(){let e=q(this,lt(t.open,t.close,this[w]),this[I]);return Object.defineProperty(this,r,{value:e}),e}};T.visible={get(){let r=q(this,this[w],!0);return Object.defineProperty(this,"visible",{value:r}),r}};at=(r,t,e,...i)=>r==="rgb"?t==="ansi16m"?O[e].ansi16m(...i):t==="ansi256"?O[e].ansi256(O.rgbToAnsi256(...i)):O[e].ansi(O.rgbToAnsi(...i)):r==="hex"?at("rgb",t,e,...O.hexToRgb(...i)):O[e][r](...i),_e=["rgb","hex","ansi256"];for(let r of _e){T[r]={get(){let{level:e}=this;return function(...i){let n=lt(at(r,Gt[e],"color",...i),O.color.close,this[w]);return q(this,n,this[I])}}};let t="bg"+r[0].toUpperCase()+r.slice(1);T[t]={get(){let{level:e}=this;return function(...i){let n=lt(at(r,Gt[e],"bgColor",...i),O.bgColor.close,this[w]);return q(this,n,this[I])}}}}Oe=Object.defineProperties(()=>{},{...T,level:{enumerable:!0,get(){return this[ot].level},set(r){this[ot].level=r}}}),lt=(r,t,e)=>{let i,n;return e===void 0?(i=r,n=t):(i=e.openAll+r,n=t+e.closeAll),{open:r,close:t,openAll:i,closeAll:n,parent:e}},q=(r,t,e)=>{let i=(...n)=>be(i,n.length===1?""+n[0]:n.join(" "));return Object.setPrototypeOf(i,Oe),i[ot]=r,i[w]=t,i[I]=e,i},be=(r,t)=>{if(r.level<=0||!t)return r[I]?"":t;let e=r[w];if(e===void 0)return t;let{openAll:i,closeAll:n}=e;if(t.includes("\x1B"))for(;e!==void 0;)t=Pt(t,e.close,e.open),e=e.parent;let s=t.indexOf(`
|
|
70
|
+
`);return s!==-1&&(t=Ht(t,n,i,s)),i+t+n};Object.defineProperties(V.prototype,T);Ce=V(),Ci=V({level:Dt?Dt.level:0}),jt=Ce});var ut={};ct(ut,{buildProgram:()=>Ae,printSessions:()=>Lt,registerSessionsCommands:()=>qt,runQuery:()=>Bt});function ye(r){let t=jt.cyan(r.shortId.padEnd(8)),e=(r.agent||"-").padEnd(8),i=(r.version||"-").slice(0,8).padEnd(8),n=(r.project||"-").slice(0,16).padEnd(16),s=(r.label||r.topic||"-").replace(/\s+/g," ").slice(0,40);return`${t} ${e} ${i} ${n} ${s}`}function Lt(r,t){if(t){process.stdout.write(JSON.stringify(r,null,2)+`
|
|
71
|
+
`);return}if(r.length===0){process.stderr.write(`No sessions matched.
|
|
72
|
+
`);return}for(let e of r)process.stdout.write(ye(e)+`
|
|
73
|
+
`);process.stderr.write(`${r.length} session${r.length===1?"":"s"}.
|
|
74
|
+
`)}function Bt(r){let t=r.includes("--json"),e=gt(r);try{let i=M(e);return Lt(i,t),0}catch(i){return process.stderr.write(`${i instanceof Error?i.message:String(i)}
|
|
75
|
+
`),1}}function qt(r){r.argument("[query...]","FTS query, or a session id").option("--json","JSON array of SessionMeta-shaped rows").option("--limit <n>","max rows","20").option("--agent <id>","filter by harness (claude, grok, \u2026)").option("--local","local index only (always true in v1; accepted for agents-cli flag parity)").option("--no-interactive","ignored; this CLI never opens a picker").allowExcessArguments().allowUnknownOption().action(()=>{process.exit(Bt(process.argv.slice(2)))}),r.addHelpText("after",`
|
|
76
|
+
Examples:
|
|
77
|
+
sessions "auth middleware" --json --limit 5
|
|
78
|
+
sessions a1b2c3d4 --json
|
|
79
|
+
sessions --limit 20
|
|
80
|
+
|
|
81
|
+
v1 is the read/index engine. resume/stop/inject stay on \`agents sessions <verb>\`.
|
|
82
|
+
Hidden fast paths (no commander): __query __serve
|
|
83
|
+
`)}function Ae(){let r=new v("sessions").description("Search and list indexed agent sessions. Local, no SSH, no agents-cli boot.").version(H(),"-v, --version").showHelpAfterError();return qt(r),r}var ht=g(()=>{"use strict";vt();Wt();Y();X()});Y();process.on("SIGPIPE",()=>{});var U=process.argv[2];if(U==="__serve"){let{runProtocolServer:r}=await Promise.resolve().then(()=>(Ct(),bt));r(),process.exit(process.exitCode??0)}if(U==="__query"){let{runQuery:r}=await Promise.resolve().then(()=>(ht(),ut));process.exit(r(process.argv.slice(3)))}(U==="--version"||U==="-v")&&(process.stdout.write(H()+`
|
|
84
|
+
`),process.exit(0));var{buildProgram:xe}=await Promise.resolve().then(()=>(ht(),ut)),Se=xe();try{await Se.parseAsync(process.argv)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
85
|
+
`),process.exit(1)}
|
package/package.json
CHANGED
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@phnx-labs/sessions-cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "High-performance session index: search, list, and preview agent transcripts",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"sessions": "dist/index.js"
|
|
8
8
|
},
|
|
9
9
|
"files": [
|
|
10
|
-
"dist
|
|
11
|
-
"dist/**/*.d.ts",
|
|
10
|
+
"dist/index.js",
|
|
12
11
|
"README.md",
|
|
13
12
|
"LICENSE",
|
|
14
13
|
"CHANGELOG.md"
|
|
@@ -23,6 +22,7 @@
|
|
|
23
22
|
"license": "FSL-1.1-Apache-2.0",
|
|
24
23
|
"scripts": {
|
|
25
24
|
"build": "bash scripts/build.sh",
|
|
25
|
+
"bundle": "bash scripts/bundle.sh",
|
|
26
26
|
"test": "bash scripts/test.sh",
|
|
27
27
|
"scan": "bash scripts/scan.sh",
|
|
28
28
|
"release": "bash scripts/release.sh"
|
|
@@ -33,6 +33,7 @@
|
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@types/node": "26.1.0",
|
|
36
|
+
"esbuild": "0.28.2",
|
|
36
37
|
"tsx": "4.21.0",
|
|
37
38
|
"typescript": "6.0.3",
|
|
38
39
|
"vitest": "4.1.9"
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { Command } from 'commander';
|
|
2
|
-
import { type SessionRow } from '../lib/query.js';
|
|
3
|
-
export declare function printSessions(rows: SessionRow[], json: boolean): void;
|
|
4
|
-
export declare function runQuery(argv: string[]): number;
|
|
5
|
-
export declare function registerSessionsCommands(program: Command): void;
|
|
6
|
-
export declare function buildProgram(): Command;
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
import { Command } from 'commander';
|
|
2
|
-
import chalk from 'chalk';
|
|
3
|
-
import { getCliVersion } from '../lib/version.js';
|
|
4
|
-
import { parseQueryArgs, querySessions } from '../lib/query.js';
|
|
5
|
-
function formatRow(row) {
|
|
6
|
-
const id = chalk.cyan(row.shortId.padEnd(8));
|
|
7
|
-
const agent = (row.agent || '-').padEnd(8);
|
|
8
|
-
const version = (row.version || '-').slice(0, 8).padEnd(8);
|
|
9
|
-
const project = (row.project || '-').slice(0, 16).padEnd(16);
|
|
10
|
-
const title = (row.label || row.topic || '-').replace(/\s+/g, ' ').slice(0, 40);
|
|
11
|
-
return `${id} ${agent} ${version} ${project} ${title}`;
|
|
12
|
-
}
|
|
13
|
-
export function printSessions(rows, json) {
|
|
14
|
-
if (json) {
|
|
15
|
-
process.stdout.write(JSON.stringify(rows, null, 2) + '\n');
|
|
16
|
-
return;
|
|
17
|
-
}
|
|
18
|
-
if (rows.length === 0) {
|
|
19
|
-
process.stderr.write('No sessions matched.\n');
|
|
20
|
-
return;
|
|
21
|
-
}
|
|
22
|
-
for (const row of rows)
|
|
23
|
-
process.stdout.write(formatRow(row) + '\n');
|
|
24
|
-
process.stderr.write(`${rows.length} session${rows.length === 1 ? '' : 's'}.\n`);
|
|
25
|
-
}
|
|
26
|
-
export function runQuery(argv) {
|
|
27
|
-
const json = argv.includes('--json');
|
|
28
|
-
const options = parseQueryArgs(argv);
|
|
29
|
-
try {
|
|
30
|
-
const rows = querySessions(options);
|
|
31
|
-
printSessions(rows, json);
|
|
32
|
-
return 0;
|
|
33
|
-
}
|
|
34
|
-
catch (error) {
|
|
35
|
-
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
36
|
-
return 1;
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
export function registerSessionsCommands(program) {
|
|
40
|
-
program
|
|
41
|
-
.argument('[query...]', 'FTS query, or a session id')
|
|
42
|
-
.option('--json', 'JSON array of SessionMeta-shaped rows')
|
|
43
|
-
.option('--limit <n>', 'max rows', '20')
|
|
44
|
-
.option('--agent <id>', 'filter by harness (claude, grok, …)')
|
|
45
|
-
.option('--local', 'local index only (always true in v1; accepted for agents-cli flag parity)')
|
|
46
|
-
.option('--no-interactive', 'ignored; this CLI never opens a picker')
|
|
47
|
-
.allowExcessArguments()
|
|
48
|
-
.allowUnknownOption()
|
|
49
|
-
.action(() => {
|
|
50
|
-
process.exit(runQuery(process.argv.slice(2)));
|
|
51
|
-
});
|
|
52
|
-
program.addHelpText('after', `
|
|
53
|
-
Examples:
|
|
54
|
-
sessions "auth middleware" --json --limit 5
|
|
55
|
-
sessions a1b2c3d4 --json
|
|
56
|
-
sessions --limit 20
|
|
57
|
-
|
|
58
|
-
v1 is the read/index engine. resume/stop/inject stay on \`agents sessions <verb>\`.
|
|
59
|
-
Hidden fast paths (no commander): __query __serve
|
|
60
|
-
`);
|
|
61
|
-
}
|
|
62
|
-
export function buildProgram() {
|
|
63
|
-
const program = new Command('sessions')
|
|
64
|
-
.description('Search and list indexed agent sessions. Local, no SSH, no agents-cli boot.')
|
|
65
|
-
.version(getCliVersion(), '-v, --version')
|
|
66
|
-
.showHelpAfterError();
|
|
67
|
-
registerSessionsCommands(program);
|
|
68
|
-
return program;
|
|
69
|
-
}
|
package/dist/index.d.ts
DELETED
package/dist/lib/paths.d.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
/** Default index path — the same file agents-cli already writes. */
|
|
2
|
-
export declare function defaultSessionsDbPath(home?: string): string;
|
|
3
|
-
/**
|
|
4
|
-
* Resolve the SQLite index. `$SESSIONS_DB` wins (tests, power users),
|
|
5
|
-
* then `$AGENTS_SESSIONS_DB` (the agents-cli test seam), else the default.
|
|
6
|
-
*/
|
|
7
|
-
export declare function resolveSessionsDbPath(env?: NodeJS.ProcessEnv, home?: string): string;
|
package/dist/lib/paths.js
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import * as os from 'os';
|
|
2
|
-
import * as path from 'path';
|
|
3
|
-
/** Default index path — the same file agents-cli already writes. */
|
|
4
|
-
export function defaultSessionsDbPath(home = os.homedir()) {
|
|
5
|
-
return path.join(home, '.agents', '.history', 'sessions', 'sessions.db');
|
|
6
|
-
}
|
|
7
|
-
/**
|
|
8
|
-
* Resolve the SQLite index. `$SESSIONS_DB` wins (tests, power users),
|
|
9
|
-
* then `$AGENTS_SESSIONS_DB` (the agents-cli test seam), else the default.
|
|
10
|
-
*/
|
|
11
|
-
export function resolveSessionsDbPath(env = process.env, home = os.homedir()) {
|
|
12
|
-
const explicit = env.SESSIONS_DB?.trim() || env.AGENTS_SESSIONS_DB?.trim();
|
|
13
|
-
if (explicit)
|
|
14
|
-
return explicit;
|
|
15
|
-
return defaultSessionsDbPath(home);
|
|
16
|
-
}
|
package/dist/lib/query.d.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
-
export interface SessionRow {
|
|
3
|
-
id: string;
|
|
4
|
-
shortId: string;
|
|
5
|
-
agent: string;
|
|
6
|
-
version: string | null;
|
|
7
|
-
account: string | null;
|
|
8
|
-
timestamp: string;
|
|
9
|
-
lastActivity: string | null;
|
|
10
|
-
project: string | null;
|
|
11
|
-
cwd: string | null;
|
|
12
|
-
gitBranch: string | null;
|
|
13
|
-
topic: string | null;
|
|
14
|
-
label: string | null;
|
|
15
|
-
messageCount: number | null;
|
|
16
|
-
tokenCount: number | null;
|
|
17
|
-
filePath: string;
|
|
18
|
-
origin: string | null;
|
|
19
|
-
machine: string | null;
|
|
20
|
-
model: string | null;
|
|
21
|
-
harness: string | null;
|
|
22
|
-
ticketId: string | null;
|
|
23
|
-
prUrl: string | null;
|
|
24
|
-
durationMs: number | null;
|
|
25
|
-
costUsd: number | null;
|
|
26
|
-
}
|
|
27
|
-
export interface QueryOptions {
|
|
28
|
-
query?: string;
|
|
29
|
-
limit?: number;
|
|
30
|
-
idPrefix?: string;
|
|
31
|
-
agent?: string;
|
|
32
|
-
dbPath?: string;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Turn a raw user query into a safe FTS5 MATCH expression.
|
|
36
|
-
* Same tokenizer as agents-cli: split on non-alphanumeric, keep tokens of
|
|
37
|
-
* 2+ chars, prefix-match with OR. Hyphens, colons, and FTS operators never
|
|
38
|
-
* reach MATCH as syntax — `secrets-cli` cannot throw `no such column: cli`.
|
|
39
|
-
*/
|
|
40
|
-
export declare function buildFtsQuery(input: string): {
|
|
41
|
-
expr: string;
|
|
42
|
-
terms: string[];
|
|
43
|
-
};
|
|
44
|
-
export declare function openSessionsDb(dbPath?: string): DatabaseSync;
|
|
45
|
-
export declare function querySessions(options?: QueryOptions): SessionRow[];
|
|
46
|
-
export declare function looksLikeId(value: string): boolean;
|
|
47
|
-
export declare function parseQueryArgs(argv: string[]): QueryOptions;
|
package/dist/lib/query.js
DELETED
|
@@ -1,156 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Read-only session index. Opens sessions.db, runs FTS / listing / id lookup,
|
|
3
|
-
* never walks the filesystem, never writes, never talks to SSH.
|
|
4
|
-
*
|
|
5
|
-
* Column names match agents-cli SessionMeta JSON so `agents sessions --json`
|
|
6
|
-
* consumers keep working after the passthrough cutover.
|
|
7
|
-
*/
|
|
8
|
-
import * as fs from 'fs';
|
|
9
|
-
import { DatabaseSync } from 'node:sqlite';
|
|
10
|
-
import { resolveSessionsDbPath } from './paths.js';
|
|
11
|
-
const SELECT_COLS = `
|
|
12
|
-
s.id,
|
|
13
|
-
s.short_id AS shortId,
|
|
14
|
-
s.agent,
|
|
15
|
-
s.version,
|
|
16
|
-
s.account,
|
|
17
|
-
s.timestamp,
|
|
18
|
-
s.last_activity AS lastActivity,
|
|
19
|
-
s.project,
|
|
20
|
-
s.cwd,
|
|
21
|
-
s.git_branch AS gitBranch,
|
|
22
|
-
s.topic,
|
|
23
|
-
s.label,
|
|
24
|
-
s.message_count AS messageCount,
|
|
25
|
-
s.token_count AS tokenCount,
|
|
26
|
-
s.file_path AS filePath,
|
|
27
|
-
s.origin,
|
|
28
|
-
s.machine,
|
|
29
|
-
s.model,
|
|
30
|
-
s.harness,
|
|
31
|
-
s.ticket_id AS ticketId,
|
|
32
|
-
s.pr_url AS prUrl,
|
|
33
|
-
s.duration_ms AS durationMs,
|
|
34
|
-
s.cost_usd AS costUsd
|
|
35
|
-
`;
|
|
36
|
-
/**
|
|
37
|
-
* Turn a raw user query into a safe FTS5 MATCH expression.
|
|
38
|
-
* Same tokenizer as agents-cli: split on non-alphanumeric, keep tokens of
|
|
39
|
-
* 2+ chars, prefix-match with OR. Hyphens, colons, and FTS operators never
|
|
40
|
-
* reach MATCH as syntax — `secrets-cli` cannot throw `no such column: cli`.
|
|
41
|
-
*/
|
|
42
|
-
export function buildFtsQuery(input) {
|
|
43
|
-
const terms = input.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length >= 2);
|
|
44
|
-
if (terms.length === 0)
|
|
45
|
-
return { expr: '', terms: [] };
|
|
46
|
-
return { expr: terms.map((t) => `${t}*`).join(' OR '), terms };
|
|
47
|
-
}
|
|
48
|
-
export function openSessionsDb(dbPath = resolveSessionsDbPath()) {
|
|
49
|
-
return new DatabaseSync(dbPath, { readOnly: true });
|
|
50
|
-
}
|
|
51
|
-
function rowFrom(raw) {
|
|
52
|
-
return {
|
|
53
|
-
id: String(raw.id),
|
|
54
|
-
shortId: String(raw.shortId ?? ''),
|
|
55
|
-
agent: String(raw.agent ?? ''),
|
|
56
|
-
version: raw.version ?? null,
|
|
57
|
-
account: raw.account ?? null,
|
|
58
|
-
timestamp: String(raw.timestamp ?? ''),
|
|
59
|
-
lastActivity: raw.lastActivity ?? null,
|
|
60
|
-
project: raw.project ?? null,
|
|
61
|
-
cwd: raw.cwd ?? null,
|
|
62
|
-
gitBranch: raw.gitBranch ?? null,
|
|
63
|
-
topic: raw.topic ?? null,
|
|
64
|
-
label: raw.label ?? null,
|
|
65
|
-
messageCount: typeof raw.messageCount === 'number' ? raw.messageCount : null,
|
|
66
|
-
tokenCount: typeof raw.tokenCount === 'number' ? raw.tokenCount : null,
|
|
67
|
-
filePath: String(raw.filePath ?? ''),
|
|
68
|
-
origin: raw.origin ?? null,
|
|
69
|
-
machine: raw.machine ?? null,
|
|
70
|
-
model: raw.model ?? null,
|
|
71
|
-
harness: raw.harness ?? null,
|
|
72
|
-
ticketId: raw.ticketId ?? null,
|
|
73
|
-
prUrl: raw.prUrl ?? null,
|
|
74
|
-
durationMs: typeof raw.durationMs === 'number' ? raw.durationMs : null,
|
|
75
|
-
costUsd: typeof raw.costUsd === 'number' ? raw.costUsd : null,
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
export function querySessions(options = {}) {
|
|
79
|
-
const dbPath = options.dbPath ?? resolveSessionsDbPath();
|
|
80
|
-
const limit = Math.max(1, Math.min(options.limit ?? 20, 500));
|
|
81
|
-
if (!fs.existsSync(dbPath) || fs.statSync(dbPath).size === 0)
|
|
82
|
-
return [];
|
|
83
|
-
const db = openSessionsDb(dbPath);
|
|
84
|
-
try {
|
|
85
|
-
if (options.idPrefix && looksLikeId(options.idPrefix) && !options.query) {
|
|
86
|
-
const stmt = db.prepare(`SELECT ${SELECT_COLS} FROM sessions s
|
|
87
|
-
WHERE (s.id = ? OR s.id LIKE ? OR s.short_id = ?)
|
|
88
|
-
AND s.archived_at IS NULL
|
|
89
|
-
LIMIT ?`);
|
|
90
|
-
const prefix = options.idPrefix;
|
|
91
|
-
const rows = stmt.all(prefix, `${prefix}%`, prefix, limit);
|
|
92
|
-
return rows.map(rowFrom);
|
|
93
|
-
}
|
|
94
|
-
if (options.query && options.query.trim()) {
|
|
95
|
-
const { expr } = buildFtsQuery(options.query);
|
|
96
|
-
if (!expr)
|
|
97
|
-
return [];
|
|
98
|
-
const stmt = db.prepare(`SELECT ${SELECT_COLS}
|
|
99
|
-
FROM sessions s
|
|
100
|
-
JOIN session_text t ON t.session_id = s.id
|
|
101
|
-
WHERE session_text MATCH ?
|
|
102
|
-
AND s.archived_at IS NULL
|
|
103
|
-
${options.agent ? 'AND s.agent = ?' : ''}
|
|
104
|
-
ORDER BY rank
|
|
105
|
-
LIMIT ?`);
|
|
106
|
-
const bind = options.agent ? [expr, options.agent, limit] : [expr, limit];
|
|
107
|
-
const rows = stmt.all(...bind);
|
|
108
|
-
return rows.map(rowFrom);
|
|
109
|
-
}
|
|
110
|
-
const stmt = db.prepare(`SELECT ${SELECT_COLS} FROM sessions s
|
|
111
|
-
WHERE s.archived_at IS NULL
|
|
112
|
-
${options.agent ? 'AND s.agent = ?' : ''}
|
|
113
|
-
ORDER BY s.last_activity DESC, s.timestamp DESC
|
|
114
|
-
LIMIT ?`);
|
|
115
|
-
const bind = options.agent ? [options.agent, limit] : [limit];
|
|
116
|
-
const rows = stmt.all(...bind);
|
|
117
|
-
return rows.map(rowFrom);
|
|
118
|
-
}
|
|
119
|
-
finally {
|
|
120
|
-
db.close();
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
export function looksLikeId(value) {
|
|
124
|
-
return /^[0-9a-f]{8,}$/i.test(value) || /^[0-9a-f-]{8,}$/i.test(value);
|
|
125
|
-
}
|
|
126
|
-
export function parseQueryArgs(argv) {
|
|
127
|
-
const options = {};
|
|
128
|
-
const rest = [];
|
|
129
|
-
for (let i = 0; i < argv.length; i++) {
|
|
130
|
-
const arg = argv[i];
|
|
131
|
-
if (arg === '--json' || arg === '--local' || arg === '--no-interactive')
|
|
132
|
-
continue;
|
|
133
|
-
if (arg === '--limit' && argv[i + 1]) {
|
|
134
|
-
options.limit = Number(argv[++i]);
|
|
135
|
-
continue;
|
|
136
|
-
}
|
|
137
|
-
if (arg.startsWith('--limit=')) {
|
|
138
|
-
options.limit = Number(arg.slice('--limit='.length));
|
|
139
|
-
continue;
|
|
140
|
-
}
|
|
141
|
-
if (arg === '--agent' && argv[i + 1]) {
|
|
142
|
-
options.agent = argv[++i];
|
|
143
|
-
continue;
|
|
144
|
-
}
|
|
145
|
-
if (arg.startsWith('--'))
|
|
146
|
-
continue;
|
|
147
|
-
rest.push(arg);
|
|
148
|
-
}
|
|
149
|
-
if (rest.length === 1 && looksLikeId(rest[0]) && !rest[0].includes(' ')) {
|
|
150
|
-
options.idPrefix = rest[0];
|
|
151
|
-
}
|
|
152
|
-
else if (rest.length > 0) {
|
|
153
|
-
options.query = rest.join(' ');
|
|
154
|
-
}
|
|
155
|
-
return options;
|
|
156
|
-
}
|
package/dist/lib/version.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare function getCliVersion(pkgJsonPath?: string): string;
|
package/dist/lib/version.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import * as fs from 'fs';
|
|
2
|
-
import * as path from 'path';
|
|
3
|
-
import { fileURLToPath } from 'url';
|
|
4
|
-
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
5
|
-
const PKG_JSON = path.join(__dirname, '..', '..', 'package.json');
|
|
6
|
-
let cached = null;
|
|
7
|
-
export function getCliVersion(pkgJsonPath = PKG_JSON) {
|
|
8
|
-
if (cached)
|
|
9
|
-
return cached;
|
|
10
|
-
try {
|
|
11
|
-
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));
|
|
12
|
-
cached = String(pkg.version || '') || 'unknown';
|
|
13
|
-
}
|
|
14
|
-
catch {
|
|
15
|
-
cached = 'unknown';
|
|
16
|
-
}
|
|
17
|
-
return cached;
|
|
18
|
-
}
|
package/dist/protocol-server.js
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
import * as fs from 'fs';
|
|
2
|
-
import { PROTOCOL_VERSION } from './protocol.js';
|
|
3
|
-
import { querySessions } from './lib/query.js';
|
|
4
|
-
/** Cap the __serve request body. Local caller, but unbounded read is a DoS. */
|
|
5
|
-
export const MAX_REQUEST_BYTES = 1024 * 1024;
|
|
6
|
-
export function readFd(fd, maxBytes = MAX_REQUEST_BYTES) {
|
|
7
|
-
const chunks = [];
|
|
8
|
-
let total = 0;
|
|
9
|
-
for (;;) {
|
|
10
|
-
const buf = Buffer.alloc(64 * 1024);
|
|
11
|
-
const n = fs.readSync(fd, buf, 0, buf.length, null);
|
|
12
|
-
if (n === 0)
|
|
13
|
-
break;
|
|
14
|
-
total += n;
|
|
15
|
-
if (total > maxBytes) {
|
|
16
|
-
throw new Error(`request exceeds ${maxBytes} bytes`);
|
|
17
|
-
}
|
|
18
|
-
chunks.push(buf.subarray(0, n));
|
|
19
|
-
}
|
|
20
|
-
return Buffer.concat(chunks);
|
|
21
|
-
}
|
|
22
|
-
export function runProtocolServer() {
|
|
23
|
-
let raw;
|
|
24
|
-
try {
|
|
25
|
-
raw = readFd(3);
|
|
26
|
-
}
|
|
27
|
-
catch (error) {
|
|
28
|
-
process.stderr.write(`sessions __serve: failed to read fd 3: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
29
|
-
process.exit(1);
|
|
30
|
-
return;
|
|
31
|
-
}
|
|
32
|
-
let request;
|
|
33
|
-
try {
|
|
34
|
-
request = JSON.parse(raw.toString('utf8'));
|
|
35
|
-
}
|
|
36
|
-
catch {
|
|
37
|
-
writeResponse({
|
|
38
|
-
v: PROTOCOL_VERSION,
|
|
39
|
-
id: '',
|
|
40
|
-
ok: false,
|
|
41
|
-
error: { code: 'INVALID_RESPONSE', message: 'request is not JSON' },
|
|
42
|
-
});
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
try {
|
|
46
|
-
const rows = querySessions({
|
|
47
|
-
query: request.op === 'get' ? undefined : request.args?.query,
|
|
48
|
-
idPrefix: request.op === 'get' ? request.args?.idPrefix : request.args?.idPrefix,
|
|
49
|
-
limit: request.args?.limit,
|
|
50
|
-
agent: request.args?.agent,
|
|
51
|
-
});
|
|
52
|
-
writeResponse({ v: PROTOCOL_VERSION, id: request.id, ok: true, result: rows });
|
|
53
|
-
}
|
|
54
|
-
catch (error) {
|
|
55
|
-
writeResponse({
|
|
56
|
-
v: PROTOCOL_VERSION,
|
|
57
|
-
id: request.id,
|
|
58
|
-
ok: false,
|
|
59
|
-
error: {
|
|
60
|
-
code: 'OPERATION_FAILED',
|
|
61
|
-
message: error instanceof Error ? error.message : String(error),
|
|
62
|
-
},
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
function writeResponse(response) {
|
|
67
|
-
const body = Buffer.from(JSON.stringify(response), 'utf8');
|
|
68
|
-
fs.writeSync(4, body);
|
|
69
|
-
}
|
package/dist/protocol.d.ts
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
export declare const PROTOCOL_VERSION = 1;
|
|
2
|
-
export type SessionsOp = 'query' | 'list' | 'get';
|
|
3
|
-
export interface SessionsRequest {
|
|
4
|
-
v: number;
|
|
5
|
-
id: string;
|
|
6
|
-
op: SessionsOp;
|
|
7
|
-
args: {
|
|
8
|
-
query?: string;
|
|
9
|
-
limit?: number;
|
|
10
|
-
idPrefix?: string;
|
|
11
|
-
agent?: string;
|
|
12
|
-
};
|
|
13
|
-
}
|
|
14
|
-
export interface SessionsResponse {
|
|
15
|
-
v: number;
|
|
16
|
-
id: string;
|
|
17
|
-
ok: boolean;
|
|
18
|
-
result?: unknown;
|
|
19
|
-
error?: {
|
|
20
|
-
code: string;
|
|
21
|
-
message: string;
|
|
22
|
-
};
|
|
23
|
-
}
|
package/dist/protocol.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export const PROTOCOL_VERSION = 1;
|