aegisone 1.0.30 → 1.0.32

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # AEGISONE
2
2
 
3
- Product version: **1.0.30**
3
+ Product version: **1.0.32**
4
4
 
5
5
  One product, two faces: the terminal (`aegiscode`) and the window (`aegis-desktop`),
6
6
  reached through one command — `aegis` — and released as one version.
@@ -60,7 +60,7 @@ fails, and it never leaves you with "nothing happened". Afterwards: `aegis`
60
60
 
61
61
  ## Size, measured not claimed
62
62
 
63
- Measured size: **2.39 MB** (2,509,385 bytes) with Electron absent — both faces inside.
63
+ Measured size: **2.50 MB** (2,626,046 bytes) with Electron absent — both faces inside.
64
64
 
65
65
  The plan's "~2 MB" was a target, so it is measured here rather than published:
66
66
  `npm pack one/` on this tree, with Electron absent, produces that tarball, and it
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegisone",
3
3
  "productName": "AEGISONE",
4
- "version": "1.0.30",
4
+ "version": "1.0.32",
5
5
  "description": "AEGISONE — one product, two faces. `aegis` opens the window when there is nothing else to do and runs the terminal otherwise; `aegiscode` keeps behaving exactly as it always has.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- import e from"node:fs";import r from"node:path";import{spawnSync as s}from"node:child_process";import{fileURLToPath as t,pathToFileURL as o}from"node:url";import{createRequire as n}from"node:module";const i=r.dirname(t(import.meta.url)),a=n(import.meta.url);export const ONE_DIR=r.join(i,"..");export const REPO_DIR=r.join(ONE_DIR,"..");export const CLI_DIR=r.join(REPO_DIR,"cli");export const DESKTOP_DIR=r.join(REPO_DIR,"desktop");export const CLI_VENDOR=r.join(CLI_DIR,"vendor");export const DESKTOP_VENDOR=r.join(DESKTOP_DIR,"vendor");export const ONE_VENDOR=r.join(ONE_DIR,"vendor");export const MANIFEST=[{src:"client/aegis.js",shapes:["mirror","flat"],note:"the thin transport — the one implementation of the wire format"},{src:"client/update.js",shapes:["mirror","flat"],note:"the npm update checker (the desktop own update path)"},{src:"client/foreign-memory.js",shapes:["mirror","flat"],note:"required by mcp/tools.js as ../client/foreign-memory.js"},{src:"client/credentials.js",shapes:["mirror","flat"],note:"the account credential store, shared by all three hosts"},{src:"client/session-store.js",shapes:["mirror","flat"],note:"the unified session store — one list in every host"},{src:"client/prefs.js",shapes:["mirror","flat"],note:"the shared non-secret preference store (D5) — the CLI and the desktop store both read/write it"},{src:"client/env-file.js",shapes:["mirror","flat"],note:"the shared ~/.aegiscode/.env loader, resolved before any key is read"},{src:"client/auto-provision.js",shapes:["mirror","flat"],note:"free device key on first launch; requires ./device-fingerprint.js"},{src:"client/device-fingerprint.js",shapes:["mirror","flat"],note:"the machine identity auto-provision.js and presence.js require"},{src:"client/presence.js",shapes:["mirror","flat"],note:"the heartbeat beacon; requires ./presence-constants.js and ./device-fingerprint.js"},{src:"client/presence-constants.js",shapes:["mirror","flat"],note:"the beacon constants — a package without them loses the beacon silently"},{src:"client/touch.js",shapes:["mirror","flat"],note:"phi(alpha): the digest module fingerprint.js requires as ./touch.js"},{src:"client/fingerprint.js",shapes:["mirror","flat"],note:"phi(alpha): the sealed session record, resolved by src/fingerprint.js"},{src:"client/authorship-key.js",shapes:["mirror","flat"],note:"phi(alpha): the authorship key, required by ./attest.js and ./record-vault.js"},{src:"client/attest.js",shapes:["mirror","flat"],note:"phi(alpha): attestation, requires ./fingerprint.js and ./authorship-key.js"},{src:"client/record-vault.js",shapes:["mirror","flat"],note:"the vault, and its refusal to copy the key with the record"},{src:"client/brain-catalog.js",shapes:["mirror","flat"],note:"the pooled-brain rule, required at load time by the engine and src/models.js"},{src:"client/byok-catalog.js",shapes:["mirror","flat"],note:"the BYOK model additions the server catalog does not name"},{src:"client/catalog-client.js",shapes:["mirror","flat"],note:"the server's cached catalog, layered between the shipped additions and the user's own models"},{src:"client/user-models.js",shapes:["mirror","flat"],note:"the models the USER declares, in one file both hosts read (requires ./credentials.js)"},{src:"client/model-discovery.js",shapes:["mirror","flat"],note:"asks the vendor what it serves, so adding a new model is not a memory test (requires ./user-models.js)"},{src:"client/hooks.js",shapes:["mirror","flat"],note:"the shared hook layer behind /hooks and the repo guard installer"},{src:"client/platform.js",shapes:["mirror","flat"],note:"the ONE place that decides which OS this is (Phase 30.1)"},{src:"client/topup.js",shapes:["mirror","flat"],note:"the token-bank top-up: amount bounds, the balance reading, and the credit watch every host drives"},{src:"client/google-signin.js",shapes:["mirror","flat"],note:"the localhost half of aegis1's desktop Google OAuth round-trip; `connect --google` drives it"},{src:"client/drive-connect.js",shapes:["mirror","flat"],note:"the desktop half of aegis1's Drive OAuth (/connect/drive, /api/drive/token); requires ./aegis.js only via the caller"},{src:"client/drive-upload.js",shapes:["mirror","flat"],note:"the Drive v3 REST wrapper that uploads the memory backup and one conversation per save"},{src:"client/conversation-export.js",shapes:["mirror","flat"],note:"the authorship stamp at the top of every uploaded file, and the two backup scope names"},{src:"mcp/tools.js",shapes:["mirror"],note:"the shared tool registry; requires ../client/foreign-memory.js"},{src:"mcp/server.js",shapes:["mirror"],note:"the stdio MCP server every installed editor config names (compiled, never required)"},{src:"hosts/spec.js",shapes:["mirror"],note:"the canonical server spec, staged under its own directory so it finds vendor/mcp/server.js"},{src:"hosts/targets.js",shapes:["mirror"],note:"the editor target registry"},{src:"hosts/install.js",shapes:["mirror"],note:"the merge-only installer behind aegiscode mcp install"},{src:"hosts/openai-shim.js",shapes:["mirror"],note:"the loopback OpenAI-compatible shim"},{src:"desktop/renderer/usage.js",shapes:["mirror"],note:"the pure usage mapping shared by the window and the terminal"},{src:"desktop/lib/local/engine.js",shapes:["mirror"],note:"the agent loop, reused as-is (one loop, not a second one drifting)"},{src:"desktop/lib/local/claude-pro.js",shapes:["mirror"],note:"the Claude Code Pro transport; requires ./../../one/src/child.js at call time"},{src:"one/src/child.js",shapes:["mirror"],note:"the ONE claude-child argv builder (rule 4); resolved by claude-pro.js at call time"},{src:"one/src/permissions.js",shapes:["mirror"],note:"resolvePosture() — the permission half of the argv, resolved at call time"},{src:"desktop/lib/local/local.js",shapes:["mirror"],note:"the local model transport and its fail-closed base-URL check"},{src:"desktop/lib/local/context.js",shapes:["mirror"],note:"the token-budget trimmer local.js requires at load"},{src:"desktop/lib/local/attachments.js",shapes:["mirror"],note:"content-part builder for dropped files; required at load by engine.js and local.js"},{src:"desktop/lib/local/session-rounds.js",shapes:["mirror"],note:"interrupted-turn bookkeeping; required at load by engine.js"},{src:"desktop/lib/local/tools.js",shapes:["mirror"],note:"the tool implementations (persistent shell, editFile, grep, exec)"},{src:"desktop/lib/local/shell.js",shapes:["mirror"],note:"the persistent shell, required by tools.js"},{src:"desktop/lib/local/spill.js",shapes:["mirror"],note:"oversized-output spill, required at load by tools.js and shell.js"},{src:"desktop/lib/local/exec-plan.js",shapes:["mirror"],note:"exec one-shot eligibility classifier, required at load by engine.js"},{src:"desktop/lib/local/agents.js",shapes:["mirror"],note:"Task subagents"},{src:"desktop/lib/local/prompt.js",shapes:["mirror"],note:"the system prompt builder"},{src:"desktop/lib/settings.js",shapes:["mirror"],note:"the provider-config store (base URL + key per provider)"},{src:"desktop/lib/local/turn-guard.js",shapes:["mirror"],note:"engine.js requires it at load; it requires ./git-scope.js"},{src:"desktop/lib/local/worktree-lock.js",shapes:["mirror"],note:"engine.js requires it at load"},{src:"desktop/lib/local/git-scope.js",shapes:["mirror"],note:"the write-scope rule turn-guard.js and the queues share"},{src:"desktop/lib/local/queue.js",shapes:["mirror"],note:"the autonomous work queue"},{src:"desktop/lib/local/autonomous.js",shapes:["mirror"],note:"the unattended worker; requires ./queue.js and ./git-scope.js"},{src:"desktop/lib/local/entitlement.js",shapes:["mirror"],note:"the shared Pro gate (account probe injected by the caller)"},{src:"desktop/lib/local/covenant.js",shapes:["mirror"],note:"the pre-action gate engine.js requires unconditionally at load"},{src:"desktop/lib/local/aegis-seal.mjs",shapes:["mirror"],note:"the codec covenant.js requires the first time it decodes"},{src:"covenant/aegis.seal",shapes:["mirror","nested"],note:"the sealed covenant (AES/1 container) — path shape is load-bearing"},{src:"covenant/README.md",shapes:["mirror","nested"],note:"the decode notice shipped beside the artifact"},{src:"tools/agent-gate.mjs",shapes:["mirror","flat"],note:"the in-process half of the lock; without it a packaged app had NO gate"}];export function entriesFor(e){const s=[];for(const t of MANIFEST){if(!t.shapes.includes(e))continue;let o;if("mirror"===e)o=r.join(CLI_VENDOR,t.src);else if("flat"===e)o=r.join(DESKTOP_VENDOR,r.basename(t.src));else{if("nested"!==e)throw new Error(`predist: unknown shape ${e}`);o=r.join(DESKTOP_VENDOR,t.src)}s.push({src:t.src,dest:o,from:r.join(REPO_DIR,t.src)})}return s}export const SHAPES=["mirror","flat","nested"];const c=[["cli",CLI_DIR,["bin","src","vendor","scripts","package.json","README.md","LICENSE"]],["desktop",DESKTOP_DIR,["main.js","preload.js","lib","renderer","bin","vendor","package.json","README.md"]]],l=new Set(["node_modules","release",".git",".cache","out"]);function d(s,t){const o=e=>l.has(e)||e.endsWith(".log"),n=(s,t)=>{if(e.mkdirSync(r.dirname(t),{recursive:!0}),e.copyFileSync(s,t),!e.readFileSync(s).equals(e.readFileSync(t)))throw new Error(`predist: bundle copy differs from source: ${r.relative(REPO_DIR,s)}`)},i=(s,a)=>{const c=e.lstatSync(s);if(!c.isSymbolicLink())if(c.isFile())n(s,r.join(t,a));else for(const t of e.readdirSync(s))o(t)||i(r.join(s,t),a?r.join(a,t):t)};e.lstatSync(s).isFile()?n(s,t):i(s,"")}const p=12e4,h=6e5,u=50,m="AEGISONE_PREDIST_LOCK_TOKEN";let f=null,g=!1,j=0;function y(e){try{return process.kill(e,0),!0}catch(e){return Boolean(e)&&"EPERM"===e.code}}const v=e=>new Promise((r=>setTimeout(r,e)));function b(){if(j>0)return void j--;const r=f,s=g,t=process.env[m];if(f=null,g=!1,r&&s){t&&delete process.env[m];try{e.unlinkSync(r)}catch{}}}export async function acquireStageLock(s){if(f)return j++,b;const t=s&&s.stdout||process.stdout;return await async function(s){const t=function(){const s=r.join(REPO_DIR,".git");let t=s;try{if(!e.lstatSync(s).isDirectory()){const o=/^gitdir:\s*(.+)$/m.exec(e.readFileSync(s,"utf8"));o&&(t=r.resolve(REPO_DIR,o[1].trim()))}}catch{t=s}return r.join(t,"aegisone-predist.lock")}(),o=Date.now()+p,n=process.env[m]||null;let i=null,a=!1;for(;;){if(n)try{const r=String(e.readFileSync(t,"utf8")).split("\n")[1];if(r&&r.trim()===n)return f=t,void(g=!1)}catch{}try{i=`${Date.now().toString(36)}-${process.pid}-${Math.random().toString(36).slice(2,10)}`;const r=e.openSync(t,"wx");return e.writeSync(r,`${process.pid}\n${i}\n`),e.closeSync(r),f=t,g=!0,void(process.env[m]=i)}catch(e){if(!e||"EEXIST"!==e.code)throw e}let r=null,c=0;try{r=e.statSync(t),c=Number(String(e.readFileSync(t,"utf8")).split("\n")[0].trim())}catch{continue}if(Date.now()-r.mtimeMs>h||Number.isFinite(c)&&c>0&&!y(c)){s(`predist: breaking an abandoned staging lock (pid ${c||"unknown"})`);try{e.unlinkSync(t)}catch{}}else{if(Date.now()>o)throw new Error(`predist: another stager (pid ${c||"unknown"}) has held ${t} for over ${Math.round(p/1e3)}s. Staging is destructive — it removes and rewrites cli/vendor, desktop/vendor and one/vendor — so it will not run concurrently with a peer. Wait for it, or delete the lock if that process is gone.`);a||(a=!0,s(`predist: another stager (pid ${c||"unknown"}) is running — waiting for it (concurrent staging would read a vendor tree the peer is rewriting)`)),await v(u+Math.floor(Math.random()*u))}}}((e=>t.write(`${e}\n`))),b}function w(s,t){t&&e.rmSync(t,{recursive:!0,force:!0});const o=[];for(const t of s){if(!e.existsSync(t.from))throw new Error(`predist: missing shared module: ${t.src} (expected at ${t.from})`);if(e.mkdirSync(r.dirname(t.dest),{recursive:!0}),e.copyFileSync(t.from,t.dest),!e.readFileSync(t.from).equals(e.readFileSync(t.dest)))throw new Error(`predist: staged copy differs from source: ${t.src}`);o.push(t)}return o}export async function stage(t){const n=t||{},i=n.io||{},l=i.stdout||process.stdout,p=(i.stderr||process.stderr,Array.isArray(n.shapes)?n.shapes:[...SHAPES,"bundle"]),h=e=>p.includes(e),u=e=>l.write(`${e}\n`),m=await acquireStageLock(i);try{return await async function({want:t,log:n}){const i={mirror:null,flat:null,nested:null,bundle:null};if(t("mirror")){const e=w(entriesFor("mirror"),CLI_VENDOR);n(`predist: staged ${e.length} shared modules into cli/vendor/`);for(const r of e)n(` ${r.src} -> vendor/${r.src}`);i.mirror={staged:e.length}}if(t("nested")&&(i.nested={staged:w(entriesFor("nested"),null).length}),t("flat")){const e=w(entriesFor("flat"),null);for(const r of e)n(`staged ${r.dest}`);i.flat={staged:e.length}}if(t("mirror")&&t("flat"))for(const s of MANIFEST){if(!s.shapes.includes("mirror")||!s.shapes.includes("flat"))continue;const t=r.join(CLI_VENDOR,s.src),o=r.join(DESKTOP_VENDOR,r.basename(s.src));if(!e.readFileSync(t).equals(e.readFileSync(o)))throw new Error(`predist: the two shapes disagree for ${s.src}`)}if(t("mirror")){const s=function(s){const t=r.join(CLI_VENDOR,"mcp","tools.js");delete a.cache[a.resolve(t)];const{createTools:o}=a(t),n=o({apiBase:"http://127.0.0.1",apiKey:"predist-probe",randomUUID:()=>"id"}).toolList().length;if(0===n)throw new Error("predist: staged registry exposes no tools");const i=a("node:vm"),c=r.join(CLI_VENDOR,"mcp","server.js");new i.Script(e.readFileSync(c,"utf8"),{filename:c});const l=r.join(CLI_VENDOR,"hosts"),d=a(r.join(l,"spec.js")),p=a(r.join(l,"install.js")),h=a(r.join(l,"targets.js")),u=d.resolveServer({AEGIS_MCP_SERVER:""});if(!u.exists||u.path!==c)throw new Error(`predist: staged hosts/spec.js resolves the server as ${u.path} (exists: ${u.exists}), expected ${c}. An installed aegiscode would write editor configs pointing at a file the package never shipped. Candidates were:\n ${u.candidates.join("\n ")}`);const m=h.getTarget("vscode"),f=p.planTarget(m,"user",{ctx:p.hostCtx({home:r.join(CLI_VENDOR,".predist-home"),env:{},cwd:REPO_DIR}),specOpts:{env:{AEGIS_MCP_SERVER:""}}}),g=JSON.stringify(f.after||"");if(f.error||!f.changed||!g.includes(JSON.stringify(c).slice(1,-1)))throw new Error(`predist: a planned vscode install does not name the staged server (error: ${f.error&&f.error.message}, changed: ${f.changed})`);if("function"!=typeof a(r.join(l,"openai-shim.js")).createShimServer)throw new Error("predist: staged hosts/openai-shim.js exposes no createShimServer");return{count:n,targets:h.targetIds().length,staged:s.length}}(entriesFor("mirror"));n(`predist: staged registry loads standalone (${s.count} tools)`),n(`predist: editor layer verified (${s.targets} host targets, server resolves to vendor/mcp/server.js, shim loads)`);const t=await async function(){const e=r.join(CLI_VENDOR,"tools","agent-gate.mjs");if("function"!=typeof(await import(o(e).href)).run)throw new Error("predist: staged tools/agent-gate.mjs exposes no run()");return e}();n(`predist: ${r.relative(REPO_DIR,t)} loads standalone and exposes run()`),i.mirror.proof=s}if(t("flat")){const s=function(s){const t=new Set(s.map((e=>r.basename(e.dest))));for(const o of s){const s=e.readFileSync(o.dest,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1");for(const e of s.matchAll(/require\(\s*'((?:\.\.?\/)[^']+)'\s*\)/g)){const s=e[1];if(r.basename(s).replace(/\.[cm]?js$/,""),s.replace(/^\.\//,"").startsWith("../"))throw new Error(`predist: flat-staged ${r.basename(o.dest)} requires '${s}', which escapes vendor/ — flattening only works for same-directory requires (add the target to the manifest, or stop staging this file flat)`);const n=s.replace(/^\.\//,"");if(!t.has(n))throw new Error(`predist: flat-staged ${r.basename(o.dest)} requires '${s}', which is not staged into desktop/vendor/ — the packaged app would throw MODULE_NOT_FOUND before the window could open`)}}const o=a(r.join(DESKTOP_VENDOR,"aegis.js"));if(!o||0===Object.keys(o).length)throw new Error("predist: staged desktop/vendor/aegis.js loads but exports nothing");return{files:s.length,exports:Object.keys(o).length}}(entriesFor("flat"));n(`predist: flattened tree is self-contained (${s.files} files, ${s.exports} transport exports) — no staged module escapes vendor/`),i.flat.proof=s}if(t("bundle")){for(const[s,t,o]of c){const i=r.join(ONE_VENDOR,s);e.rmSync(i,{recursive:!0,force:!0});for(const s of o){const o=r.join(t,s);if(!e.existsSync(o)){if("LICENSE"===s||"README.md"===s)continue;throw new Error(`predist: bundle source missing: ${r.relative(REPO_DIR,o)}`)}d(o,r.join(i,s))}n(`staged the ${s} face into one/vendor/${s}/`)}const t=function(){const t=r.join(ONE_VENDOR,"cli"),o=r.join(t,"src","deps.js"),n=s(process.execPath,["-e","const d=require(process.argv[1]);console.log(JSON.stringify(d.paths))",o],{cwd:t,encoding:"utf8"});if(0!==n.status)throw new Error(`predist: the bundled CLI does not load: ${n.stderr||n.stdout}`);const i=JSON.parse(n.stdout),a=[];let l=0;for(const[e,s]of Object.entries(i)){const t=r.relative(ONE_VENDOR,s);t.startsWith("..")||r.isAbsolute(t)?a.push(`${e} -> ${s}`):"cli"!==t.split(r.sep)[0]&&l++}if(a.length)throw new Error(`predist: the bundled CLI resolves these shared modules OUTSIDE the bundle (${ONE_VENDOR}) — the product tarball would depend on a repo checkout:\n `+a.join("\n "));if(!e.existsSync(r.join(t,"bin","aegiscode.js")))throw new Error("predist: the bundle has no cli/bin/aegiscode.js");const d=[];for(const[s,t,o]of c)for(const n of o){const o=r.join(ONE_VENDOR,s,n);let i=null,a=null;try{i=e.lstatSync(r.join(t,n))}catch{continue}try{a=e.lstatSync(o)}catch{d.push(`${s}/${n} -> missing`);continue}i.isFile()&&!a.isFile()&&d.push(`${s}/${n} -> not a regular file`),i.isDirectory()&&!a.isDirectory()&&d.push(`${s}/${n} -> not a directory`)}if(d.length)throw new Error(`predist: the bundle staged these in the wrong shape:\n ${d.join("\n ")}`);return{modules:Object.keys(i).length,inSiblingFace:l}}();n(`predist: the bundled CLI resolves ${t.modules} shared modules from inside one/vendor/ (${t.inSiblingFace} through the bundled desktop face) — no repo checkout needed`),i.bundle=t}return i}({want:h,log:u})}finally{m()}}export async function main(e,r){const s=r||{},t=Array.isArray(e)?e:[],o=t.includes("--quiet")?{write:()=>!0}:s.stdout||process.stdout,n=s.stderr||process.stderr;let i;t.includes("--mirror-only")?i=["mirror"]:t.includes("--flat-only")?i=["flat","nested"]:t.includes("--bundle-only")&&(i=["bundle"]);try{return await stage({shapes:i,io:{stdout:o,stderr:n}}),0}catch(e){return n.write(`${e&&e.message}\n`),1}}!function(){const e=process.argv[1];let s=!1;if(e)try{s=r.resolve(e)===t(import.meta.url)}catch{s=!1}s&&main(process.argv.slice(2)).then((e=>{process.exitCode=e}))}();
4
+ import e from"node:fs";import r from"node:path";import{spawnSync as s}from"node:child_process";import{fileURLToPath as t,pathToFileURL as o}from"node:url";import{createRequire as n}from"node:module";const i=r.dirname(t(import.meta.url)),a=n(import.meta.url);export const ONE_DIR=r.join(i,"..");export const REPO_DIR=r.join(ONE_DIR,"..");export const CLI_DIR=r.join(REPO_DIR,"cli");export const DESKTOP_DIR=r.join(REPO_DIR,"desktop");export const CLI_VENDOR=r.join(CLI_DIR,"vendor");export const DESKTOP_VENDOR=r.join(DESKTOP_DIR,"vendor");export const ONE_VENDOR=r.join(ONE_DIR,"vendor");export const MANIFEST=[{src:"client/aegis.js",shapes:["mirror","flat"],note:"the thin transport — the one implementation of the wire format"},{src:"client/update.js",shapes:["mirror","flat"],note:"the npm update checker (the desktop own update path)"},{src:"client/foreign-memory.js",shapes:["mirror","flat"],note:"required by mcp/tools.js as ../client/foreign-memory.js"},{src:"client/credentials.js",shapes:["mirror","flat"],note:"the account credential store, shared by all three hosts"},{src:"client/session-store.js",shapes:["mirror","flat"],note:"the unified session store — one list in every host"},{src:"client/naming.js",shapes:["mirror","flat"],note:"the conversation-naming ladder — ONE implementation for the terminal and the window (cli/src/naming.js re-exports it)"},{src:"client/prefs.js",shapes:["mirror","flat"],note:"the shared non-secret preference store (D5) — the CLI and the desktop store both read/write it"},{src:"client/env-file.js",shapes:["mirror","flat"],note:"the shared ~/.aegiscode/.env loader, resolved before any key is read"},{src:"client/auto-provision.js",shapes:["mirror","flat"],note:"free device key on first launch; requires ./device-fingerprint.js"},{src:"client/device-fingerprint.js",shapes:["mirror","flat"],note:"the machine identity auto-provision.js and presence.js require"},{src:"client/presence.js",shapes:["mirror","flat"],note:"the heartbeat beacon; requires ./presence-constants.js and ./device-fingerprint.js"},{src:"client/presence-constants.js",shapes:["mirror","flat"],note:"the beacon constants — a package without them loses the beacon silently"},{src:"client/touch.js",shapes:["mirror","flat"],note:"phi(alpha): the digest module fingerprint.js requires as ./touch.js"},{src:"client/fingerprint.js",shapes:["mirror","flat"],note:"phi(alpha): the sealed session record, resolved by src/fingerprint.js"},{src:"client/authorship-key.js",shapes:["mirror","flat"],note:"phi(alpha): the authorship key, required by ./attest.js and ./record-vault.js"},{src:"client/attest.js",shapes:["mirror","flat"],note:"phi(alpha): attestation, requires ./fingerprint.js and ./authorship-key.js"},{src:"client/record-vault.js",shapes:["mirror","flat"],note:"the vault, and its refusal to copy the key with the record"},{src:"client/brain-catalog.js",shapes:["mirror","flat"],note:"the pooled-brain rule, required at load time by the engine and src/models.js"},{src:"client/byok-catalog.js",shapes:["mirror","flat"],note:"the BYOK model additions the server catalog does not name"},{src:"client/catalog-client.js",shapes:["mirror","flat"],note:"the server's cached catalog, layered between the shipped additions and the user's own models"},{src:"client/user-models.js",shapes:["mirror","flat"],note:"the models the USER declares, in one file both hosts read (requires ./credentials.js)"},{src:"client/model-discovery.js",shapes:["mirror","flat"],note:"asks the vendor what it serves, so adding a new model is not a memory test (requires ./user-models.js)"},{src:"client/hooks.js",shapes:["mirror","flat"],note:"the shared hook layer behind /hooks and the repo guard installer"},{src:"client/platform.js",shapes:["mirror","flat"],note:"the ONE place that decides which OS this is (Phase 30.1)"},{src:"client/topup.js",shapes:["mirror","flat"],note:"the token-bank top-up: amount bounds, the balance reading, and the credit watch every host drives"},{src:"client/google-signin.js",shapes:["mirror","flat"],note:"the localhost half of aegis1's desktop Google OAuth round-trip; `connect --google` drives it"},{src:"client/drive-connect.js",shapes:["mirror","flat"],note:"the desktop half of aegis1's Drive OAuth (/connect/drive, /api/drive/token); requires ./aegis.js only via the caller"},{src:"client/drive-upload.js",shapes:["mirror","flat"],note:"the Drive v3 REST wrapper that uploads the memory backup and one conversation per save"},{src:"client/conversation-export.js",shapes:["mirror","flat"],note:"the authorship stamp at the top of every uploaded file, and the two backup scope names"},{src:"mcp/tools.js",shapes:["mirror"],note:"the shared tool registry; requires ../client/foreign-memory.js"},{src:"mcp/server.js",shapes:["mirror"],note:"the stdio MCP server every installed editor config names (compiled, never required)"},{src:"hosts/spec.js",shapes:["mirror"],note:"the canonical server spec, staged under its own directory so it finds vendor/mcp/server.js"},{src:"hosts/targets.js",shapes:["mirror"],note:"the editor target registry"},{src:"hosts/install.js",shapes:["mirror"],note:"the merge-only installer behind aegiscode mcp install"},{src:"hosts/openai-shim.js",shapes:["mirror"],note:"the loopback OpenAI-compatible shim"},{src:"desktop/renderer/usage.js",shapes:["mirror"],note:"the pure usage mapping shared by the window and the terminal"},{src:"desktop/lib/local/engine.js",shapes:["mirror"],note:"the agent loop, reused as-is (one loop, not a second one drifting)"},{src:"desktop/lib/local/claude-pro.js",shapes:["mirror"],note:"the Claude Code Pro transport; requires ./../../one/src/child.js at call time"},{src:"one/src/child.js",shapes:["mirror"],note:"the ONE claude-child argv builder (rule 4); resolved by claude-pro.js at call time"},{src:"one/src/permissions.js",shapes:["mirror"],note:"resolvePosture() — the permission half of the argv, resolved at call time"},{src:"desktop/lib/local/local.js",shapes:["mirror"],note:"the local model transport and its fail-closed base-URL check"},{src:"desktop/lib/local/context.js",shapes:["mirror"],note:"the token-budget trimmer local.js requires at load"},{src:"desktop/lib/local/attachments.js",shapes:["mirror"],note:"content-part builder for dropped files; required at load by engine.js and local.js"},{src:"desktop/lib/local/session-rounds.js",shapes:["mirror"],note:"interrupted-turn bookkeeping; required at load by engine.js"},{src:"desktop/lib/local/tools.js",shapes:["mirror"],note:"the tool implementations (persistent shell, editFile, grep, exec)"},{src:"desktop/lib/local/shell.js",shapes:["mirror"],note:"the persistent shell, required by tools.js"},{src:"desktop/lib/local/integrity.js",shapes:["mirror"],note:"the desktop second gate; required at load by shell.js and tools.js, and the seal over its own four units"},{src:"desktop/main.js",shapes:["mirror"],bytesOnly:!0,note:"seal unit d1 — hashed by integrity.js as BYTES and never required from the mirror, so its own requires (the whole Electron main-process closure) are not staged behind it"},{src:"desktop/lib/local/spill.js",shapes:["mirror"],note:"oversized-output spill, required at load by tools.js and shell.js"},{src:"desktop/lib/local/exec-plan.js",shapes:["mirror"],note:"exec one-shot eligibility classifier, required at load by engine.js"},{src:"desktop/lib/local/agents.js",shapes:["mirror"],note:"Task subagents"},{src:"desktop/lib/local/prompt.js",shapes:["mirror"],note:"the system prompt builder"},{src:"desktop/lib/settings.js",shapes:["mirror"],note:"the provider-config store (base URL + key per provider)"},{src:"desktop/lib/local/turn-guard.js",shapes:["mirror"],note:"engine.js requires it at load; it requires ./git-scope.js"},{src:"desktop/lib/local/worktree-lock.js",shapes:["mirror"],note:"engine.js requires it at load"},{src:"desktop/lib/local/git-scope.js",shapes:["mirror"],note:"the write-scope rule turn-guard.js and the queues share"},{src:"desktop/lib/local/queue.js",shapes:["mirror"],note:"the autonomous work queue"},{src:"desktop/lib/local/autonomous.js",shapes:["mirror"],note:"the unattended worker; requires ./queue.js and ./git-scope.js"},{src:"desktop/lib/local/entitlement.js",shapes:["mirror"],note:"the shared Pro gate (account probe injected by the caller)"},{src:"desktop/lib/local/covenant.js",shapes:["mirror"],note:"the pre-action gate engine.js requires unconditionally at load"},{src:"desktop/lib/local/aegis-seal.mjs",shapes:["mirror"],note:"the codec covenant.js requires the first time it decodes"},{src:"covenant/aegis.seal",shapes:["mirror","nested"],note:"the sealed covenant (AES/1 container) — path shape is load-bearing"},{src:"covenant/README.md",shapes:["mirror","nested"],note:"the decode notice shipped beside the artifact"},{src:"tools/agent-gate.mjs",shapes:["mirror","flat"],note:"the in-process half of the lock; without it a packaged app had NO gate"}];export function entriesFor(e){const s=[];for(const t of MANIFEST){if(!t.shapes.includes(e))continue;let o;if("mirror"===e)o=r.join(CLI_VENDOR,t.src);else if("flat"===e)o=r.join(DESKTOP_VENDOR,r.basename(t.src));else{if("nested"!==e)throw new Error(`predist: unknown shape ${e}`);o=r.join(DESKTOP_VENDOR,t.src)}s.push({src:t.src,dest:o,from:r.join(REPO_DIR,t.src)})}return s}export const SHAPES=["mirror","flat","nested"];const c=[["cli",CLI_DIR,["bin","src","vendor","scripts","package.json","README.md","LICENSE"]],["desktop",DESKTOP_DIR,["main.js","preload.js","lib","renderer","bin","vendor","package.json","README.md"]]],l=new Set(["node_modules","release",".git",".cache","out"]);function d(s,t){const o=e=>l.has(e)||e.endsWith(".log"),n=(s,t)=>{if(e.mkdirSync(r.dirname(t),{recursive:!0}),e.copyFileSync(s,t),!e.readFileSync(s).equals(e.readFileSync(t)))throw new Error(`predist: bundle copy differs from source: ${r.relative(REPO_DIR,s)}`)},i=(s,a)=>{const c=e.lstatSync(s);if(!c.isSymbolicLink())if(c.isFile())n(s,r.join(t,a));else for(const t of e.readdirSync(s))o(t)||i(r.join(s,t),a?r.join(a,t):t)};e.lstatSync(s).isFile()?n(s,t):i(s,"")}const p=12e4,h=6e5,u=50,m="AEGISONE_PREDIST_LOCK_TOKEN";let f=null,g=!1,j=0;function y(e){try{return process.kill(e,0),!0}catch(e){return Boolean(e)&&"EPERM"===e.code}}const v=e=>new Promise((r=>setTimeout(r,e)));function b(){if(j>0)return void j--;const r=f,s=g,t=process.env[m];if(f=null,g=!1,r&&s){t&&delete process.env[m];try{e.unlinkSync(r)}catch{}}}export async function acquireStageLock(s){if(f)return j++,b;const t=s&&s.stdout||process.stdout;return await async function(s){const t=function(){const s=r.join(REPO_DIR,".git");let t=s;try{if(!e.lstatSync(s).isDirectory()){const o=/^gitdir:\s*(.+)$/m.exec(e.readFileSync(s,"utf8"));o&&(t=r.resolve(REPO_DIR,o[1].trim()))}}catch{t=s}return r.join(t,"aegisone-predist.lock")}(),o=Date.now()+p,n=process.env[m]||null;let i=null,a=!1;for(;;){if(n)try{const r=String(e.readFileSync(t,"utf8")).split("\n")[1];if(r&&r.trim()===n)return f=t,void(g=!1)}catch{}try{i=`${Date.now().toString(36)}-${process.pid}-${Math.random().toString(36).slice(2,10)}`;const r=e.openSync(t,"wx");return e.writeSync(r,`${process.pid}\n${i}\n`),e.closeSync(r),f=t,g=!0,void(process.env[m]=i)}catch(e){if(!e||"EEXIST"!==e.code)throw e}let r=null,c=0;try{r=e.statSync(t),c=Number(String(e.readFileSync(t,"utf8")).split("\n")[0].trim())}catch{continue}if(Date.now()-r.mtimeMs>h||Number.isFinite(c)&&c>0&&!y(c)){s(`predist: breaking an abandoned staging lock (pid ${c||"unknown"})`);try{e.unlinkSync(t)}catch{}}else{if(Date.now()>o)throw new Error(`predist: another stager (pid ${c||"unknown"}) has held ${t} for over ${Math.round(p/1e3)}s. Staging is destructive — it removes and rewrites cli/vendor, desktop/vendor and one/vendor — so it will not run concurrently with a peer. Wait for it, or delete the lock if that process is gone.`);a||(a=!0,s(`predist: another stager (pid ${c||"unknown"}) is running — waiting for it (concurrent staging would read a vendor tree the peer is rewriting)`)),await v(u+Math.floor(Math.random()*u))}}}((e=>t.write(`${e}\n`))),b}function w(s,t){t&&e.rmSync(t,{recursive:!0,force:!0});const o=[];for(const t of s){if(!e.existsSync(t.from))throw new Error(`predist: missing shared module: ${t.src} (expected at ${t.from})`);if(e.mkdirSync(r.dirname(t.dest),{recursive:!0}),e.copyFileSync(t.from,t.dest),!e.readFileSync(t.from).equals(e.readFileSync(t.dest)))throw new Error(`predist: staged copy differs from source: ${t.src}`);o.push(t)}return o}export async function stage(t){const n=t||{},i=n.io||{},l=i.stdout||process.stdout,p=(i.stderr||process.stderr,Array.isArray(n.shapes)?n.shapes:[...SHAPES,"bundle"]),h=e=>p.includes(e),u=e=>l.write(`${e}\n`),m=await acquireStageLock(i);try{return await async function({want:t,log:n}){const i={mirror:null,flat:null,nested:null,bundle:null};if(t("mirror")){const e=w(entriesFor("mirror"),CLI_VENDOR);n(`predist: staged ${e.length} shared modules into cli/vendor/`);for(const r of e)n(` ${r.src} -> vendor/${r.src}`);i.mirror={staged:e.length}}if(t("nested")&&(i.nested={staged:w(entriesFor("nested"),null).length}),t("flat")){const e=w(entriesFor("flat"),null);for(const r of e)n(`staged ${r.dest}`);i.flat={staged:e.length}}if(t("mirror")&&t("flat"))for(const s of MANIFEST){if(!s.shapes.includes("mirror")||!s.shapes.includes("flat"))continue;const t=r.join(CLI_VENDOR,s.src),o=r.join(DESKTOP_VENDOR,r.basename(s.src));if(!e.readFileSync(t).equals(e.readFileSync(o)))throw new Error(`predist: the two shapes disagree for ${s.src}`)}if(t("mirror")){const s=function(s){const t=r.join(CLI_VENDOR,"mcp","tools.js");delete a.cache[a.resolve(t)];const{createTools:o}=a(t),n=o({apiBase:"http://127.0.0.1",apiKey:"predist-probe",randomUUID:()=>"id"}).toolList().length;if(0===n)throw new Error("predist: staged registry exposes no tools");const i=a("node:vm"),c=r.join(CLI_VENDOR,"mcp","server.js");new i.Script(e.readFileSync(c,"utf8"),{filename:c});const l=r.join(CLI_VENDOR,"hosts"),d=a(r.join(l,"spec.js")),p=a(r.join(l,"install.js")),h=a(r.join(l,"targets.js")),u=d.resolveServer({AEGIS_MCP_SERVER:""});if(!u.exists||u.path!==c)throw new Error(`predist: staged hosts/spec.js resolves the server as ${u.path} (exists: ${u.exists}), expected ${c}. An installed aegiscode would write editor configs pointing at a file the package never shipped. Candidates were:\n ${u.candidates.join("\n ")}`);const m=h.getTarget("vscode"),f=p.planTarget(m,"user",{ctx:p.hostCtx({home:r.join(CLI_VENDOR,".predist-home"),env:{},cwd:REPO_DIR}),specOpts:{env:{AEGIS_MCP_SERVER:""}}}),g=JSON.stringify(f.after||"");if(f.error||!f.changed||!g.includes(JSON.stringify(c).slice(1,-1)))throw new Error(`predist: a planned vscode install does not name the staged server (error: ${f.error&&f.error.message}, changed: ${f.changed})`);if("function"!=typeof a(r.join(l,"openai-shim.js")).createShimServer)throw new Error("predist: staged hosts/openai-shim.js exposes no createShimServer");return{count:n,targets:h.targetIds().length,staged:s.length}}(entriesFor("mirror"));n(`predist: staged registry loads standalone (${s.count} tools)`),n(`predist: editor layer verified (${s.targets} host targets, server resolves to vendor/mcp/server.js, shim loads)`);const t=await async function(){const e=r.join(CLI_VENDOR,"tools","agent-gate.mjs");if("function"!=typeof(await import(o(e).href)).run)throw new Error("predist: staged tools/agent-gate.mjs exposes no run()");return e}();n(`predist: ${r.relative(REPO_DIR,t)} loads standalone and exposes run()`),i.mirror.proof=s}if(t("flat")){const s=function(s){const t=new Set(s.map((e=>r.basename(e.dest))));for(const o of s){const s=e.readFileSync(o.dest,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1");for(const e of s.matchAll(/require\(\s*'((?:\.\.?\/)[^']+)'\s*\)/g)){const s=e[1];if(r.basename(s).replace(/\.[cm]?js$/,""),s.replace(/^\.\//,"").startsWith("../"))throw new Error(`predist: flat-staged ${r.basename(o.dest)} requires '${s}', which escapes vendor/ — flattening only works for same-directory requires (add the target to the manifest, or stop staging this file flat)`);const n=s.replace(/^\.\//,"");if(!t.has(n))throw new Error(`predist: flat-staged ${r.basename(o.dest)} requires '${s}', which is not staged into desktop/vendor/ — the packaged app would throw MODULE_NOT_FOUND before the window could open`)}}const o=a(r.join(DESKTOP_VENDOR,"aegis.js"));if(!o||0===Object.keys(o).length)throw new Error("predist: staged desktop/vendor/aegis.js loads but exports nothing");return{files:s.length,exports:Object.keys(o).length}}(entriesFor("flat"));n(`predist: flattened tree is self-contained (${s.files} files, ${s.exports} transport exports) — no staged module escapes vendor/`),i.flat.proof=s}if(t("bundle")){for(const[s,t,o]of c){const i=r.join(ONE_VENDOR,s);e.rmSync(i,{recursive:!0,force:!0});for(const s of o){const o=r.join(t,s);if(!e.existsSync(o)){if("LICENSE"===s||"README.md"===s)continue;throw new Error(`predist: bundle source missing: ${r.relative(REPO_DIR,o)}`)}d(o,r.join(i,s))}n(`staged the ${s} face into one/vendor/${s}/`)}const t=function(){const t=r.join(ONE_VENDOR,"cli"),o=r.join(t,"src","deps.js"),n=s(process.execPath,["-e","const d=require(process.argv[1]);console.log(JSON.stringify(d.paths))",o],{cwd:t,encoding:"utf8"});if(0!==n.status)throw new Error(`predist: the bundled CLI does not load: ${n.stderr||n.stdout}`);const i=JSON.parse(n.stdout),a=[];let l=0;for(const[e,s]of Object.entries(i)){const t=r.relative(ONE_VENDOR,s);t.startsWith("..")||r.isAbsolute(t)?a.push(`${e} -> ${s}`):"cli"!==t.split(r.sep)[0]&&l++}if(a.length)throw new Error(`predist: the bundled CLI resolves these shared modules OUTSIDE the bundle (${ONE_VENDOR}) — the product tarball would depend on a repo checkout:\n `+a.join("\n "));if(!e.existsSync(r.join(t,"bin","aegiscode.js")))throw new Error("predist: the bundle has no cli/bin/aegiscode.js");const d=[];for(const[s,t,o]of c)for(const n of o){const o=r.join(ONE_VENDOR,s,n);let i=null,a=null;try{i=e.lstatSync(r.join(t,n))}catch{continue}try{a=e.lstatSync(o)}catch{d.push(`${s}/${n} -> missing`);continue}i.isFile()&&!a.isFile()&&d.push(`${s}/${n} -> not a regular file`),i.isDirectory()&&!a.isDirectory()&&d.push(`${s}/${n} -> not a directory`)}if(d.length)throw new Error(`predist: the bundle staged these in the wrong shape:\n ${d.join("\n ")}`);return{modules:Object.keys(i).length,inSiblingFace:l}}();n(`predist: the bundled CLI resolves ${t.modules} shared modules from inside one/vendor/ (${t.inSiblingFace} through the bundled desktop face) — no repo checkout needed`),i.bundle=t}return i}({want:h,log:u})}finally{m()}}export async function main(e,r){const s=r||{},t=Array.isArray(e)?e:[],o=t.includes("--quiet")?{write:()=>!0}:s.stdout||process.stdout,n=s.stderr||process.stderr;let i;t.includes("--mirror-only")?i=["mirror"]:t.includes("--flat-only")?i=["flat","nested"]:t.includes("--bundle-only")&&(i=["bundle"]);try{return await stage({shapes:i,io:{stdout:o,stderr:n}}),0}catch(e){return n.write(`${e&&e.message}\n`),1}}!function(){const e=process.argv[1];let s=!1;if(e)try{s=r.resolve(e)===t(import.meta.url)}catch{s=!1}s&&main(process.argv.slice(2)).then((e=>{process.exitCode=e}))}();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.22",
4
+ "version": "7.0.24",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const path=require("node:path"),PREVIEW_LINES=8,PREVIEW_LINES_EXPANDED=30,LANGUAGE_BY_EXT={".js":"javascript",".ts":"typescript",".tsx":"typescript",".jsx":"javascript",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".c":"c",".cpp":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".php":"php",".html":"html",".htm":"html",".css":"css",".scss":"scss",".json":"json",".yaml":"yaml",".yml":"yaml",".xml":"xml",".md":"markdown",".sh":"bash",".bash":"bash",".sql":"sql",".lua":"lua",".swift":"swift",".kt":"kotlin"};function extractPreview(e,t,s=8){if(!e||"string"!=typeof t)return null;const r=path.extname(e).toLowerCase(),n=LANGUAGE_BY_EXT[r]||"",i=t.split("\n"),l=i.length>s;return{file:e,language:n,lines:i.slice(0,s),totalLines:i.length,truncated:l}}function renderFilePreview(e,t,s=80){if(!e)return[];const{RESET:r,BOLD:n,DIM:i}=require("./theme.js"),l=require("./theme.js").themeOf(t),{clip:a}=require("./screen.js"),c=[],o=`${n}${a(e.file,Math.max(20,s-20))}${r} ${i}(${e.totalLines} line${1===e.totalLines?"":"s"})${r}`;c.push(` ${l.gold}┌─ ${o}`);const p=String(e.totalLines).length;for(let t=0;t<e.lines.length;t++){const n=String(t+1).padStart(p," "),o=a(e.lines[t]||"",Math.max(8,s-p-10)),h=`${l.gray}${n}${r} ${i}│${r}`;c.push(` ${h} ${o}`)}if(e.truncated){const t=e.totalLines-e.lines.length,s=`${t} more line${1===t?"":"s"} — press 'v' to view full`;c.push(` ${l.gray}└─ ${i}${s}${r}`)}else c.push(` ${l.gray}└─${r}`);return c}function extractNewContent(e,t){return!t||"object"!=typeof t||"Write"!==e&&"writeFile"!==e?null:t.content}module.exports={extractPreview:extractPreview,renderFilePreview:renderFilePreview,extractNewContent:extractNewContent,PREVIEW_LINES:8,PREVIEW_LINES_EXPANDED:30};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),o=i(t);if(!n||!o)return!1;if(n===o)return!0;if(o.length<=14&&(n.startsWith(o)||o.startsWith(n)))return!0;if(o.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!ECHO_STOP.has(e)))),n=i(e),o=i(t);if(n.size&&n.size===o.size&&[...n].every((e=>o.has(e))))return!0}return!1}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let o=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return o?(o=o[0].toUpperCase()+o.slice(1),o.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const o=cleanTitle(e);if(o)return looksLikeEcho(o,n)?GENERIC_TITLE:o}return deriveTitle(n)}async function refineTitle(e,t,i={}){if(!isGenericTitle(e))return null;if(!String(t||"").trim()||isTopicless(t))return null;const n=cleanTitle(await nameConversation(t,i));return!n||isGenericTitle(n)?null:n}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),CANDIDATES=[path.join(__dirname,"..","..","client","naming.js"),path.join(__dirname,"..","vendor","client","naming.js"),path.join(__dirname,"..","vendor","naming.js")];let resolved=null;for(const e of CANDIDATES)if(fs.existsSync(e)){resolved=e;break}if(!resolved)throw new Error("aegiscode: cannot find client/naming.js. Expected it beside cli/ (in the repo) or under cli/vendor/ (installed package). Reinstall the package, or run `node scripts/predist.mjs` from cli/ if this is a source checkout.");module.exports=require(resolved);
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{RGB:RGB,BG:BG,RESET:RESET,BOLD:BOLD,DIM:DIM,ITALIC:ITALIC,UNDER:UNDER,RESET_FG:RESET_FG,RESET_BG:RESET_BG,GLYPH:GLYPH,VERBS:VERBS,DONE_VERBS:DONE_VERBS,themeOf:themeOf}=require("./theme.js"),{WELCOME_TITLE:WELCOME_TITLE,WELCOME_BACK:WELCOME_BACK,TAGLINE:TAGLINE,STAR:STAR,stencilGlyph:stencilGlyph,welcomeArtParts:welcomeArtParts}=require("./art.js"),{w:w,pad:pad,padStart:padStart,wrapBlock:wrapBlock,clip:clip,span:span}=require("./screen.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,feeBillable:feeBillable}=require("./format.js"),{renderDiffBlock:renderDiffBlock}=require("./diffview.js");let markdown=null;try{markdown=require("./markdown.js")}catch{markdown=null}const errMark=()=>GLYPH.err,warnMark=()=>GLYPH.warn,fg=(e,t)=>`${t}`,bg=e=>BG(...e),spansToString=e=>e.map((e=>(e.s||"")+e.t)).join("")+RESET;function centerStyled(e,t,r){const n=clip(e,t),s=Math.max(0,Math.floor((t-w(n))/2));return" ".repeat(s)+r+n+RESET}function tintWhale(e,t){const r={"▓":t.blue,"▒":t.lavender,"░":t.dim,"█":t.white,[STAR]:t.gold,"·":t.dim},n={};for(const e of Object.keys(r))n[stencilGlyph(e)]=r[e];const s=[];let o=null,a="";for(const t of e){const e=null!=n[t]?n[t]:"";null!==o&&e===a?o+=t:(null!==o&&s.push(span(a,o)),o=t,a=e)}return null!==o&&s.push(span(a,o)),s}function artRow(e,t,r,n){const s=themeOf(e),o=t[0]||"",a=t[1]||"",l=[span(""," ".repeat(n))];return o&&a?(l.push(span(s.gold,o)),l.push(span(""," ".repeat(r.gutter))),l.push(...tintWhale(a,s))):o?(l.push(span(s.gold,o)),w(o)<r.width&&l.push(span(""," ".repeat(r.width-w(o))))):a?(l.push(...tintWhale(a,s)),w(a)<r.width&&l.push(span(""," ".repeat(r.width-w(a))))):l.push(span(""," ".repeat(r.width))),spansToString(l)}function renderBanner(e,t={}){const r=themeOf(e),n=Math.max(20,Number(t.width)||80),s=[];s.push(`${r.gold}${GLYPH.ruleHeavy}${GLYPH.rule.repeat(Math.max(0,n-2))}${GLYPH.ruleHeavy}${RESET}`),s.push("");const o=welcomeArtParts();if(n>=o.width+2){const t=Math.max(0,Math.floor((n-o.width)/2));for(const r of o.rows)s.push(artRow(e,r,o,t))}else s.push(centerStyled("AEGIS CODE",n,r.gold+BOLD));s.push("");const a=!1===t.firstRun?WELCOME_BACK:WELCOME_TITLE;s.push(centerStyled(a,n,r.coral+BOLD));const l=[t.version?`v${t.version}`:null,TAGLINE].filter(Boolean).join(` ${GLYPH.bullet} `);return s.push(centerStyled(l,n,r.gray)),s.push(""),s.push(...renderIdentityBox(e,t,n)),s}function renderIdentityBox(e,t={},r=80){const n=themeOf(e),s=[renderHeading(e,"aegiscode",r)],o=[["version",t.version?`v${t.version}`:null],["model",t.model||"server default"],["base",t.base||""],["key",t.key||"not set"],["render",!1===t.stream?"buffered":"streaming"]].filter((([,e])=>e));for(const[e,t]of o){const o=clip(String(t),Math.max(0,r-12));s.push(` ${n.gray}${e.padEnd(8)}${RESET}${n.white}${o}${RESET}`)}const a=clip(` type /help for commands ${GLYPH.bullet} /quit to exit`,r);return s.push(""),s.push(`${n.dim}${a}${RESET}`),s}function mdLines(e,t,r){const n=themeOf(r),s=[];let o=!1;const a=Math.max(20,t-4);for(const t of String(null==e?"":e).split("\n")){if(/^\s*```/.test(t)){o=!o;continue}if(o){for(const e of wrapBlock(t,a))s.push(`${n.gray} ${e}${RESET}`);continue}if(""===t.trim()){s.push("");continue}const e=/^(\s*)[-*]\s+(.*)$/.exec(t);if(e){const t=" ".repeat(Math.min(6,e[1].length));for(const o of wrapBlock(inline(e[2],r),a-2))s.push(`${t}${n.gray}${GLYPH.bullet}${RESET} ${o}`);continue}const l=/^(#{1,6})\s+(.*)$/.exec(t);if(l)s.push(`${n.gold}${BOLD}${inline(l[2],r)}${RESET}`);else for(const e of wrapBlock(inline(t,r),a,""))s.push(e)}return s}function inline(e,t){const r=themeOf(t);return String(null==e?"":e).replace(/`([^`]+)`/g,((e,t)=>`${r.green}${t}${RESET}`)).replace(/\*\*([^*]+)\*\*/g,((e,t)=>`${BOLD}${t}${RESET}`))}function assistantLines(e,t,r){return markdown&&"function"==typeof markdown.renderMarkdown?markdown.renderMarkdown(String(null==t?"":t),r,e).map(spansToString):mdLines(t,r,e)}function renderTurn(e,t,r=80){const n=themeOf(e),s=t.role||"assistant",o=String(null==t.text?"":t.text),a=[];if("user"===s)wrapBlock(o,Math.max(8,r-2)).forEach(((e,t)=>{0===t?a.push(`${n.gray}${GLYPH.cursor}${RESET} ${n.white}${e}${RESET}`):a.push(` ${n.white}${e}${RESET}`)}));else if("assistant"===s||"system"===s){const t=assistantLines(e,o,Math.max(8,r-2));t.length||t.push(""),t[0]=`${n.white}${GLYPH.block}${RESET} `+t[0],a.push(...t)}else if("tool"===s){const s=void 0===t.ok?"":t.ok?` ${n.green}${GLYPH.check}${RESET}`:` ${n.red}${errMark()}${RESET}`;a.push(`${n.gray}${t.label||"tool"}${RESET}${s}`);const o=null==t.args?"":"string"==typeof t.args?t.args:JSON.stringify(t.args);t.diff?a.push(...renderDiffBlock(t.diff,e,r,{open:!!t.diffOpen})):o&&a.push(` ${n.gray}${GLYPH.hook} $ ${clip(o,Math.max(0,r-6))}${RESET}`)}else if("error"===s)a.push(`${n.red}${errMark()} ${o}${RESET}`);else for(const e of wrapBlock(o,Math.max(8,r-2)))a.push(`${n.white}${e}${RESET}`);if(t.meta){const n=renderMeta(e,t.meta,r);n&&a.push(n)}return a}function renderMeta(e,t={},r=80){const n=themeOf(e),s=[];t.model&&s.push(`${n.blue}${t.model}${RESET}`);const o=t.usage&&"object"==typeof t.usage?t.usage:t,a=fmtUsageSplit(o);if(a)s.push(`${n.white}${a.output}${RESET}`);else{const e=displayTokens(o);null!=e&&s.push(`${n.white}${fmtTokens(e)} tokens${RESET}`)}if(null!=t.eur&&feeBillable()&&s.push(`${t.eur>0?n.coral:n.green}${fmtEur(t.eur)}${RESET}`),null!=t.ms&&s.push(`${n.gray}${fmtElapsed(t.ms)}${RESET}`),t.calls>1&&s.push(`${n.gray}${t.calls} calls${RESET}`),!s.length)return"";const l=`${n.dim} ${GLYPH.bullet} ${RESET}`;return`${n.dim}${GLYPH.hook} ${RESET}${s.join(l)}`}function renderStatus(e,t={},r=80){const n=themeOf(e),s=["aegis"];t.model&&s.push(t.model),null!=t.tokens&&s.push(`${fmtTokens(t.tokens)} tokens`),null!=t.spend&&s.push(fmtEur(t.spend)),t.mode&&s.push(t.mode);const o=t.hint||"ctrl+c quit",a=` ${s.join(` ${GLYPH.bullet} `)} `,l=r-w(a)-w(o)-1,i=l>0?a+" ".repeat(l)+o+" ":clip(a,r);return`${n.gray}${pad(i,r)}${RESET}`}function renderWorking(e,t={}){const r=themeOf(e);if(t.done){const e=t.verb||DONE_VERBS[t.tools?1:0]||DONE_VERBS[0],n=null!=t.secs?t.secs:Math.max(1,Math.round((t.elapsedMs||0)/1e3));return`${r.gray}${GLYPH.bloom} ${e} for ${n}s${RESET}`}const n=GLYPH.spin[Math.abs(Math.floor(t.tick||0))%GLYPH.spin.length],s=t.verb||VERBS[0],o=[];null!=t.elapsedMs&&o.push(fmtElapsed(t.elapsedMs)),null!=t.streamed&&o.push(`↓${t.streamedFloor?"≥":""}${fmtTokens(t.streamed)} tokens`);const a=o.length?` ${r.gray}(${o.join(` ${GLYPH.bullet} `)})${RESET}`:"";return`${r.coral}${n}${RESET} ${r.white}${s}${RESET}${r.white}…${RESET}${a}${r.dim} esc to interrupt${RESET}`}function renderHeading(e,t,r=80){const n=themeOf(e),s=` ${t} `,o=Math.max(0,r-w(s)),a=Math.floor(o/2),l=GLYPH.rule;return`${n.gray}${l.repeat(a)}${RESET}${n.gold}${BOLD}${s}${RESET}${n.gray}${l.repeat(Math.max(0,o-a))}${RESET}`}function renderToolResult(e,t,r,n=80){const s=themeOf(e),o=[renderHeading(e,t,n)];for(const e of wrapBlock(String(null==r?"":r),Math.max(8,n-2)))o.push(e?` ${s.white}${e}${RESET}`:"");return o}function renderApproval(e,t={},r=80){const n=themeOf(e),s=[renderHeading(e,`confirm ${t.tool||"tool"}`,r)],o=t.diff?t.diff:null==t.args?"":"string"==typeof t.args?t.args:JSON.stringify(t.args);for(const e of wrapBlock(o,Math.max(8,r-2)))s.push(e?` ${n.gray}${e}${RESET}`:"");return s.push(""),s.push(` ${n.coral}${GLYPH.bullet}${RESET} ${n.white}y${RESET}es once ${n.dim}${GLYPH.bullet}${RESET} ${n.white}s${RESET}ession ${n.dim}${GLYPH.bullet}${RESET} ${n.white}n${RESET}o ${n.dim}(default)${RESET}`),s}const NOTICE={info:["gray",()=>GLYPH.bullet],warn:["coral",warnMark],error:["red",errMark],ok:["green",()=>GLYPH.check]};function renderNotice(e,t,r){const n=themeOf(e),[s,o]=NOTICE[t]||NOTICE.info;return`${n[s]}${o()} ${r}${RESET}`}module.exports={renderBanner:renderBanner,renderIdentityBox:renderIdentityBox,renderTurn:renderTurn,renderMeta:renderMeta,renderStatus:renderStatus,renderWorking:renderWorking,renderHeading:renderHeading,renderToolResult:renderToolResult,renderApproval:renderApproval,renderNotice:renderNotice,mdLines:mdLines,inline:inline,artRow:artRow,tintWhale:tintWhale,fg:fg,bg:bg,UNDER:UNDER,ITALIC:ITALIC,RESET_FG:RESET_FG,RESET_BG:RESET_BG,pad:pad,padStart:padStart};
3
+ "use strict";const{RGB:RGB,BG:BG,RESET:RESET,BOLD:BOLD,DIM:DIM,ITALIC:ITALIC,UNDER:UNDER,RESET_FG:RESET_FG,RESET_BG:RESET_BG,GLYPH:GLYPH,VERBS:VERBS,DONE_VERBS:DONE_VERBS,themeOf:themeOf}=require("./theme.js"),{WELCOME_TITLE:WELCOME_TITLE,WELCOME_BACK:WELCOME_BACK,TAGLINE:TAGLINE,STAR:STAR,stencilGlyph:stencilGlyph,welcomeArtParts:welcomeArtParts}=require("./art.js"),{w:w,pad:pad,padStart:padStart,wrapBlock:wrapBlock,clip:clip,span:span}=require("./screen.js"),{fmtTokens:fmtTokens,fmtEur:fmtEur,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,feeBillable:feeBillable}=require("./format.js"),{renderDiffBlock:renderDiffBlock}=require("./diffview.js"),{extractPreview:extractPreview,renderFilePreview:renderFilePreview,extractNewContent:extractNewContent}=require("./filepreview.js");let markdown=null;try{markdown=require("./markdown.js")}catch{markdown=null}const errMark=()=>GLYPH.err,warnMark=()=>GLYPH.warn,fg=(e,t)=>`${t}`,bg=e=>BG(...e),spansToString=e=>e.map((e=>(e.s||"")+e.t)).join("")+RESET;function centerStyled(e,t,r){const n=clip(e,t),s=Math.max(0,Math.floor((t-w(n))/2));return" ".repeat(s)+r+n+RESET}function tintWhale(e,t){const r={"▓":t.blue,"▒":t.lavender,"░":t.dim,"█":t.white,[STAR]:t.gold,"·":t.dim},n={};for(const e of Object.keys(r))n[stencilGlyph(e)]=r[e];const s=[];let o=null,a="";for(const t of e){const e=null!=n[t]?n[t]:"";null!==o&&e===a?o+=t:(null!==o&&s.push(span(a,o)),o=t,a=e)}return null!==o&&s.push(span(a,o)),s}function artRow(e,t,r,n){const s=themeOf(e),o=t[0]||"",a=t[1]||"",l=[span(""," ".repeat(n))];return o&&a?(l.push(span(s.gold,o)),l.push(span(""," ".repeat(r.gutter))),l.push(...tintWhale(a,s))):o?(l.push(span(s.gold,o)),w(o)<r.width&&l.push(span(""," ".repeat(r.width-w(o))))):a?(l.push(...tintWhale(a,s)),w(a)<r.width&&l.push(span(""," ".repeat(r.width-w(a))))):l.push(span(""," ".repeat(r.width))),spansToString(l)}function renderBanner(e,t={}){const r=themeOf(e),n=Math.max(20,Number(t.width)||80),s=[];s.push(`${r.gold}${GLYPH.ruleHeavy}${GLYPH.rule.repeat(Math.max(0,n-2))}${GLYPH.ruleHeavy}${RESET}`),s.push("");const o=welcomeArtParts();if(n>=o.width+2){const t=Math.max(0,Math.floor((n-o.width)/2));for(const r of o.rows)s.push(artRow(e,r,o,t))}else s.push(centerStyled("AEGIS CODE",n,r.gold+BOLD));s.push("");const a=!1===t.firstRun?WELCOME_BACK:WELCOME_TITLE;s.push(centerStyled(a,n,r.coral+BOLD));const l=[t.version?`v${t.version}`:null,TAGLINE].filter(Boolean).join(` ${GLYPH.bullet} `);return s.push(centerStyled(l,n,r.gray)),s.push(""),s.push(...renderIdentityBox(e,t,n)),s}function renderIdentityBox(e,t={},r=80){const n=themeOf(e),s=[renderHeading(e,"aegiscode",r)],o=[["version",t.version?`v${t.version}`:null],["model",t.model||"server default"],["base",t.base||""],["key",t.key||"not set"],["render",!1===t.stream?"buffered":"streaming"]].filter((([,e])=>e));for(const[e,t]of o){const o=clip(String(t),Math.max(0,r-12));s.push(` ${n.gray}${e.padEnd(8)}${RESET}${n.white}${o}${RESET}`)}const a=clip(` type /help for commands ${GLYPH.bullet} /quit to exit`,r);return s.push(""),s.push(`${n.dim}${a}${RESET}`),s}function mdLines(e,t,r){const n=themeOf(r),s=[];let o=!1;const a=Math.max(20,t-4);for(const t of String(null==e?"":e).split("\n")){if(/^\s*```/.test(t)){o=!o;continue}if(o){for(const e of wrapBlock(t,a))s.push(`${n.gray} ${e}${RESET}`);continue}if(""===t.trim()){s.push("");continue}const e=/^(\s*)[-*]\s+(.*)$/.exec(t);if(e){const t=" ".repeat(Math.min(6,e[1].length));for(const o of wrapBlock(inline(e[2],r),a-2))s.push(`${t}${n.gray}${GLYPH.bullet}${RESET} ${o}`);continue}const l=/^(#{1,6})\s+(.*)$/.exec(t);if(l)s.push(`${n.gold}${BOLD}${inline(l[2],r)}${RESET}`);else for(const e of wrapBlock(inline(t,r),a,""))s.push(e)}return s}function inline(e,t){const r=themeOf(t);return String(null==e?"":e).replace(/`([^`]+)`/g,((e,t)=>`${r.green}${t}${RESET}`)).replace(/\*\*([^*]+)\*\*/g,((e,t)=>`${BOLD}${t}${RESET}`))}function assistantLines(e,t,r){return markdown&&"function"==typeof markdown.renderMarkdown?markdown.renderMarkdown(String(null==t?"":t),r,e).map(spansToString):mdLines(t,r,e)}function renderTurn(e,t,r=80){const n=themeOf(e),s=t.role||"assistant",o=String(null==t.text?"":t.text),a=[];if("user"===s)wrapBlock(o,Math.max(8,r-2)).forEach(((e,t)=>{0===t?a.push(`${n.gray}${GLYPH.cursor}${RESET} ${n.white}${e}${RESET}`):a.push(` ${n.white}${e}${RESET}`)}));else if("assistant"===s||"system"===s){const t=assistantLines(e,o,Math.max(8,r-2));t.length||t.push(""),t[0]=`${n.white}${GLYPH.block}${RESET} `+t[0],a.push(...t)}else if("tool"===s){const s=void 0===t.ok?"":t.ok?` ${n.green}${GLYPH.check}${RESET}`:` ${n.red}${errMark()}${RESET}`;a.push(`${n.gray}${t.label||"tool"}${RESET}${s}`);const o=null==t.args?"":"string"==typeof t.args?t.args:JSON.stringify(t.args),l=t.label&&(t.label.includes("writeFile")||t.label.includes("Write"));if(l&&t.args){const n=extractNewContent(t.label.split(/\s+/)[1],t.args);if(n){const s=t.args.file_path||t.args.path,o=extractPreview(s,n);o&&a.push(...renderFilePreview(o,e,r))}}t.diff&&!l?a.push(...renderDiffBlock(t.diff,e,r,{open:!!t.diffOpen})):o&&!l&&a.push(` ${n.gray}${GLYPH.hook} $ ${clip(o,Math.max(0,r-6))}${RESET}`)}else if("error"===s)a.push(`${n.red}${errMark()} ${o}${RESET}`);else for(const e of wrapBlock(o,Math.max(8,r-2)))a.push(`${n.white}${e}${RESET}`);if(t.meta){const n=renderMeta(e,t.meta,r);n&&a.push(n)}return a}function renderMeta(e,t={},r=80){const n=themeOf(e),s=[];t.model&&s.push(`${n.blue}${t.model}${RESET}`);const o=t.usage&&"object"==typeof t.usage?t.usage:t,a=fmtUsageSplit(o);if(a)s.push(`${n.white}${a.output}${RESET}`);else{const e=displayTokens(o);null!=e&&s.push(`${n.white}${fmtTokens(e)} tokens${RESET}`)}if(null!=t.eur&&feeBillable()&&s.push(`${t.eur>0?n.coral:n.green}${fmtEur(t.eur)}${RESET}`),null!=t.ms&&s.push(`${n.gray}${fmtElapsed(t.ms)}${RESET}`),t.calls>1&&s.push(`${n.gray}${t.calls} calls${RESET}`),!s.length)return"";const l=`${n.dim} ${GLYPH.bullet} ${RESET}`;return`${n.dim}${GLYPH.hook} ${RESET}${s.join(l)}`}function renderStatus(e,t={},r=80){const n=themeOf(e),s=["aegis"];t.model&&s.push(t.model),null!=t.tokens&&s.push(`${fmtTokens(t.tokens)} tokens`),null!=t.spend&&s.push(fmtEur(t.spend)),t.mode&&s.push(t.mode);const o=t.hint||"ctrl+c quit",a=` ${s.join(` ${GLYPH.bullet} `)} `,l=r-w(a)-w(o)-1,i=l>0?a+" ".repeat(l)+o+" ":clip(a,r);return`${n.gray}${pad(i,r)}${RESET}`}function renderWorking(e,t={}){const r=themeOf(e);if(t.done){const e=t.verb||DONE_VERBS[t.tools?1:0]||DONE_VERBS[0],n=null!=t.secs?t.secs:Math.max(1,Math.round((t.elapsedMs||0)/1e3));return`${r.gray}${GLYPH.bloom} ${e} for ${n}s${RESET}`}const n=GLYPH.spin[Math.abs(Math.floor(t.tick||0))%GLYPH.spin.length],s=t.verb||VERBS[0],o=[];null!=t.elapsedMs&&o.push(fmtElapsed(t.elapsedMs)),null!=t.streamed&&o.push(`↓${t.streamedFloor?"≥":""}${fmtTokens(t.streamed)} tokens`);const a=o.length?` ${r.gray}(${o.join(` ${GLYPH.bullet} `)})${RESET}`:"";return`${r.coral}${n}${RESET} ${r.white}${s}${RESET}${r.white}…${RESET}${a}${r.dim} esc to interrupt${RESET}`}function renderHeading(e,t,r=80){const n=themeOf(e),s=` ${t} `,o=Math.max(0,r-w(s)),a=Math.floor(o/2),l=GLYPH.rule;return`${n.gray}${l.repeat(a)}${RESET}${n.gold}${BOLD}${s}${RESET}${n.gray}${l.repeat(Math.max(0,o-a))}${RESET}`}function renderToolResult(e,t,r,n=80){const s=themeOf(e),o=[renderHeading(e,t,n)];for(const e of wrapBlock(String(null==r?"":r),Math.max(8,n-2)))o.push(e?` ${s.white}${e}${RESET}`:"");return o}function renderApproval(e,t={},r=80){const n=themeOf(e),s=[renderHeading(e,`confirm ${t.tool||"tool"}`,r)],o=t.diff?t.diff:null==t.args?"":"string"==typeof t.args?t.args:JSON.stringify(t.args);for(const e of wrapBlock(o,Math.max(8,r-2)))s.push(e?` ${n.gray}${e}${RESET}`:"");return s.push(""),s.push(` ${n.coral}${GLYPH.bullet}${RESET} ${n.white}y${RESET}es once ${n.dim}${GLYPH.bullet}${RESET} ${n.white}s${RESET}ession ${n.dim}${GLYPH.bullet}${RESET} ${n.white}n${RESET}o ${n.dim}(default)${RESET}`),s}const NOTICE={info:["gray",()=>GLYPH.bullet],warn:["coral",warnMark],error:["red",errMark],ok:["green",()=>GLYPH.check]};function renderNotice(e,t,r){const n=themeOf(e),[s,o]=NOTICE[t]||NOTICE.info;return`${n[s]}${o()} ${r}${RESET}`}module.exports={renderBanner:renderBanner,renderIdentityBox:renderIdentityBox,renderTurn:renderTurn,renderMeta:renderMeta,renderStatus:renderStatus,renderWorking:renderWorking,renderHeading:renderHeading,renderToolResult:renderToolResult,renderApproval:renderApproval,renderNotice:renderNotice,mdLines:mdLines,inline:inline,artRow:artRow,tintWhale:tintWhale,fg:fg,bg:bg,UNDER:UNDER,ITALIC:ITALIC,RESET_FG:RESET_FG,RESET_BG:RESET_BG,pad:pad,padStart:padStart};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),o=i(t);if(!n||!o)return!1;if(n===o)return!0;if(o.length<=14&&(n.startsWith(o)||o.startsWith(n)))return!0;if(o.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!ECHO_STOP.has(e)))),n=i(e),o=i(t);if(n.size&&n.size===o.size&&[...n].every((e=>o.has(e))))return!0}return!1}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let o=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return o?(o=o[0].toUpperCase()+o.slice(1),o.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const o=cleanTitle(e);if(o)return looksLikeEcho(o,n)?GENERIC_TITLE:o}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,o=i&&!0===i.seeded;if(n)return null;if(!o&&!isGenericTitle(e))return null;if(!String(t||"").trim()||isTopicless(t))return null;const r=cleanTitle(await nameConversation(t,i));return!r||isGenericTitle(r)?null:r}async function nameSession(e,t,i,n,o={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const r="function"==typeof e.getSession?e.getSession(t,i):null,s=r&&r.title,l={...o,seeded:!(!r||r.named)},a=await refineTitle(s,n,l);if(a){try{e.setTitle(t,i,a,{named:!0})}catch{return null}return a}if(isTopicless(n)&&r&&!r.named&&!isGenericTitle(s)){try{e.setTitle(t,i,GENERIC_TITLE)}catch{return null}return GENERIC_TITLE}return null}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle,nameSession:nameSession};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=2e3,LOCK_WAIT_MS=500;function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS;for(let e=0;e<200;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(e>LOCK_STALE_MS){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;const s=Date.now()+5;for(;Date.now()<s;);}return!1}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){const n=acquireLock(e);try{const n=load(e),s=t(n);return save(e,n),s}finally{n&&releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=MAX_MESSAGES_PER_SESSION?e:e.slice(e.length-MAX_MESSAGES_PER_SESSION):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,(e=>{const s=e[n]||{messages:[]};return e[n]={...s,...t,id:n,version:2},!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]}))}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,(e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s}))}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId;return mutate(e,(e=>{const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],o=n.ts||(new Date).toISOString(),i={role:"user",content:null==n.prompt?"":String(n.prompt),ts:o},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:o};return n.tokens&&(a.tokens=n.tokens),"number"==typeof n.costUsd&&(a.costUsd=n.costUsd),n.status&&(a.status=n.status),n.model&&(a.model=n.model),n.provider&&(a.provider=n.provider),n.origin&&(i.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([i,a])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t}))}function setTitle(e,t,n){const s=String(null==n?"":n).trim().slice(0,200);return t&&s?mutate(e,(e=>{const n=e[t];return n?(n.title=s,n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null})):null}function listSessions(e){const t=load(e);return Object.values(t).filter((e=>e&&e.id)).sort(((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0)))}function getSession(e,t){return load(e)[t]||null}function deleteSession(e,t){return mutate(e,(e=>(delete e[t],{ok:!0})))}function markSynced(e,t,n){return mutate(e,(e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null}))}function markPending(e,t){return mutate(e,(e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null}))}function listPending(e){return listSessions(e).filter((e=>!1!==e.pending))}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,(e=>{let t=0;for(const s of n){const n=s&&(s.session_id||s.id);if(!n)continue;const r=e[n],o=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=o)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:o||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:s.session_id||s.id,origin:s.source||r&&r.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t})):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map((e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find((e=>e&&"user"===e.role));return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}}))}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter((e=>e&&("user"===e.role||"assistant"===e.role))).map((e=>({role:e.role,text:null==e.content?"":String(e.content)}))):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter((e=>e&&e.id));return r.length?listSessions(e).length?{adopted:!1,sessions:0,from:n,reason:"store already has sessions"}:(mutate(e,(e=>{for(const t of r)e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),{adopted:!0,sessions:r.length,from:n}):{adopted:!1,sessions:0,from:n,reason:"legacy store empty"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:MAX_MESSAGES_PER_SESSION,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:LOCK_STALE_MS,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=2e3,LOCK_WAIT_MS=500;function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS;for(let e=0;e<200;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(e>LOCK_STALE_MS){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;const s=Date.now()+5;for(;Date.now()<s;);}return!1}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){const n=acquireLock(e);try{const n=load(e),s=t(n);return save(e,n),s}finally{n&&releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=MAX_MESSAGES_PER_SESSION?e:e.slice(e.length-MAX_MESSAGES_PER_SESSION):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,(e=>{const s=e[n]||{messages:[]};return e[n]={...s,...t,id:n,version:2},!0===s.named&&"string"==typeof s.title&&s.title&&(e[n].title=s.title,e[n].named=!0),!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]}))}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,(e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s}))}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId;return mutate(e,(e=>{const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],o=n.ts||(new Date).toISOString(),i={role:"user",content:null==n.prompt?"":String(n.prompt),ts:o},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:o};return n.tokens&&(a.tokens=n.tokens),"number"==typeof n.costUsd&&(a.costUsd=n.costUsd),n.status&&(a.status=n.status),n.model&&(a.model=n.model),n.provider&&(a.provider=n.provider),n.origin&&(i.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([i,a])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t}))}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const o=s&&!0===s.named;return mutate(e,(e=>{const n=e[t];return n?(n.title=r,o&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null}))}function listSessions(e){const t=load(e);return Object.values(t).filter((e=>e&&e.id)).sort(((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0)))}function getSession(e,t){return load(e)[t]||null}function deleteSession(e,t){return mutate(e,(e=>(delete e[t],{ok:!0})))}function markSynced(e,t,n){return mutate(e,(e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null}))}function markPending(e,t){return mutate(e,(e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null}))}function listPending(e){return listSessions(e).filter((e=>!1!==e.pending))}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,(e=>{let t=0;for(const s of n){const n=s&&(s.session_id||s.id);if(!n)continue;const r=e[n],o=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=o)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:o||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:s.session_id||s.id,origin:s.source||r&&r.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t})):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map((e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find((e=>e&&"user"===e.role));return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}}))}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter((e=>e&&("user"===e.role||"assistant"===e.role))).map((e=>({role:e.role,text:null==e.content?"":String(e.content)}))):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter((e=>e&&e.id));return r.length?listSessions(e).length?{adopted:!1,sessions:0,from:n,reason:"store already has sessions"}:(mutate(e,(e=>{for(const t of r)e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),{adopted:!0,sessions:r.length,from:n}):{adopted:!1,sessions:0,from:n,reason:"legacy store empty"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:MAX_MESSAGES_PER_SESSION,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:LOCK_STALE_MS,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
@@ -1,3 +1,271 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- const READ_VERBS=new Set(["cat","head","tail","less","more","wc","grep","egrep","fgrep","rg","sed","awk","cut","sort","uniq","tr","diff","comm","join","nl","ls","dir","tree","stat","file","du","df","pwd","which","type","basename","dirname","realpath","readlink","find","locate","echo","printf","date","uname","whoami","id","env","printenv","true","test"]),GIT_READ_SUBCOMMANDS=new Set(["diff","status","log","show","blame","grep","ls-files","rev-parse","describe","cat-file","shortlog","whatchanged","reflog","show-ref","ls-tree","diff-tree","diff-files","diff-index","merge-base"]),WRITE_PATTERNS=[/(^|[\s;&|(])rm(\s|$)/,/(^|[\s;&|(])rmdir(\s|$)/,/(^|[\s;&|(])mv(\s|$)/,/(^|[\s;&|(])cp(\s|$)/,/(^|[\s;&|(])ln(\s|$)/,/(^|[\s;&|(])mkdir(\s|$)/,/(^|[\s;&|(])touch(\s|$)/,/(^|[\s;&|(])chmod(\s|$)/,/(^|[\s;&|(])chown(\s|$)/,/(^|[\s;&|(])truncate(\s|$)/,/(^|[\s;&|(])dd(\s|$)/,/(^|[\s;&|(])tee(\s|$)/,/(^|[\s;&|(])install(\s|$)/,/(^|[\s;&|(])patch(\s|$)/,/(^|[\s;&|(])git\s+(commit|add|rm|mv|checkout|switch|reset|apply|revert|merge|rebase|stash|clean|init|clone|pull|push|fetch|tag|branch|config)\b/,/(^|[\s;&|(])sed\s+(-[a-zA-Z]*i|--in-place)/,/(^|[\s;&|(])sort\b[^|;]*\s-o(\s|$)/,/(^|[\s;&|(])sort\b[^|;]*--output=/,/(^|[\s;&|(])dd\b[^|;]*\bof=/,/(^|[\s;&|(])find\b[^|;]*\s-(fprint|fprint0|fls)\b/,/(^|[\s;&|(])find\b[^|]*\s-(delete|exec|execdir|ok|okdir)\b/,/(^|[\s;&|(])(pip|pip3)\s+(install|uninstall|download)\b/,/(^|[\s;&|(])npm\s+(install|i|ci|uninstall|publish|run)\b/,/(^|[\s;&|(])yarn\s+(add|install|remove)\b/,/(^|[\s;&|(])apt(-get)?\s+(install|remove|purge|update|upgrade)\b/,/(^|[\s;&|(])(python|python3)\s+-m\s+pip\s+install\b/,/(^|[\s;&|(])pytest\b[^|]*--(cov|junitxml)/,/(?<![0-9&])>>?(?![&-])/,/\bexport\s+[A-Za-z_]/,/(^|[\s;&|(])source(\s|$)/],STATEFUL_PATTERNS=[/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/,/(^|[\s;&|(])pushd(\s|$)/,/(^|[\s;&|(])popd(\s|$)/,/(^|[\s;&|(])nohup(\s|$)/,/(^|[\s;&|(])disown(\s|$)/,/<<-?\s*['"]?[A-Za-z_]/,/(^|[\s;&|(])\&$/,/(^|[\s;&|(])exec(\s|$)/,/(^|[\s;&|(])history(\s|$)/,/(^|[\s;&|(])jobs(\s|$)/];function effectiveVerb(e){let s=0;for(let t=0;t<4&&s<e.length;t++){const t=e[s];if("time"!==t&&"command"!==t)if("env"!==t)if("timeout"!==t){if("nice"!==t)break;s+=1,s<e.length&&"-n"===e[s]?s+=2:s<e.length&&/^-?\d+$/.test(e[s])&&(s+=1)}else{for(s+=1;s<e.length&&e[s].startsWith("-");)s+=1;s<e.length&&/^[0-9]+(\.[0-9]+)?[smhd]?$/.test(e[s])&&(s+=1)}else for(s+=1;s<e.length&&(e[s].startsWith("-")||/^[A-Za-z_][A-Za-z0-9_]*=/.test(e[s]));)s+=1;else s+=1}return s<e.length?{verb:e[s],rest:e.slice(s)}:null}function segments(e){const s=[],t=/(\|\||&&|[;|])/g;let n,r=0;for(;n=t.exec(e);)s.push({sep:null,text:e.slice(r,n.index)}),s.push({sep:n[1]}),r=n.index+n[1].length;return s.push({sep:null,text:e.slice(r)}),s}function leadingCd(e){const s=/^\s*cd\s+(?:--\s+)?(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*&&\s*([\s\S]+)$/.exec(e);if(!s)return{cwd:null,rest:e};const t=(s[1]||s[2]||s[3]||"").trim();return t.startsWith("/")?{cwd:t,rest:s[4]}:{cwd:null,rest:e}}function planExec(e,s={}){const t=s.baseCwd||null,n="string"==typeof e?e:"",r=e=>({oneShot:!1,cwd:null,reason:e});if(!n.trim())return r("empty command");if(n.includes("\n"))return r("multi-line command");for(const e of STATEFUL_PATTERNS)if(e.test(n))return r("depends on session state");for(const e of WRITE_PATTERNS)if(e.test(n))return r("contains a write");const{cwd:i,rest:o}=leadingCd(n),l=o.trim();if(!l)return r("nothing after the cd");const a=segments(l).filter((e=>!e.sep));if(!a.length)return r("no command");for(const e of a){const s=e.text.trim().replace(/^\(+\s*/,"").split(/\s+/).filter(Boolean);if(!s.length)continue;const t=effectiveVerb(s);if(!t)return r("empty command after wrappers");const n=t.verb;if("git"!==n){if(!READ_VERBS.has(n))return r(`${n} is not a known read verb`);if(("sed"===n||"awk"===n)&&/(^|\s)-[a-zA-Z]*w\s/.test(t.rest.join(" ")))return r(`${n} writes a file`)}else{const e=t.rest[1];if(!e||e.startsWith("-"))continue;if(!GIT_READ_SUBCOMMANDS.has(e))return r(`git ${e} is not read-only`)}}return{oneShot:!0,cwd:i||t,reason:"read-only"}}module.exports={planExec:planExec,READ_VERBS:READ_VERBS,GIT_READ_SUBCOMMANDS:GIT_READ_SUBCOMMANDS,WRITE_PATTERNS:WRITE_PATTERNS,STATEFUL_PATTERNS:STATEFUL_PATTERNS};
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ /**
7
+ * Which `exec` calls are safe to run WITHOUT the turn's persistent shell.
8
+ *
9
+ * WHY THIS EXISTS. `engine.js` batches the read-only calls in a round into one
10
+ * `Promise.all`, but `exec` was excluded from that batching because it is in
11
+ * `MUTATING_TOOLS` — one persistent shell per turn means two concurrent
12
+ * commands would interleave their streams and the `__AEGIS_SH_…EXIT` sentinel
13
+ * each one parses would resolve the wrong call. That exclusion is correct, but
14
+ * it is also where the wall-clock went: across the measured SWE-bench runs
15
+ * 81.7% of tool calls are `exec` (438/536) and only 10.4% are readFile/grep/
16
+ * listDir/glob, so the parallel window covered a tenth of the work. Total time
17
+ * was 2223s against another harness's 1322s for the SAME patches while the
18
+ * medians matched (120s vs 126s) — a serial dispatch shows up as tail, not as
19
+ * median.
20
+ *
21
+ * THE OPENING. Most of those exec calls are not mutations at all. They are
22
+ * reads dressed as shell — `grep`, `sed -n`, `git log`, `ls`, `cat` — and
23
+ * 378 of 438 chain an absolute `cd` first, which is the habit the `exec` schema
24
+ * teaches ("state does not persist"? — it does, but the model writes `cd` anyway
25
+ * because every one-shot example it has seen does). A leading `cd <abs> &&` is
26
+ * therefore not state TO the command, it is an address the command carries with
27
+ * it: run that command with `cwd` set to that directory and the shell it does
28
+ * not touch is irrelevant.
29
+ *
30
+ * SO THE TEST IS: could this exact command run in a FRESH process, with `cwd`
31
+ * set as the lead-in says, and produce the same output? Everything below is an
32
+ * attempt to answer that conservatively. The bias is deliberate and one-way —
33
+ * a false negative costs a round of serial execution, a false positive corrupts
34
+ * a user's repository, so every uncertainty resolves to "keep it sequential".
35
+ *
36
+ * WHAT IS REJECTED, and why each one is not merely cautious:
37
+ * - a write verb anywhere in the command (`rm`, `mv`, `tee`, `>`, `>>`, `sed -i`,
38
+ * `pip install`, `patch`, `git commit`, …) — obviously not read-only;
39
+ * - `cd` that is NOT the sole leading `cd <path> &&` — a mid-command `cd`
40
+ * changes what a LATER command in the same string sees;
41
+ * - shell variables (`$FOO`, `${FOO}`), bare `export`, `source`, `.` — these
42
+ * only mean anything if session state exists, and with a fresh process they
43
+ * would expand to empty strings and silently produce a DIFFERENT result
44
+ * rather than an error;
45
+ * - job control / backgrounding (`&`, `nohup`), pipelines into a pager;
46
+ * - here-docs and multi-line commands — the exit sentinel logic is per-line
47
+ * and a multi-line body is the shape most likely to hide a write;
48
+ * - any command whose leading `cd` target is relative or `~`-relative beyond
49
+ * the first segment, because it would resolve against the SESSION's cwd,
50
+ * not this process's.
51
+ */
52
+
53
+ // Read-shaped verbs that are safe as the FIRST word of a pipeline segment.
54
+ // Deliberately a small allow-list rather than a deny-list of write verbs: a
55
+ // deny-list fails open the moment someone invents a write verb we did not
56
+ // imagine, and the cost of failing open here is a corrupted tree.
57
+ //
58
+ // NOT in this set, on purpose: `python`, `python3`, `node`, `sh`, `bash`.
59
+ // They are arbitrary programs, and the contract this classifier has to prove is
60
+ // not "the command is a read the USER would call a read" but "the command cannot
61
+ // produce a filesystem mutation a CONCURRENT peer could observe". No text scan
62
+ // can prove that about an interpreter — `python -c "open(p,'w')"` is one line,
63
+ // and chasing every spelling of a write (`write`, `os.remove`, `shutil`,
64
+ // `subprocess`, `-m pip`) is an unbounded guess. So interpreter invocations stay
65
+ // on the sequential path. That is a real limit on how much of the measured
66
+ // exec traffic this opens up (most SWE-bench commands are `python -c`), and it
67
+ // is the reason the wall-clock gain here is bounded rather than dramatic.
68
+ const READ_VERBS = new Set([
69
+ 'cat', 'head', 'tail', 'less', 'more', 'wc', 'grep', 'egrep', 'fgrep', 'rg',
70
+ 'sed', 'awk', 'cut', 'sort', 'uniq', 'tr', 'diff', 'comm', 'join', 'nl',
71
+ 'ls', 'dir', 'tree', 'stat', 'file', 'du', 'df', 'pwd', 'which', 'type',
72
+ 'basename', 'dirname', 'realpath', 'readlink', 'find', 'locate',
73
+ 'echo', 'printf', 'date', 'uname', 'whoami', 'id', 'env', 'printenv',
74
+ 'true', 'test',
75
+ ]);
76
+
77
+ // `git` subcommands that only read. `git diff/status/log/show/blame/grep` are
78
+ // the ones that actually appear in agent transcripts; anything else (`git
79
+ // checkout`, `git apply`, `git stash`, `git reset`) is not on this list on
80
+ // purpose.
81
+ const GIT_READ_SUBCOMMANDS = new Set([
82
+ 'diff', 'status', 'log', 'show', 'blame', 'grep', 'ls-files', 'rev-parse',
83
+ 'describe', 'cat-file', 'shortlog', 'whatchanged', 'reflog', 'show-ref',
84
+ 'ls-tree', 'diff-tree', 'diff-files', 'diff-index', 'merge-base',
85
+ ]);
86
+
87
+ // Absolute-write shapes. Any hit anywhere (not just at a segment start) makes
88
+ // the whole command sequential — `find . -delete`, `sed -i`, `python -c
89
+ // "open(p,'w')"` all hide their write behind a read-shaped verb.
90
+ const WRITE_PATTERNS = [
91
+ /(^|[\s;&|(])rm(\s|$)/,
92
+ /(^|[\s;&|(])rmdir(\s|$)/,
93
+ /(^|[\s;&|(])mv(\s|$)/,
94
+ /(^|[\s;&|(])cp(\s|$)/,
95
+ /(^|[\s;&|(])ln(\s|$)/,
96
+ /(^|[\s;&|(])mkdir(\s|$)/,
97
+ /(^|[\s;&|(])touch(\s|$)/,
98
+ /(^|[\s;&|(])chmod(\s|$)/,
99
+ /(^|[\s;&|(])chown(\s|$)/,
100
+ /(^|[\s;&|(])truncate(\s|$)/,
101
+ /(^|[\s;&|(])dd(\s|$)/,
102
+ /(^|[\s;&|(])tee(\s|$)/,
103
+ /(^|[\s;&|(])install(\s|$)/,
104
+ /(^|[\s;&|(])patch(\s|$)/,
105
+ /(^|[\s;&|(])git\s+(commit|add|rm|mv|checkout|switch|reset|apply|revert|merge|rebase|stash|clean|init|clone|pull|push|fetch|tag|branch|config)\b/,
106
+ /(^|[\s;&|(])sed\s+(-[a-zA-Z]*i|--in-place)/,
107
+ // `sort -o f`, `uniq -o`? — only a few read verbs take a write flag, and it
108
+ // is easy to miss because the verb is allow-listed. `grep -o` is NOT this
109
+ // (it only changes the OUTPUT shape), so the match is verb-qualified.
110
+ /(^|[\s;&|(])sort\b[^|;]*\s-o(\s|$)/,
111
+ /(^|[\s;&|(])sort\b[^|;]*--output=/,
112
+ /(^|[\s;&|(])dd\b[^|;]*\bof=/,
113
+ /(^|[\s;&|(])find\b[^|;]*\s-(fprint|fprint0|fls)\b/,
114
+ /(^|[\s;&|(])find\b[^|]*\s-(delete|exec|execdir|ok|okdir)\b/,
115
+ /(^|[\s;&|(])(pip|pip3)\s+(install|uninstall|download)\b/,
116
+ /(^|[\s;&|(])npm\s+(install|i|ci|uninstall|publish|run)\b/,
117
+ /(^|[\s;&|(])yarn\s+(add|install|remove)\b/,
118
+ /(^|[\s;&|(])apt(-get)?\s+(install|remove|purge|update|upgrade)\b/,
119
+ /(^|[\s;&|(])(python|python3)\s+-m\s+pip\s+install\b/,
120
+ /(^|[\s;&|(])pytest\b[^|]*--(cov|junitxml)/,
121
+ // Shell-level writes. `>` redirect is matched conservatively: `2>&1` and
122
+ // `>&-` are not writes, so the digit/`&` cases are excluded explicitly.
123
+ /(?<![0-9&])>>?(?![&-])/,
124
+ /\bexport\s+[A-Za-z_]/,
125
+ /(^|[\s;&|(])source(\s|$)/,
126
+ ];
127
+
128
+ // Commands that only make sense against session state.
129
+ const STATEFUL_PATTERNS = [
130
+ /\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/,
131
+ /(^|[\s;&|(])pushd(\s|$)/,
132
+ /(^|[\s;&|(])popd(\s|$)/,
133
+ /(^|[\s;&|(])nohup(\s|$)/,
134
+ /(^|[\s;&|(])disown(\s|$)/,
135
+ /<<-?\s*['"]?[A-Za-z_]/,
136
+ /(^|[\s;&|(])\&$/,
137
+ /(^|[\s;&|(])exec(\s|$)/,
138
+ /(^|[\s;&|(])history(\s|$)/,
139
+ /(^|[\s;&|(])jobs(\s|$)/,
140
+ ];
141
+
142
+ /**
143
+ * Strip leading wrapper programs (`timeout 300`, `time`, `command`, `env -i`)
144
+ * down to the verb that actually runs. A wrapper must NOT be trusted on its
145
+ * own: `timeout 550 python x.py` starts with `timeout`, but the thing being
146
+ * run is an interpreter, and the allow-list has to judge THAT.
147
+ * Returns null when the wrapper chain hides something we cannot name.
148
+ */
149
+ function effectiveVerb(words) {
150
+ let i = 0;
151
+ // Bound the walk: a pathological chain of wrappers is not worth reasoning
152
+ // about, and stopping early only costs a miss (stays sequential).
153
+ for (let guard = 0; guard < 4 && i < words.length; guard++) {
154
+ const w = words[i];
155
+ if (w === 'time' || w === 'command') { i += 1; continue; }
156
+ if (w === 'env') {
157
+ i += 1;
158
+ // `env -i`, `env -u X`, and `env FOO=1` prefixes are all local to this
159
+ // invocation (they are not session state), so skip them.
160
+ while (i < words.length && (words[i].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]))) i += 1;
161
+ continue;
162
+ }
163
+ if (w === 'timeout') {
164
+ i += 1;
165
+ while (i < words.length && words[i].startsWith('-')) i += 1;
166
+ // the duration argument
167
+ if (i < words.length && /^[0-9]+(\.[0-9]+)?[smhd]?$/.test(words[i])) i += 1;
168
+ continue;
169
+ }
170
+ if (w === 'nice') {
171
+ i += 1;
172
+ if (i < words.length && words[i] === '-n') i += 2;
173
+ else if (i < words.length && /^-?\d+$/.test(words[i])) i += 1;
174
+ continue;
175
+ }
176
+ break;
177
+ }
178
+ return i < words.length ? { verb: words[i], rest: words.slice(i) } : null;
179
+ }
180
+
181
+ /** Split on `;`/`&&`/`||`/`|` into [ {sep, text} ] keeping the separators. */
182
+ function segments(command) {
183
+ const out = [];
184
+ const re = /(\|\||&&|[;|])/g;
185
+ let last = 0;
186
+ let m;
187
+ while ((m = re.exec(command))) {
188
+ out.push({ sep: null, text: command.slice(last, m.index) });
189
+ out.push({ sep: m[1] });
190
+ last = m.index + m[1].length;
191
+ }
192
+ out.push({ sep: null, text: command.slice(last) });
193
+ return out;
194
+ }
195
+
196
+ /**
197
+ * Pull a single leading `cd <absolute path> &&` off the front.
198
+ * Returns { cwd, rest } — `cwd` is null when there is no such lead-in.
199
+ * Only an ABSOLUTE path qualifies: a relative one would resolve against the
200
+ * session's directory, which a one-shot process does not share.
201
+ */
202
+ function leadingCd(command) {
203
+ const m = /^\s*cd\s+(?:--\s+)?(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*&&\s*([\s\S]+)$/.exec(command);
204
+ if (!m) return { cwd: null, rest: command };
205
+ const target = (m[1] || m[2] || m[3] || '').trim();
206
+ if (!target.startsWith('/')) return { cwd: null, rest: command };
207
+ // `cd /a && cd /b && …` — the second cd is not the lead-in, so the rest must
208
+ // be judged on its own (it will then be rejected as a non-leading cd).
209
+ return { cwd: target, rest: m[4] };
210
+ }
211
+
212
+ /**
213
+ * Decide whether `command` may run as a one-shot process with an explicit cwd.
214
+ *
215
+ * @param {string} command raw command the model asked `exec` to run
216
+ * @param {object} [opts]
217
+ * @param {string} [opts.baseCwd] the turn's cwd, used when there is no lead-in
218
+ * @returns {{ oneShot: boolean, cwd: string|null, reason: string }}
219
+ * `reason` is for tests and diagnostics; it is never shown to the model.
220
+ */
221
+ function planExec(command, opts = {}) {
222
+ const baseCwd = opts.baseCwd || null;
223
+ const raw = typeof command === 'string' ? command : '';
224
+ const no = (reason) => ({ oneShot: false, cwd: null, reason });
225
+
226
+ if (!raw.trim()) return no('empty command');
227
+ // A newline means a multi-command body. The session's exit sentinel is
228
+ // appended per command and a multi-line body is where a write hides; not
229
+ // worth the risk for the handful of these a turn contains.
230
+ if (raw.includes('\n')) return no('multi-line command');
231
+
232
+ for (const re of STATEFUL_PATTERNS) {
233
+ if (re.test(raw)) return no('depends on session state');
234
+ }
235
+ for (const re of WRITE_PATTERNS) {
236
+ if (re.test(raw)) return no('contains a write');
237
+ }
238
+
239
+ const { cwd, rest } = leadingCd(raw);
240
+ const restText = rest.trim();
241
+ if (!restText) return no('nothing after the cd');
242
+
243
+ // Every segment must start with a read-shaped verb. `git` is special-cased
244
+ // on its subcommand; a bare `git` with no subcommand reads the status, which
245
+ // is read-only, and `git --version` likewise.
246
+ const segs = segments(restText).filter((s) => !s.sep);
247
+ if (!segs.length) return no('no command');
248
+ for (const seg of segs) {
249
+ const words = seg.text.trim().replace(/^\(+\s*/, '').split(/\s+/).filter(Boolean);
250
+ if (!words.length) continue;
251
+ const eff = effectiveVerb(words);
252
+ if (!eff) return no('empty command after wrappers');
253
+ const verb = eff.verb;
254
+ if (verb === 'git') {
255
+ const sub = eff.rest[1];
256
+ if (!sub || sub.startsWith('-')) continue; // `git`, `git --version`
257
+ if (!GIT_READ_SUBCOMMANDS.has(sub)) return no(`git ${sub} is not read-only`);
258
+ continue;
259
+ }
260
+ if (!READ_VERBS.has(verb)) return no(`${verb} is not a known read verb`);
261
+ // `sed -i` is already caught by WRITE_PATTERNS above, but `sed … -w file`
262
+ // and `awk … > file` write without an `-i`.
263
+ if ((verb === 'sed' || verb === 'awk') && /(^|\s)-[a-zA-Z]*w\s/.test(eff.rest.join(' '))) {
264
+ return no(`${verb} writes a file`);
265
+ }
266
+ }
267
+
268
+ return { oneShot: true, cwd: cwd || baseCwd, reason: 'read-only' };
269
+ }
270
+
271
+ module.exports = { planExec, READ_VERBS, GIT_READ_SUBCOMMANDS, WRITE_PATTERNS, STATEFUL_PATTERNS };