aegiscode 7.0.28 → 7.0.29
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/package.json +2 -3
- package/src/app.js +1 -1
- package/src/art.js +1 -1
- package/src/chatflow.js +1 -1
- package/src/commands.js +1 -1
- package/src/credentials.js +1 -1
- package/src/diffview.js +1 -1
- package/src/export.js +1 -1
- package/src/init.js +1 -1
- package/src/models.js +1 -1
- package/src/panels.js +1 -1
- package/src/screens.js +1 -1
- package/src/theme.js +1 -1
- package/vendor/client/aegis.js +1 -1
- package/vendor/client/attest.js +1 -1
- package/vendor/client/catalog-client.js +1 -1
- package/vendor/client/conversation-export.js +1 -1
- package/vendor/client/credentials.js +1 -1
- package/vendor/client/drive-upload.js +1 -1
- package/vendor/client/env-file.js +1 -1
- package/vendor/client/hooks.js +1 -1
- package/vendor/client/model-discovery.js +1 -1
- package/vendor/client/naming.js +1 -1
- package/vendor/client/platform.js +1 -1
- package/vendor/client/record-vault.js +2 -2
- package/vendor/client/session-store.js +1 -1
- package/vendor/client/user-models.js +1 -1
- package/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/exec-plan.js +269 -1
- package/vendor/desktop/lib/local/integrity.js +163 -1
- package/vendor/desktop/lib/local/shell.js +712 -1
- package/vendor/desktop/lib/local/tools.js +1328 -1
- package/vendor/desktop/main.js +4956 -1
- package/vendor/hosts/install.js +1 -1
- package/vendor/hosts/openai-shim.js +1 -1
- package/vendor/mcp/server.js +1 -1
- package/vendor/mcp/tools.js +1 -1
- package/vendor/one/src/selfhost.js +3 -0
package/vendor/hosts/install.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const fs=require("node:fs"),path=require("node:path"),{TARGETS:TARGETS,getTarget:getTarget,appConfig:appConfig}=require("./targets.js"),{buildSpec:buildSpec,resolveServer:resolveServer}=require("./spec.js");function hostCtx(e={}){return{env:process.env,platform:process.platform,home:null,cwd:process.cwd(),...e}}function readText(e){try{return{text:fs.readFileSync(e,"utf8"),exists:!0}}catch(e){if("ENOENT"===e.code)return{text:null,exists:!1};throw e}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function parseJson(e,t){if(null===e||""===e.trim())return{};try{return JSON.parse(e)}catch(e){throw new Error(`${t} is not valid JSON (${e.message}) — refusing to overwrite it`)}}function setPath(e,t,r){const n=t.split(".");let s=e;for(const e of n.slice(0,-1))(null===s[e]||"object"!=typeof s[e]||Array.isArray(s[e]))&&(s[e]={}),s=s[e];return s[n[n.length-1]]=r,e}function getPath(e,t){let r=e;for(const e of t.split(".")){if(null===r||"object"!=typeof r)return;r=r[e]}return r}function delPath(e,t,r=!1){const n=t.split("."),s=[];let o=e;for(const t of n.slice(0,-1)){if(null===o||"object"!=typeof o)return e;s.push([o,t]),o=o[t]}if(o&&"object"==typeof o&&delete o[n[n.length-1]],!r)return e;for(let e=s.length-1;e>=0;e--){const[t,r]=s[e],n=t[r];if(!n||"object"!=typeof n||0!==Object.keys(n).length)break;delete t[r]}return e}const TOML_BARE=/^[A-Za-z0-9_-]+$/;function tomlKey(e){return TOML_BARE.test(e)?e:JSON.stringify(e)}function tomlString(e){return JSON.stringify(String(e))}function tomlArray(e){return`[${e.map(tomlString).join(", ")}]`}function tomlHeaderName(e){const t=e.trim();return/^\[/.test(t)?t.replace(/^\[+\s*/,"").replace(/\s*\]+$/,""):null}function ownedTomlHeader(e,t){const r=tomlHeaderName(e);return null!==r&&(r===t||r.startsWith(`${t}.`))}function upsertTomlSection(e,t,r){const n=`[${t}]`,s=(e||"").split("\n"),o=[];let i=!1,a=0;for(;a<s.length;)if(s[a].trim()!==n)o.push(s[a]),a++;else{for(o.push(n,...r,""),i=!0,a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++;for(;a<s.length&&ownedTomlHeader(s[a],t);)for(a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++}if(!i){for(;o.length&&""===o[o.length-1].trim();)o.pop();o.length&&o.push(""),o.push(n,...r,"")}return o.join("\n")}function removeTomlSection(e,t){const r=`[${t}]`,n=(e||"").split("\n"),s=[];let o=0;for(;o<n.length;)if(n[o].trim()!==r)s.push(n[o]),o++;else{for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++;for(;o<n.length&&ownedTomlHeader(n[o],t);)for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++}return s.join("\n")}function renderEntry(e,t){if("mcp-toml"===e.kind){const r=[`# Added by \`aegiscode mcp install ${e.id}\`. Key resolution lives in`,"# ~/.aegiscode/.env and the 0600 store `aegiscode login` writes.","command = "+tomlString(t.command),"args = "+tomlArray(t.args)];if(t.env&&Object.keys(t.env).length){r.push("",`[${e.container}.${t.name}.env]`);for(const[e,n]of Object.entries(t.env))r.push(`${tomlKey(e)} = ${tomlString(n)}`)}return r}return e.entry(t)}function planTarget(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(i.exists)try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind){const t=`${e.container}.${s.name}`,r=renderEntry(e,s);return i.before=c,i.after=upsertTomlSection(c,t,r),i.changed=i.after!==(c||""),i}try{a=parseJson(c,o)}catch(e){return i.error=e,i}if(null===a||"object"!=typeof a||Array.isArray(a))return i.error=new Error(`${o} does not contain a JSON object — refusing to overwrite it`),i;if(setPath(a,`${e.container}.${s.name}`,renderEntry(e,s)),"function"==typeof e.extras){const t=e.extras(s);if(t&&t.inputs){const e=Array.isArray(a.inputs)?a.inputs:[];for(const r of t.inputs){const t=e.findIndex((e=>e&&e.id===r.id));-1===t?e.push(r):e[t]=r}a.inputs=e}}return i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==(c||""),i}function planRemove(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(!i.exists)return i;try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind)return i.before=c,i.after=removeTomlSection(c,`${e.container}.${s.name}`),i.changed=i.after!==c,i;try{a=parseJson(c,o)}catch(e){return i.error=e,i}const l=`${e.container}.${s.name}`,u=void 0!==getPath(a,l),f=Array.isArray(a.inputs)&&a.inputs.some((e=>e&&"aegis-api-key"===e.id));if(!u&&!f)return i.before=c,i.after=c,i.changed=!1,i;delPath(a,l,!0);const p=Array.isArray(a.inputs)?a.inputs.filter((e=>!(e&&"aegis-api-key"===e.id))):null;return p&&(p.length?a.inputs=p:delete a.inputs),i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==c,i}function modeFor(e){return e.withKey?384:e.mode||420}function apply(e,t={}){if(e.error)return{...e,applied:!1};if(!e.changed)return{...e,applied:!1};if(t.dryRun)return{...e,applied:!1,dryRun:!0};if(e.withKey=Boolean(t.withKey),fs.mkdirSync(path.dirname(e.file),{recursive:!0}),e.exists&&null!==e.before){const t=`${e.file}.aegis-backup-${Date.now()}`;fs.writeFileSync(t,e.before,{mode:384}),e.backupOf=t}const r=`${e.file}.aegis-tmp-${process.pid}`;try{fs.writeFileSync(r,e.after,{mode:384}),fs.renameSync(r,e.file),fs.chmodSync(e.file,modeFor(e))}finally{try{fs.unlinkSync(r)}catch{}}return{...e,applied:!0}}function parseTomlEntry(e,t){if(!e)return null;const r=t.replace(/[.[\]*+?^$(){}|]/g,"\\$&"),n=new RegExp("^\\s*\\["+r+"\\]\\s*$","m").exec(e);if(!n)return null;const s=e.slice(n.index+n[0].length).split("\n"),o=[];let i=0;for(;i<s.length&&(!/^\s*\[/.test(s[i])||ownedTomlHeader(s[i],t));)o.push(s[i]),i++;const a={command:null,args:[],env:{}},c=/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m.exec(o.join("\n"));c&&(a.command=JSON.parse('"'+c[1]+'"'));const l=/^\s*args\s*=\s*\[([\s\S]*?)\]/m.exec(o.join("\n"));l&&(a.args=[...l[1].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((e=>JSON.parse('"'+e[1]+'"'))));for(const e of o.join("\n").matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/gm))"command"!==e[1]&&"args"!==e[1]&&(a.env[e[1]]=JSON.parse('"'+e[2]+'"'));return a}function entryServerPath(e){return e&&(Array.isArray(e.args)?e.args:[]).find((e=>"string"==typeof e&&/\.(js|mjs|cjs)$/.test(e)))||null}const HOST_VAR_RE=/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z_][A-Za-z0-9_]*%/;function hasHostVar(e){return"string"==typeof e&&HOST_VAR_RE.test(e)}function status(e,t={}){const r=t.ctx||hostCtx(),n=t.spec||buildSpec(t.specOpts||{}),s=e&&e.length?e.map((e=>getTarget(e))).filter(Boolean):TARGETS,o=[];for(const
|
|
1
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{TARGETS:TARGETS,getTarget:getTarget,appConfig:appConfig}=require("./targets.js"),{buildSpec:buildSpec,resolveServer:resolveServer}=require("./spec.js");function hostCtx(e={}){return{env:process.env,platform:process.platform,home:null,cwd:process.cwd(),...e}}function readText(e){try{return{text:fs.readFileSync(e,"utf8"),exists:!0}}catch(e){if("ENOENT"===e.code)return{text:null,exists:!1};throw e}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function parseJson(e,t){if(null===e||""===e.trim())return{};try{return JSON.parse(e)}catch(e){throw new Error(`${t} is not valid JSON (${e.message}) — refusing to overwrite it`)}}function setPath(e,t,r){const n=t.split(".");let s=e;for(const e of n.slice(0,-1))(null===s[e]||"object"!=typeof s[e]||Array.isArray(s[e]))&&(s[e]={}),s=s[e];return s[n[n.length-1]]=r,e}function getPath(e,t){let r=e;for(const e of t.split(".")){if(null===r||"object"!=typeof r)return;r=r[e]}return r}function delPath(e,t,r=!1){const n=t.split("."),s=[];let o=e;for(const t of n.slice(0,-1)){if(null===o||"object"!=typeof o)return e;s.push([o,t]),o=o[t]}if(o&&"object"==typeof o&&delete o[n[n.length-1]],!r)return e;for(let e=s.length-1;e>=0;e--){const[t,r]=s[e],n=t[r];if(!n||"object"!=typeof n||0!==Object.keys(n).length)break;delete t[r]}return e}const TOML_BARE=/^[A-Za-z0-9_-]+$/;function tomlKey(e){return TOML_BARE.test(e)?e:JSON.stringify(e)}function tomlString(e){return JSON.stringify(String(e))}function tomlArray(e){return`[${e.map(tomlString).join(", ")}]`}function tomlHeaderName(e){const t=e.trim();return/^\[/.test(t)?t.replace(/^\[+\s*/,"").replace(/\s*\]+$/,""):null}function ownedTomlHeader(e,t){const r=tomlHeaderName(e);return null!==r&&(r===t||r.startsWith(`${t}.`))}function upsertTomlSection(e,t,r){const n=`[${t}]`,s=(e||"").split("\n"),o=[];let i=!1,a=0;for(;a<s.length;)if(s[a].trim()!==n)o.push(s[a]),a++;else{for(o.push(n,...r,""),i=!0,a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++;for(;a<s.length&&ownedTomlHeader(s[a],t);)for(a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++}if(!i){for(;o.length&&""===o[o.length-1].trim();)o.pop();o.length&&o.push(""),o.push(n,...r,"")}return o.join("\n")}function removeTomlSection(e,t){const r=`[${t}]`,n=(e||"").split("\n"),s=[];let o=0;for(;o<n.length;)if(n[o].trim()!==r)s.push(n[o]),o++;else{for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++;for(;o<n.length&&ownedTomlHeader(n[o],t);)for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++}return s.join("\n")}function renderEntry(e,t){if("mcp-toml"===e.kind){const r=[`# Added by \`aegiscode mcp install ${e.id}\`. Key resolution lives in`,"# ~/.aegiscode/.env and the 0600 store `aegiscode login` writes.","command = "+tomlString(t.command),"args = "+tomlArray(t.args)];if(t.env&&Object.keys(t.env).length){r.push("",`[${e.container}.${t.name}.env]`);for(const[e,n]of Object.entries(t.env))r.push(`${tomlKey(e)} = ${tomlString(n)}`)}return r}return e.entry(t)}function planTarget(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(i.exists)try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind){const t=`${e.container}.${s.name}`,r=renderEntry(e,s);return i.before=c,i.after=upsertTomlSection(c,t,r),i.changed=i.after!==(c||""),i}try{a=parseJson(c,o)}catch(e){return i.error=e,i}if(null===a||"object"!=typeof a||Array.isArray(a))return i.error=new Error(`${o} does not contain a JSON object — refusing to overwrite it`),i;if(setPath(a,`${e.container}.${s.name}`,renderEntry(e,s)),"function"==typeof e.extras){const t=e.extras(s);if(t&&t.inputs){const e=Array.isArray(a.inputs)?a.inputs:[];for(const r of t.inputs){const t=e.findIndex((e=>e&&e.id===r.id));-1===t?e.push(r):e[t]=r}a.inputs=e}}return i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==(c||""),i}function planRemove(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(!i.exists)return i;try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind)return i.before=c,i.after=removeTomlSection(c,`${e.container}.${s.name}`),i.changed=i.after!==c,i;try{a=parseJson(c,o)}catch(e){return i.error=e,i}const l=`${e.container}.${s.name}`,u=void 0!==getPath(a,l),f=Array.isArray(a.inputs)&&a.inputs.some((e=>e&&"aegis-api-key"===e.id));if(!u&&!f)return i.before=c,i.after=c,i.changed=!1,i;delPath(a,l,!0);const p=Array.isArray(a.inputs)?a.inputs.filter((e=>!(e&&"aegis-api-key"===e.id))):null;return p&&(p.length?a.inputs=p:delete a.inputs),i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==c,i}function modeFor(e){return e.withKey?384:e.mode||420}function apply(e,t={}){if(e.error)return{...e,applied:!1};if(!e.changed)return{...e,applied:!1};if(t.dryRun)return{...e,applied:!1,dryRun:!0};if(e.withKey=Boolean(t.withKey),fs.mkdirSync(path.dirname(e.file),{recursive:!0}),e.exists&&null!==e.before){const t=`${e.file}.aegis-backup-${Date.now()}`;fs.writeFileSync(t,e.before,{mode:384}),e.backupOf=t}const r=`${e.file}.aegis-tmp-${process.pid}`;try{fs.writeFileSync(r,e.after,{mode:384}),fs.renameSync(r,e.file),fs.chmodSync(e.file,modeFor(e))}finally{try{fs.unlinkSync(r)}catch{}}return{...e,applied:!0}}function parseTomlEntry(e,t){if(!e)return null;const r=t.replace(/[.[\]*+?^$(){}|]/g,"\\$&"),n=new RegExp("^\\s*\\["+r+"\\]\\s*$","m").exec(e);if(!n)return null;const s=e.slice(n.index+n[0].length).split("\n"),o=[];let i=0;for(;i<s.length&&(!/^\s*\[/.test(s[i])||ownedTomlHeader(s[i],t));)o.push(s[i]),i++;const a={command:null,args:[],env:{}},c=/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m.exec(o.join("\n"));c&&(a.command=JSON.parse('"'+c[1]+'"'));const l=/^\s*args\s*=\s*\[([\s\S]*?)\]/m.exec(o.join("\n"));l&&(a.args=[...l[1].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((e=>JSON.parse('"'+e[1]+'"'))));for(const e of o.join("\n").matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/gm))"command"!==e[1]&&"args"!==e[1]&&(a.env[e[1]]=JSON.parse('"'+e[2]+'"'));return a}function entryServerPath(e){return e&&(Array.isArray(e.args)?e.args:[]).find((e=>"string"==typeof e&&/\.(js|mjs|cjs)$/.test(e)))||null}const HOST_VAR_RE=/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z_][A-Za-z0-9_]*%/;function hasHostVar(e){return"string"==typeof e&&HOST_VAR_RE.test(e)}function status(e,t={}){const r=t.ctx||hostCtx(),n=t.spec||buildSpec(t.specOpts||{}),s=e&&e.length?e.map((e=>getTarget(e))).filter(Boolean):TARGETS,o=[];for(const e of s)for(const t of e.scopes||["user"]){const s=e.path(t,r),i={id:e.id,label:e.label,scope:t,file:s,exists:!1,installed:!1,entry:null,error:null,docs:e.docs,verified:e.verified};let a;try{a=readText(s)}catch(e){i.error=e.message,o.push(i);continue}if(i.exists=a.exists,a.exists&&null!==a.text)if("mcp-toml"===e.kind)i.entry=parseTomlEntry(a.text,`${e.container}.${n.name}`),i.installed=Boolean(i.entry);else try{const t=parseJson(a.text,s);i.entry=getPath(t,`${e.container}.${n.name}`)||null,i.installed=Boolean(i.entry)}catch(e){i.error=e.message}i.installed&&(i.serverPath=entryServerPath(i.entry),i.serverUnverifiable=hasHostVar(i.serverPath),i.serverExists=i.serverPath&&!i.serverUnverifiable?isFile(i.serverPath):null),o.push(i)}return o}function detected(e={}){const t=e.ctx||hostCtx(),r=new Set;for(const e of TARGETS)for(const n of e.scopes||["user"])try{fs.accessSync(e.path(n,t)),r.add(e.id)}catch{}for(const[e,n]of[["Code","vscode"],["Code - Insiders","vscode-insiders"],["VSCodium","vscodium"],["Cursor","cursor"]])try{fs.accessSync(path.join(appConfig(t),e)),r.add(n)}catch{}for(const[e,n]of[[[".codeium"],"windsurf"],[[".gemini"],"gemini"],[[".codex"],"codex"],[[".continue"],"continue"],[[".junie"],"junie"],[[".cursor"],"cursor"]])try{fs.accessSync(path.join(t.home||t.env.HOME||t.env.USERPROFILE,...e)),r.add(n)}catch{}return r}module.exports={hostCtx:hostCtx,planTarget:planTarget,planRemove:planRemove,apply:apply,status:status,detected:detected,renderEntry:renderEntry,entryServerPath:entryServerPath,hasHostVar:hasHostVar,parseTomlEntry:parseTomlEntry,upsertTomlSection:upsertTomlSection,removeTomlSection:removeTomlSection,setPath:setPath,getPath:getPath,delPath:delPath,readText:readText,resolveServer:resolveServer};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
2
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),http=require("node:http"),{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js");function resolveModelsModule(){const e=[path.join(__dirname,"..","cli","src","models.js"),path.join(__dirname,"..","..","src","models.js")];for(const t of e)if(fs.existsSync(t))return t;throw new Error(`aegis-shim: cannot find models.js. Expected cli/src/models.js beside hosts/ (source checkout) or src/models.js in the package root (installed). Looked in: ${e.join(", ")}`)}const{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries}=require(resolveModelsModule()),DEFAULT_PORT=8787,DEFAULT_HOST="127.0.0.1",LOOPBACK=new Set(["127.0.0.1","::1","localhost"]);function assertBindAllowed(e,t){if(!LOOPBACK.has(e)&&!t)throw new Error(`refusing to bind ${e}: the shim spends your account's tokens, so it is loopback-only unless you pass --allow-remote`)}const EPOCH=1735689600;function logLine(e,t){e.write(`aegis-shim: ${t}\n`)}function extraFromBody(e){const t={};for(const o of["tools","tool_choice","temperature","top_p","stop","presence_penalty","frequency_penalty"])void 0!==e[o]&&(t[o]=e[o]);const o=e.reasoning_effort||e.effort;return"string"==typeof o&&["low","medium","high"].includes(o.toLowerCase())&&(t.effort=o.toLowerCase()),void 0!==e.workers&&(t.workers=e.workers),t}function sseHead(e){e.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"})}function sseSend(e,t){e.write(`data: ${JSON.stringify(t)}\n\n`)}function chunkFrame(e,t,o,n){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t||"aegis",choices:[{index:0,delta:o,finish_reason:n||null}]}}function createShimServer(e={}){const t=e.client||createClient(credentials.clientOptions()),o=e.host||DEFAULT_HOST,n=void 0===e.port?DEFAULT_PORT:e.port,s=e.log||process.stderr,r=!1!==e.requireKey,a=e.fetchModels||(()=>t.listModels());assertBindAllowed(o,e.allowRemote);let i={at:0,models:[]};function c(e,t,o){const n=JSON.stringify(o);e.writeHead(t,{"Content-Type":"application/json; charset=utf-8","Content-Length":Buffer.byteLength(n)}),e.end(n)}function l(e,t,o,n){c(e,t,{error:{message:o,type:n||"aegis_error",code:t}})}function d(e){if(!r)return!0;const t=e.headers.authorization||"",o=/^Bearer\s+(.+)$/i.exec(t);return Boolean(o&&o[1].trim())}const m=http.createServer(((e,s)=>{const r=new URL(e.url||"/",`http://${e.headers.host||"127.0.0.1"}`).pathname.replace(/\/+$/,"")||"/";return"GET"!==e.method||"/health"!==r&&"/"!==r?"GET"!==e.method||"/v1/models"!==r&&"/models"!==r?"POST"!==e.method||"/v1/chat/completions"!==r&&"/chat/completions"!==r?"POST"===e.method&&"/v1/messages"===r?l(s,404,"this endpoint speaks the OpenAI schema; point the client at /v1 with the OpenAI provider","invalid_request_error"):l(s,404,`no such route: ${e.method} ${r}`,"invalid_request_error"):d(e)?async function(e,o){let n;try{n=await async function(e){const t=[];let o=0;for await(const n of e){if(o+=n.length,o>8388608)throw new Error("request body too large");t.push(n)}const n=Buffer.concat(t).toString("utf8");return n.trim()?JSON.parse(n):{}}(e)}catch(e){return l(o,400,`invalid JSON body: ${e.message}`,"invalid_request_error")}const s=Array.isArray(n.messages)?n.messages:null;if(!s||!s.length)return l(o,400,"`messages` is required","invalid_request_error");const r=!0===n.stream,a=`chatcmpl-aegis-${Date.now().toString(36)}`,i=n.model&&"aegis-default"!==n.model?String(n.model):void 0,d={messages:s,model:i,maxTokens:n.max_tokens||n.max_completion_tokens,extra:extraFromBody(n),includeUsage:r};if(!r)try{const e=await t.chatCompletion({...d,stream:!1}),n=e.choices&&e.choices[0]&&e.choices[0].message||{content:""};return c(o,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:e.model||i||"aegis",choices:[{index:0,message:{role:"assistant",...n},finish_reason:n.tool_calls?"tool_calls":"stop"}],usage:e.usage||void 0})}catch(e){return l(o,e.status&&e.status>=400&&e.status<600?e.status:502,e.message)}sseHead(o);let m=!1;e.on("close",(()=>{m=!0}));const u=e=>{m||sseSend(o,e)};u(chunkFrame(a,i,{role:"assistant",content:""}));try{const e=await t.chatCompletion({...d,stream:!0,onStream:e=>{e.delta?u(chunkFrame(a,i,{content:e.delta})):e.reasoning&&u(chunkFrame(a,i,{reasoning_content:e.reasoning}))},onReasoning:e=>u(chunkFrame(a,i,{reasoning_content:e}))}),n=e.choices&&e.choices[0]&&e.choices[0].message||{};Array.isArray(n.tool_calls)&&n.tool_calls.length&&u(chunkFrame(a,i,{tool_calls:n.tool_calls.map(((e,t)=>({index:t,id:e.id,type:"function",function:{name:e.function&&e.function.name,arguments:e.function&&e.function.arguments||""}})))})),u(chunkFrame(a,i,{},n.tool_calls&&n.tool_calls.length?"tool_calls":"stop")),e.usage&&u({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.model||i||"aegis",choices:[],usage:e.usage}),m||(o.write("data: [DONE]\n\n"),o.end())}catch(e){u({error:{message:e.message,type:"aegis_error"}}),m||(o.write("data: [DONE]\n\n"),o.end())}}(e,s):l(s,401,"missing API key — any non-empty value works locally","invalid_request_error"):d(e)?async function(e){c(e,200,{object:"list",data:(await async function(){if(Date.now()-i.at<6e4&&i.models.length)return i.models;const e=await a();return i={at:Date.now(),models:pickerEntries(normalizeModelCatalog(e&&e.models?e.models:e))},i.models}()).map((e=>({id:e.id,object:"model",created:EPOCH,owned_by:"aegis",...e.label&&e.label!==e.id?{name:e.label}:{}})))})}(s).catch((e=>l(s,502,e.message))):l(s,401,"missing API key — any non-empty value works locally","invalid_request_error"):c(s,200,{ok:!0,service:"aegis-openai-shim",endpoint:`http://${o}:${n}/v1`})}));var u;return m.listen=(u=m.listen,function(...e){return u.apply(m,e)}),{server:m,host:o,port:n,url:`http://${o}:${n}/v1`,listen:()=>new Promise(((e,t)=>{m.once("error",t),m.listen(n,o,(()=>{const t=m.address();logLine(s,`OpenAI-compatible endpoint on http://${o}:${t.port}/v1`),logLine(s,"point any OpenAI-compatible client at that base URL (any API key value)"),e(t)}))})),close:()=>new Promise((e=>m.close(e)))}}function parseArgv(e){const t={log:process.stderr};for(let o=0;o<e.length;o++){const n=e[o];"--port"===n?t.port=Number(e[++o]):"--host"===n?t.host=e[++o]:"--allow-remote"===n?t.allowRemote=!0:"--no-auth"===n?t.requireKey=!1:"--help"!==n&&"-h"!==n||(t.help=!0)}return t}async function main(e){const t=parseArgv(e);if(t.help)return process.stdout.write(["aegis openai shim — serve AEGIS as an OpenAI-compatible endpoint",""," node hosts/openai-shim.js [--port 8787] [--host 127.0.0.1] [--allow-remote] [--no-auth]","","Then point a coding tool at it:"," base URL http://127.0.0.1:8787/v1"," API key anything non-empty (the AEGIS key is read from ~/.aegiscode/.env)",""].join("\n")),0;const o=t.log||process.stderr;try{assertBindAllowed(t.host||DEFAULT_HOST,t.allowRemote)}catch(e){return logLine(o,e.message),1}try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&logLine(o,`${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it`)}catch(e){logLine(o,`could not read the shared env file: ${e&&e.message}`)}const n=credentials.resolveApiKey();if(!n.key)return logLine(o,`no AEGIS account key — ${credentials.HOW_TO_SET}, or set ${credentials.KEY_ENV} in ~/.aegiscode/.env`),1;let s;logLine(o,`AEGIS key: ${credentials.sourceLabel(n.source)}`);try{s=createShimServer(t),await s.listen()}catch(e){return logLine(process.stderr,e.message),1}const r=async()=>{await s.close(),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",r),null}require.main===module&&main(process.argv.slice(2)).then((e=>{"number"==typeof e&&process.exit(e)})).catch((e=>{logLine(process.stderr,e&&e.message?e.message:e),process.exit(1)})),module.exports={createShimServer:createShimServer,extraFromBody:extraFromBody,DEFAULT_PORT:DEFAULT_PORT};
|
package/vendor/mcp/server.js
CHANGED
|
@@ -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
|
-
const{createClient:
|
|
4
|
+
"use strict";const{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js"),{autoProvisionApiKey:autoProvisionApiKey}=require("../client/auto-provision.js"),{createTools:createTools}=require("./tools.js");try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&process.stderr.write(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch{}const aegis=createClient(credentials.clientOptions()),{TOOLS:TOOLS,toolList:toolList}=createTools(aegis),API_BASE=aegis.apiBase,SERVER_NAME="aegis",SERVER_VERSION="0.4.0";function missingKeyText(){const{path:e}=credentials.keyStatus();return["No AEGIS API key is configured for this session.","","Set one with any of:"," • `aegiscode login` in a terminal (saves it to "+e+", mode 0600)"," • export AEGIS_API_KEY=… in the environment Claude Code was launched from"," • put `AEGIS_API_KEY=…` in ~/.aegiscode/.env (read at startup, every host)","","Then restart Claude Code. Get a key at https://aegiscloud.org."].join("\n")}let provisionAttempted=!1;async function ensureApiKey(){if(aegis.apiKey||provisionAttempted)return;provisionAttempted=!0;const e=await autoProvisionApiKey(aegis,credentials,{app:"mcp"});e.error?process.stderr.write(`aegis: device auto-registration failed (${e.error.message}) — falling back to manual setup.\n`):e.key?process.stderr.write("aegis: no API key was configured — auto-provisioned a free AEGIS account"+(e.ok?` (key saved to ${credentials.keyStatus().path}).\n`:" (could not save it — see above).\n")+`Fund it at ${aegis.promptUrl("topup","device_autoprovision")} or set your own BYOK key with aegis_byok_set.\n`):process.stderr.write("aegis: device auto-registration returned no usable key — falling back to manual setup.\n")}function send(e){process.stdout.write(JSON.stringify(e)+"\n")}function reply(e,t){send({jsonrpc:"2.0",id:e,result:t})}function replyError(e,t,i){send({jsonrpc:"2.0",id:e,error:{code:t,message:i}})}let pending=0,stdinClosed=!1;function maybeExit(){stdinClosed&&0===pending&&process.exit(0)}async function handleMessage(e){const{id:t,method:i,params:o}=e,r=null==t;try{switch(i){case"initialize":return void reply(t,{protocolVersion:o&&o.protocolVersion||"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"aegis",version:"0.4.0"}});case"notifications/initialized":case"notifications/cancelled":return;case"ping":return void(r||reply(t,{}));case"tools/list":return void reply(t,{tools:toolList()});case"tools/call":{const e=o&&o.name,i=TOOLS[e];if(!i)return void reply(t,{content:[{type:"text",text:`Unknown tool: ${e}`}],isError:!0});if(aegis.apiKey||await ensureApiKey(),!aegis.apiKey)return void reply(t,{content:[{type:"text",text:missingKeyText()}],isError:!0});try{reply(t,{content:[{type:"text",text:await i.run(o&&o.arguments||{})}],isError:!1})}catch(e){reply(t,{content:[{type:"text",text:`AEGIS error: ${e.message}`}],isError:!0})}return}default:return void(r||replyError(t,-32601,`Method not found: ${i}`))}}catch(e){r||replyError(t,-32603,e.message)}}let buffer="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(e=>{let t;for(buffer+=e;-1!==(t=buffer.indexOf("\n"));){const e=buffer.slice(0,t).trim();if(buffer=buffer.slice(t+1),!e)continue;let i;try{i=JSON.parse(e)}catch{continue}pending++,Promise.resolve(handleMessage(i)).finally((()=>{pending--,maybeExit()}))}})),process.stdin.on("end",(()=>{stdinClosed=!0,maybeExit()}));
|
package/vendor/mcp/tools.js
CHANGED
|
@@ -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 foreignMemory=require("../client/foreign-memory.js");function createTools(e){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const t=e,o={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${t.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const o=await t.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),s=o.choices&&o.choices[0]||{};return`${s.message&&s.message.content||"(empty response)"}\n\n— ${[o.model?`model: ${o.model}`:null,o.usage?`tokens: ${o.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map((e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`))].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.tokenBankBalance(),o=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],s=(e.ledger||[]).slice(0,5);if(s.length){o.push("","Recent activity:");for(const e of s){const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,s=Math.abs(t),r=`${t<0?"-":"+"}€${s<.01?s.toFixed(4):s.toFixed(2)}`,i="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||i||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";o.push(` ${e.created_at||""} ${n}${a} ${r}`)}}else o.push("No spend yet.");var r;return(e.balance_eur||0)<=0&&o.push("",`Balance is empty — top up at ${r="topup","function"==typeof t.promptUrl?t.promptUrl(r,"topup_bank"):`https://aegiscloud.org/go/${r}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),o.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const o=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const t of e){const e=(t.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean),s=t.configured?" ✓ set"+(t.masked?` (${t.masked})`:""):"";o.push(""),o.push(` ${t.id}${s}`),t.label&&o.push(` ${t.label}`),e.length&&o.push(` models: ${e.join(", ")}`),t.key_prefix&&o.push(` key starts with: ${t.key_prefix}`),t.key_url&&o.push(` get a key: ${t.key_url}`)}return o.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.byokStatus(),o=Object.entries(e||{});if(!o.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let s={};try{const e=await t.byokProviders();for(const t of e.providers||[])s[t.id]=t.label||""}catch{}return`BYOK keys:\n${o.map((([e,t])=>{const o=t&&t.set;return` ${e}${s[e]?` ${s[e]}`:""}: ${o?`set (${t.masked})`:"not set"}`})).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await t.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const o=(await t.memorySearch(e.query,e.limit||5)).entries||[];return o.length?o.map(((e,t)=>{const o=e.timestamp||e.createdAt||"",s=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";return`${t+1}. ${e.content}${s}${o?`\n (${o})`:""}`})).join("\n"):`No memory entries matched "${e.query}".`}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const o={id:t.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await t.memorySave(o)).saved||1} memory entry (id ${o.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const o=e.limit||1e3,s=foreignMemory.scan({sources:e.sources,limit:o}),r=foreignMemory.describe(s);if(!s.entries.length)return`${r}\n\nNothing to import.`;if(!e.confirm)return[r,"",`Dry run — ${s.totals.entries} entries would be saved to AEGIS memory under ${s.totals.sourcesWithEntries} session(s) (${s.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let i=0;const n=[];for(const o of foreignMemory.chunk(s.entries,200))try{const e=await t.memorySaveBatch(o);i+=e&&e.saved||o.length}catch(e){n.push(e.message);break}return n.length?`${r}\n\nSaved ${i} of ${s.totals.entries} entries, then stopped: ${n[0]}`:`${r}\n\nSaved ${i} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const o=(await t.memoryList(e.limit||10)).entries||[];if(!o.length)return"AEGIS cloud memory is empty.";const s=o.map(((e,t)=>`${t+1}. ${e.content}`)).join("\n");return`Recent ${o.length} entries:\n${s}`}}};return{TOOLS:o,toolList:function(){return Object.entries(o).map((([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema})))}}}module.exports={createTools:createTools};
|
|
3
|
+
"use strict";const foreignMemory=require("../client/foreign-memory.js");function createTools(e){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const t=e,o={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${t.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const o=await t.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),s=o.choices&&o.choices[0]||{};return`${s.message&&s.message.content||"(empty response)"}\n\n— ${[o.model?`model: ${o.model}`:null,o.usage?`tokens: ${o.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map((e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`))].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.tokenBankBalance(),o=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],s=(e.ledger||[]).slice(0,5);if(s.length){o.push("","Recent activity:");for(const e of s){const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,s=Math.abs(t),r=`${t<0?"-":"+"}€${s<.01?s.toFixed(4):s.toFixed(2)}`,i="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||i||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";o.push(` ${e.created_at||""} ${n}${a} ${r}`)}}else o.push("No spend yet.");var r;return(e.balance_eur||0)<=0&&o.push("",`Balance is empty — top up at ${r="topup","topup_bank","function"==typeof t.promptUrl?t.promptUrl(r,"topup_bank"):`https://aegiscloud.org/go/${r}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),o.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const o=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const t of e){const e=(t.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean),s=t.configured?" ✓ set"+(t.masked?` (${t.masked})`:""):"";o.push(""),o.push(` ${t.id}${s}`),t.label&&o.push(` ${t.label}`),e.length&&o.push(` models: ${e.join(", ")}`),t.key_prefix&&o.push(` key starts with: ${t.key_prefix}`),t.key_url&&o.push(` get a key: ${t.key_url}`)}return o.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.byokStatus(),o=Object.entries(e||{});if(!o.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let s={};try{const e=await t.byokProviders();for(const t of e.providers||[])s[t.id]=t.label||""}catch{}return`BYOK keys:\n${o.map((([e,t])=>{const o=t&&t.set;return` ${e}${s[e]?` ${s[e]}`:""}: ${o?`set (${t.masked})`:"not set"}`})).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await t.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const o=(await t.memorySearch(e.query,e.limit||5)).entries||[];return o.length?o.map(((e,t)=>{const o=e.timestamp||e.createdAt||"",s=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";return`${t+1}. ${e.content}${s}${o?`\n (${o})`:""}`})).join("\n"):`No memory entries matched "${e.query}".`}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const o={id:t.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await t.memorySave(o)).saved||1} memory entry (id ${o.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const o=e.limit||1e3,s=foreignMemory.scan({sources:e.sources,limit:o}),r=foreignMemory.describe(s);if(!s.entries.length)return`${r}\n\nNothing to import.`;if(!e.confirm)return[r,"",`Dry run — ${s.totals.entries} entries would be saved to AEGIS memory under ${s.totals.sourcesWithEntries} session(s) (${s.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let i=0;const n=[];for(const e of foreignMemory.chunk(s.entries,200))try{const o=await t.memorySaveBatch(e);i+=o&&o.saved||e.length}catch(e){n.push(e.message);break}return n.length?`${r}\n\nSaved ${i} of ${s.totals.entries} entries, then stopped: ${n[0]}`:`${r}\n\nSaved ${i} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const o=(await t.memoryList(e.limit||10)).entries||[];if(!o.length)return"AEGIS cloud memory is empty.";const s=o.map(((e,t)=>`${t+1}. ${e.content}`)).join("\n");return`Recent ${o.length} entries:\n${s}`}}};return{TOOLS:o,toolList:function(){return Object.entries(o).map((([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema})))}}}module.exports={createTools:createTools};
|
|
@@ -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"),FACE=Object.freeze({TUI:"tui",GUI:"gui"}),RUN_AS_NODE="ELECTRON_RUN_AS_NODE",FORCE_TUI=["--tui","code"],COMPAT_BIN="aegiscode";function faceRoot(e,n){return path.join(e,"faces",n)}function cliEntry(e){return path.join(faceRoot(e,"cli"),"bin","aegiscode.js")}function binName(e){return path.basename(String(e||"aegis")).replace(/\.(exe|cmd|bat|AppImage)$/i,"").replace(/\.js$/,"")}function plan(e){const n=e||{};if(!n.packaged)return null;const t=n.execPath,a=n.resourcesPath,i=Array.isArray(n.argv)?n.argv.map(String):[];if(!t||!a)return null;const r=(e,n)=>({face:FACE.TUI,exec:t,args:[cliEntry(a),...e],env:{[RUN_AS_NODE]:"1"},reason:n});if(binName(n.invokedAs)===COMPAT_BIN)return r(i,"aegiscode is the compatibility bin");const c=i.find((e=>FORCE_TUI.includes(e)));return c?r(i.filter((e=>e!==c)),`${c} asks for the terminal face`):null}function spawnOptions(e,n){return e?{exec:e.exec,args:e.args,env:Object.assign({},n||{},e.env)}:null}module.exports={plan:plan,spawnOptions:spawnOptions,FACE:FACE,RUN_AS_NODE:RUN_AS_NODE,COMPAT_BIN:COMPAT_BIN,FORCE_TUI:FORCE_TUI,cliEntry:cliEntry,faceRoot:faceRoot,binName:binName};
|