aegiscode 7.0.16 → 7.0.17

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.
Files changed (43) hide show
  1. package/bin/aegiscode.js +1 -0
  2. package/package.json +2 -3
  3. package/src/app.js +1 -1
  4. package/src/art.js +1 -1
  5. package/src/chatflow.js +1 -1
  6. package/src/commands.js +1 -1
  7. package/src/credentials.js +1 -1
  8. package/src/diffview.js +1 -1
  9. package/src/engine.js +1 -1
  10. package/src/export.js +1 -1
  11. package/src/history.js +1 -1
  12. package/src/init.js +1 -1
  13. package/src/limits.js +1 -1
  14. package/src/models.js +1 -1
  15. package/src/overlays.js +1 -1
  16. package/src/panels.js +1 -1
  17. package/src/provenance.lock.json +2 -2
  18. package/src/screens.js +1 -1
  19. package/src/theme.js +1 -1
  20. package/vendor/client/aegis.js +1 -1
  21. package/vendor/client/attest.js +1 -1
  22. package/vendor/client/byok-catalog.js +1 -1
  23. package/vendor/client/catalog-client.js +3 -0
  24. package/vendor/client/conversation-export.js +3 -0
  25. package/vendor/client/credentials.js +1 -1
  26. package/vendor/client/drive-upload.js +1 -1
  27. package/vendor/client/env-file.js +1 -1
  28. package/vendor/client/platform.js +1 -1
  29. package/vendor/client/session-store.js +1 -1
  30. package/vendor/desktop/lib/local/attachments.js +3 -0
  31. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  32. package/vendor/desktop/lib/local/context.js +1 -1
  33. package/vendor/desktop/lib/local/engine.js +1 -1
  34. package/vendor/desktop/lib/local/exec-plan.js +3 -0
  35. package/vendor/desktop/lib/local/local.js +1 -1
  36. package/vendor/desktop/lib/local/prompt.js +1 -1
  37. package/vendor/desktop/lib/local/session-rounds.js +1 -1
  38. package/vendor/desktop/lib/local/shell.js +1 -1
  39. package/vendor/desktop/lib/local/spill.js +3 -0
  40. package/vendor/desktop/lib/local/tools.js +1 -1
  41. package/vendor/hosts/openai-shim.js +1 -1
  42. package/vendor/mcp/server.js +1 -1
  43. package/vendor/one/src/permissions.js +1 -1
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const e=require("node:fs"),t=require("node:path"),o=require("node:http"),{createClient:n}=require("../client/aegis.js"),s=require("../client/credentials.js"),{normalizeModelCatalog:r,pickerEntries:a}=require(function(){const o=[t.join(__dirname,"..","cli","src","models.js"),t.join(__dirname,"..","..","src","models.js")];for(const t of o)if(e.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: ${o.join(", ")}`)}()),i="127.0.0.1",c=new Set(["127.0.0.1","::1","localhost"]);function l(e,t){if(!c.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`)}function d(e,t){e.write(`aegis-shim: ${t}\n`)}function u(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 m(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 h(e={}){const t=e.client||n(s.clientOptions()),c=e.host||i,h=void 0===e.port?8787:e.port,p=e.log||process.stderr,g=!1!==e.requireKey,f=e.fetchModels||(()=>t.listModels());l(c,e.allowRemote);let y={at:0,models:[]};function w(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 _(e,t,o,n){w(e,t,{error:{message:o,type:n||"aegis_error",code:t}})}function v(e){if(!g)return!0;const t=e.headers.authorization||"",o=/^Bearer\s+(.+)$/i.exec(t);return Boolean(o&&o[1].trim())}const k=o.createServer(((e,o)=>{const n=new URL(e.url||"/",`http://${e.headers.host||"127.0.0.1"}`).pathname.replace(/\/+$/,"")||"/";return"GET"!==e.method||"/health"!==n&&"/"!==n?"GET"!==e.method||"/v1/models"!==n&&"/models"!==n?"POST"!==e.method||"/v1/chat/completions"!==n&&"/chat/completions"!==n?"POST"===e.method&&"/v1/messages"===n?_(o,404,"this endpoint speaks the OpenAI schema; point the client at /v1 with the OpenAI provider","invalid_request_error"):_(o,404,`no such route: ${e.method} ${n}`,"invalid_request_error"):v(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 _(o,400,`invalid JSON body: ${e.message}`,"invalid_request_error")}const s=Array.isArray(n.messages)?n.messages:null;if(!s||!s.length)return _(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,c={messages:s,model:i,maxTokens:n.max_tokens||n.max_completion_tokens,extra:u(n),includeUsage:r};if(!r)try{const e=await t.chatCompletion({...c,stream:!1}),n=e.choices&&e.choices[0]&&e.choices[0].message||{content:""};return w(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 _(o,e.status&&e.status>=400&&e.status<600?e.status:502,e.message)}!function(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"})}(o);let l=!1;e.on("close",(()=>{l=!0}));const d=e=>{l||function(e,t){e.write(`data: ${JSON.stringify(t)}\n\n`)}(o,e)};d(m(a,i,{role:"assistant",content:""}));try{const e=await t.chatCompletion({...c,stream:!0,onStream:e=>{e.delta?d(m(a,i,{content:e.delta})):e.reasoning&&d(m(a,i,{reasoning_content:e.reasoning}))},onReasoning:e=>d(m(a,i,{reasoning_content:e}))}),n=e.choices&&e.choices[0]&&e.choices[0].message||{};Array.isArray(n.tool_calls)&&n.tool_calls.length&&d(m(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||""}})))})),d(m(a,i,{},n.tool_calls&&n.tool_calls.length?"tool_calls":"stop")),e.usage&&d({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.model||i||"aegis",choices:[],usage:e.usage}),l||(o.write("data: [DONE]\n\n"),o.end())}catch(e){d({error:{message:e.message,type:"aegis_error"}}),l||(o.write("data: [DONE]\n\n"),o.end())}}(e,o):_(o,401,"missing API key — any non-empty value works locally","invalid_request_error"):v(e)?async function(e){w(e,200,{object:"list",data:(await async function(){if(Date.now()-y.at<6e4&&y.models.length)return y.models;const e=await f();return y={at:Date.now(),models:a(r(e&&e.models?e.models:e))},y.models}()).map((e=>({id:e.id,object:"model",created:1735689600,owned_by:"aegis",...e.label&&e.label!==e.id?{name:e.label}:{}})))})}(o).catch((e=>_(o,502,e.message))):_(o,401,"missing API key — any non-empty value works locally","invalid_request_error"):w(o,200,{ok:!0,service:"aegis-openai-shim",endpoint:`http://${c}:${h}/v1`})}));var b;return k.listen=(b=k.listen,function(...e){return b.apply(k,e)}),{server:k,host:c,port:h,url:`http://${c}:${h}/v1`,listen:()=>new Promise(((e,t)=>{k.once("error",t),k.listen(h,c,(()=>{const t=k.address();d(p,`OpenAI-compatible endpoint on http://${c}:${t.port}/v1`),d(p,"point any OpenAI-compatible client at that base URL (any API key value)"),e(t)}))})),close:()=>new Promise((e=>k.close(e)))}}require.main===module&&async function(e){const t=function(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}(process.argv.slice(2));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{l(t.host||i,t.allowRemote)}catch(e){return d(o,e.message),1}try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&d(o,`${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it`)}catch(e){d(o,`could not read the shared env file: ${e&&e.message}`)}const n=s.resolveApiKey();if(!n.key)return d(o,`no AEGIS account key — ${s.HOW_TO_SET}, or set ${s.KEY_ENV} in ~/.aegiscode/.env`),1;let r;d(o,`AEGIS key: ${s.sourceLabel(n.source)}`);try{r=h(t),await r.listen()}catch(e){return d(process.stderr,e.message),1}const a=async()=>{await r.close(),process.exit(0)};return process.on("SIGINT",a),process.on("SIGTERM",a),null}().then((e=>{"number"==typeof e&&process.exit(e)})).catch((e=>{d(process.stderr,e&&e.message?e.message:e),process.exit(1)})),module.exports={createShimServer:h,extraFromBody:u,DEFAULT_PORT:8787};
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};
@@ -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:e}=require("../client/aegis.js"),t=require("../client/credentials.js"),{autoProvisionApiKey:o}=require("../client/auto-provision.js"),{createTools:i}=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 n=e(t.clientOptions()),{TOOLS:r,toolList:s}=i(n);function a(){const{path:e}=t.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")}n.apiBase;let c=!1;function l(e){process.stdout.write(JSON.stringify(e)+"\n")}function u(e,t){l({jsonrpc:"2.0",id:e,result:t})}function d(e,t,o){l({jsonrpc:"2.0",id:e,error:{code:t,message:o}})}let p=0,f=!1;function y(){f&&0===p&&process.exit(0)}async function g(e){const{id:i,method:l,params:p}=e,f=null==i;try{switch(l){case"initialize":return void u(i,{protocolVersion:p&&p.protocolVersion||"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"aegis",version:"0.4.0"}});case"notifications/initialized":case"notifications/cancelled":return;case"ping":return void(f||u(i,{}));case"tools/list":return void u(i,{tools:s()});case"tools/call":{const e=p&&p.name,s=r[e];if(!s)return void u(i,{content:[{type:"text",text:`Unknown tool: ${e}`}],isError:!0});if(n.apiKey||await async function(){if(n.apiKey||c)return;c=!0;const e=await o(n,t,{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 ${t.keyStatus().path}).\n`:" (could not save it — see above).\n")+`Fund it at ${n.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")}(),!n.apiKey)return void u(i,{content:[{type:"text",text:a()}],isError:!0});try{u(i,{content:[{type:"text",text:await s.run(p&&p.arguments||{})}],isError:!1})}catch(e){u(i,{content:[{type:"text",text:`AEGIS error: ${e.message}`}],isError:!0})}return}default:return void(f||d(i,-32601,`Method not found: ${l}`))}}catch(e){f||d(i,-32603,e.message)}}let v="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(e=>{let t;for(v+=e;-1!==(t=v.indexOf("\n"));){const e=v.slice(0,t).trim();if(v=v.slice(t+1),!e)continue;let o;try{o=JSON.parse(e)}catch{continue}p++,Promise.resolve(g(o)).finally((()=>{p--,y()}))}})),process.stdin.on("end",(()=>{f=!0,y()}));
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()}));
@@ -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 path=require("node:path"),CHILD_KINDS=Object.freeze({HEADLESS:"headless",INTERACTIVE:"interactive"}),CONFIGURABLE_CLASSES=Object.freeze(["exec","writeFile","editFile"]),SKIP_FLAG="--dangerously-skip-permissions",FROZEN_CLASSES=Object.freeze(["write","shell","network","offDevice"]),PERMISSION_MODES=Object.freeze(["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]);let cachedEvaluator=null,cachedConfig=null;function loadEvaluator(e){if(e)return e;if(cachedEvaluator)return cachedEvaluator;const o=[path.join(__dirname,"..","..","cli","src","permissions.js"),path.join(__dirname,"..","vendor","cli","src","permissions.js")];for(const e of o)try{const o=require(e);if(o&&"function"==typeof o.evalPermission&&"function"==typeof o.resolveSkip)return cachedEvaluator=o,o}catch{}throw new Error("aegis: the one rule evaluator (cli/src/permissions.js) is missing from this install — refusing to resolve a permission posture from a second, unshared rule engine.")}function loadConfigStore(e){if(e)return e;if(cachedConfig)return cachedConfig;const o=[path.join(__dirname,"..","..","cli","src","config.js"),path.join(__dirname,"..","vendor","cli","src","config.js")];for(const e of o)try{const o=require(e);if(o&&"function"==typeof o.confirmPosture)return cachedConfig=o,o}catch{}return null}function storedPermissionFacts(e={}){const o=loadConfigStore(e.config);if(!o)return{confirmationsOn:void 0,rules:void 0,source:"unavailable"};try{const e=o.confirmPosture();let r;try{r=o.loadPermissions()}catch{r=void 0}return{confirmationsOn:e&&"boolean"==typeof e.enabled?e.enabled:void 0,rules:r,source:e&&e.source||"unavailable"}}catch{return{confirmationsOn:void 0,rules:void 0,source:"unavailable"}}}function normalizeRules(e){const o=e&&"object"==typeof e?e:{},r=e=>Array.isArray(e)?e.map(String):[];return Object.freeze({defaultMode:"allow"===o.defaultMode||"deny"===o.defaultMode?o.defaultMode:"ask",allow:Object.freeze(r(o.allow)),deny:Object.freeze(r(o.deny)),ask:Object.freeze(r(o.ask)),explicitAsk:!0===o.explicitAsk||"ask"===o.defaultMode})}function resolvePosture(e={},o={}){const r=loadEvaluator(o.evaluator),s=normalizeRules(e.rules),i=!0===e.interactive,a=e.childKind===CHILD_KINDS.INTERACTIVE?CHILD_KINDS.INTERACTIVE:CHILD_KINDS.HEADLESS,n=r.resolveSkip({flag:!0===e.flag,env:e.env,interactive:i}),t=!1===e.gate,l=n.skip||t,c=n.skip?n.source:t?"posture":n.source,u=a===CHILD_KINDS.INTERACTIVE;return Object.freeze({version:1,rules:s,interactive:i,childKind:a,skip:l,skipSource:c,skipFromFlag:n.skip,envVarSet:n.envSet,storedGate:void 0===e.gate||null===e.gate?null:Boolean(e.gate),warned:n.warned,warning:n.warning||null,skipped:Object.freeze(l?CONFIGURABLE_CLASSES:[]),frozen:FROZEN_CLASSES,child:Object.freeze({kind:a,skip:l,flag:l?u?"--allow-dangerously-skip-permissions":"--dangerously-skip-permissions":null,why:l?u?"the interactive variant offers the bypass as an option (the child still asks; a human is there)":"the headless variant takes the bypass as a default, because no one can answer the child's prompt":"no skip was asked for, so no permission flag is passed to the child"})})}function gateFor(e,o,r,s={}){const i=loadEvaluator(s.evaluator),a=e&&e.rules?e.rules:normalizeRules({}),n=i.evalPermission(o,r,a);return"deny"===n?"deny":"allow"===n||e&&e.skip?"allow":"ask"}function skipReport(e){if(!e||!e.skip)return null;const o=e.child.flag?`; the ${e.child.kind} Claude child is passed ${e.child.flag}`:"";return`aegis: ${"posture"===e.skipSource?"automode (the stored confirmation posture both faces share)":"--dangerously-skip-permissions"} (via ${e.skipSource}) — skipping the configurable confirmation gates (${CONFIGURABLE_CLASSES.join(", ")})${o}. NOT skipped, and not reachable by any setting, flag or env var: the ÆGIS covenant pre-action assert and the ${FROZEN_CLASSES.join("|")} approvals (always 'ask'), plus any explicit deny rule.`}module.exports={CHILD_KINDS:CHILD_KINDS,CONFIGURABLE_CLASSES:CONFIGURABLE_CLASSES,FROZEN_CLASSES:FROZEN_CLASSES,PERMISSION_MODES:PERMISSION_MODES,SKIP_FLAG:SKIP_FLAG,loadEvaluator:loadEvaluator,loadConfigStore:loadConfigStore,storedPermissionFacts:storedPermissionFacts,normalizeRules:normalizeRules,resolvePosture:resolvePosture,gateFor:gateFor,skipReport:skipReport};
3
+ "use strict";const path=require("node:path"),CHILD_KINDS=Object.freeze({HEADLESS:"headless",INTERACTIVE:"interactive"}),CONFIGURABLE_CLASSES=Object.freeze(["exec","writeFile","editFile"]),SKIP_FLAG="--dangerously-skip-permissions",FROZEN_CLASSES=Object.freeze(["write","shell","network","offDevice"]),PERMISSION_MODES=Object.freeze(["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]);let cachedEvaluator=null,cachedConfig=null;function loadEvaluator(e){if(e)return e;if(cachedEvaluator)return cachedEvaluator;const o=[path.join(__dirname,"..","..","cli","src","permissions.js"),path.join(__dirname,"..","vendor","cli","src","permissions.js"),path.join(__dirname,"..","..","..","src","permissions.js")];for(const e of o)try{const o=require(e);if(o&&"function"==typeof o.evalPermission&&"function"==typeof o.resolveSkip)return cachedEvaluator=o,o}catch{}throw new Error("aegis: the one rule evaluator (cli/src/permissions.js) is missing from this install — refusing to resolve a permission posture from a second, unshared rule engine.")}function loadConfigStore(e){if(e)return e;if(cachedConfig)return cachedConfig;const o=[path.join(__dirname,"..","..","cli","src","config.js"),path.join(__dirname,"..","vendor","cli","src","config.js"),path.join(__dirname,"..","..","..","src","config.js")];for(const e of o)try{const o=require(e);if(o&&"function"==typeof o.confirmPosture)return cachedConfig=o,o}catch{}return null}function storedPermissionFacts(e={}){const o=loadConfigStore(e.config);if(!o)return{confirmationsOn:void 0,rules:void 0,source:"unavailable"};try{const e=o.confirmPosture();let r;try{r=o.loadPermissions()}catch{r=void 0}return{confirmationsOn:e&&"boolean"==typeof e.enabled?e.enabled:void 0,rules:r,source:e&&e.source||"unavailable"}}catch{return{confirmationsOn:void 0,rules:void 0,source:"unavailable"}}}function normalizeRules(e){const o=e&&"object"==typeof e?e:{},r=e=>Array.isArray(e)?e.map(String):[];return Object.freeze({defaultMode:"allow"===o.defaultMode||"deny"===o.defaultMode?o.defaultMode:"ask",allow:Object.freeze(r(o.allow)),deny:Object.freeze(r(o.deny)),ask:Object.freeze(r(o.ask)),explicitAsk:!0===o.explicitAsk||"ask"===o.defaultMode})}function resolvePosture(e={},o={}){const r=loadEvaluator(o.evaluator),s=normalizeRules(e.rules),i=!0===e.interactive,n=e.childKind===CHILD_KINDS.INTERACTIVE?CHILD_KINDS.INTERACTIVE:CHILD_KINDS.HEADLESS,a=r.resolveSkip({flag:!0===e.flag,env:e.env,interactive:i}),t=!1===e.gate,l=a.skip||t,c=a.skip?a.source:t?"posture":a.source,u=n===CHILD_KINDS.INTERACTIVE;return Object.freeze({version:1,rules:s,interactive:i,childKind:n,skip:l,skipSource:c,skipFromFlag:a.skip,envVarSet:a.envSet,storedGate:void 0===e.gate||null===e.gate?null:Boolean(e.gate),warned:a.warned,warning:a.warning||null,skipped:Object.freeze(l?CONFIGURABLE_CLASSES:[]),frozen:FROZEN_CLASSES,child:Object.freeze({kind:n,skip:l,flag:l?u?"--allow-dangerously-skip-permissions":"--dangerously-skip-permissions":null,why:l?u?"the interactive variant offers the bypass as an option (the child still asks; a human is there)":"the headless variant takes the bypass as a default, because no one can answer the child's prompt":"no skip was asked for, so no permission flag is passed to the child"})})}function gateFor(e,o,r,s={}){const i=loadEvaluator(s.evaluator),n=e&&e.rules?e.rules:normalizeRules({}),a=i.evalPermission(o,r,n);return"deny"===a?"deny":"allow"===a||e&&e.skip?"allow":"ask"}function skipReport(e){if(!e||!e.skip)return null;const o=e.child.flag?`; the ${e.child.kind} Claude child is passed ${e.child.flag}`:"";return`aegis: ${"posture"===e.skipSource?"automode (the stored confirmation posture both faces share)":"--dangerously-skip-permissions"} (via ${e.skipSource}) — skipping the configurable confirmation gates (${CONFIGURABLE_CLASSES.join(", ")})${o}. NOT skipped, and not reachable by any setting, flag or env var: the ÆGIS covenant pre-action assert and the ${FROZEN_CLASSES.join("|")} approvals (always 'ask'), plus any explicit deny rule.`}module.exports={CHILD_KINDS:CHILD_KINDS,CONFIGURABLE_CLASSES:CONFIGURABLE_CLASSES,FROZEN_CLASSES:FROZEN_CLASSES,PERMISSION_MODES:PERMISSION_MODES,SKIP_FLAG:SKIP_FLAG,loadEvaluator:loadEvaluator,loadConfigStore:loadConfigStore,storedPermissionFacts:storedPermissionFacts,normalizeRules:normalizeRules,resolvePosture:resolvePosture,gateFor:gateFor,skipReport:skipReport};