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
|
@@ -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
|
-
const
|
|
3
|
+
"use strict";const SCOPE_CONVERSATION="conversation",SCOPE_MEMORY="memory",SCOPE_TEXT={conversation:"one conversation",memory:"the whole memory base"};function keyTag(e){const n="string"==typeof e?e.trim():"";return n?`φ_${n}`:null}function authorLine(e){return keyTag(e)||"no key — this copy is unsigned"}function safeFileName(e,n){return String(e||n||"aegis-export").normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"aegis-export"}function stamp({scope:e,keyFingerprint:n=null,email:t=null,exportedAt:o=null,subject:r=null,count:i=null}={}){const a=keyTag(n),s=[];return r&&s.push(`**What this is:** ${r}`),s.push(`**Scope:** ${SCOPE_TEXT[e]||String(e||"unknown")} (${e||"unknown"})`),s.push(`**Author:** ${authorLine(n)}`),s.push(`**Account:** ${t||"not reported by the server"}`),null!=i&&s.push(`**Entries:** ${i}`),s.push(`**Exported:** ${o||"timestamp not recorded"}`),s.push(a?`**Sealed by:** ${a} — this is a key tag, not the key. It proves the same machine wrote it.`:"**Sealed by:** nothing — no authorship key is set on this machine, so this copy cannot prove it came from you."),`${s.join("\n")}\n\n`}function conversationMarkdown(e,n={}){return`# ${e&&(e.title||e.id)||"Untitled conversation"}\n\n${stamp({scope:"conversation",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${n.transcript||""}`}function memoryMarkdown(e,n={}){return`${stamp({scope:"memory",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${e||""}`}function conversationFileName(e,n){const t=String(n||"").replace(/[:.]/g,"-").replace(/[^\w-]+/g,""),o=safeFileName(e&&(e.title||e.id),"conversation");return t?`${o}-${t}.md`:`${o}.md`}module.exports={SCOPE_CONVERSATION:"conversation",SCOPE_MEMORY:"memory",SCOPE_TEXT:SCOPE_TEXT,keyTag:keyTag,authorLine:authorLine,safeFileName:safeFileName,stamp:stamp,conversationMarkdown:conversationMarkdown,memoryMarkdown:memoryMarkdown,conversationFileName:conversationFileName};
|
|
@@ -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
|
-
const
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),KEY_ENV="AEGIS_API_KEY",MEMORY_ENV="AEGIS_MEMORY_TOKEN",HOME_ENV="AEGISCODE_HOME",CREDENTIALS_FILE="credentials.json",CONFIG_FILE="config.json",FILE_MODE=384,DIR_MODE=448;function aegisHome(e){const r=e||process.env,n=r&&r[HOME_ENV];return n&&String(n).trim()?path.resolve(String(n).trim()):path.join(os.homedir(),".aegiscode")}function credentialsPath(e){return path.join(e||aegisHome(),CREDENTIALS_FILE)}function configPath(e){return path.join(e||aegisHome(),CONFIG_FILE)}function normalizeApiKey(e){let r=String(null==e?"":e).trim();if(!r)return"";r=r.replace(/^export\s+/i,"").trim();const n=/^[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/s.exec(r);return n&&(r=n[1].trim()),r=r.replace(/^["']|["']$/g,"").trim(),r=r.replace(/^Bearer\s+/i,"").trim(),r}function validateApiKey(e,r={}){const n=String(r.label||"AEGIS"),t=normalizeApiKey(e);return t?/\s/.test(t)?{ok:!1,key:t,reason:"whitespace",message:"that looks like more than one word — paste just the key"}:t.length<16?{ok:!1,key:t,reason:"too short",message:`that key is ${t.length} characters — ${n} keys are longer than that`}:{ok:!0,key:t,reason:null,message:null}:{ok:!1,key:t,reason:"empty",message:"no key given"}}function readCredentials(e){try{const r=JSON.parse(fs.readFileSync(credentialsPath(e),"utf8"));if(r&&"object"==typeof r)return r}catch{}return{}}function writeCredentials(e,r){const n=credentialsPath(r),t={...readCredentials(r),...e,version:1};try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:DIR_MODE});const e=n+".tmp";fs.writeFileSync(e,JSON.stringify(t,null,2)+"\n",{mode:FILE_MODE}),fs.renameSync(e,n);try{fs.chmodSync(n,FILE_MODE)}catch{}}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[credentials] write failed:",e),{ok:!1,error:e,credentials:t}}return{ok:!0,credentials:t}}function readLegacyConfig(e){try{const r=JSON.parse(fs.readFileSync(configPath(e),"utf8"));if(!r||"object"!=typeof r)return{};const n=r.aegiscloud&&"object"==typeof r.aegiscloud?r.aegiscloud:{},t=r.memory&&"object"==typeof r.memory?r.memory:{};return{apiKey:normalizeApiKey(n.api_key),memoryToken:String(t.token||"").trim(),syncConversations:!0===n.syncConversations||void 0,lastVerified:n.lastVerified||null,memorySubscribed:!0===t.subscribed||void 0}}catch{return{}}}function legacyKeyOnDisk(e){return!!readLegacyConfig(e).apiKey}function adoptLegacy(e){const r=readLegacyConfig(e),n=readCredentials(e),t={};return r.apiKey&&!n.aegisApiKey&&(t.aegisApiKey=r.apiKey),r.memoryToken&&!n.memoryToken&&(t.memoryToken=r.memoryToken),Object.keys(t).length&&writeCredentials({...t,adoptedFrom:configPath(e)},e).ok?{adopted:Object.keys(t)}:{adopted:[]}}function fromEnvFile(e,r,n){try{const t=require("./env-file.js");return"function"==typeof t.isFromEnvFile&&t.isFromEnvFile(e,r,n?{env:n}:void 0)}catch{return!1}}function resolveApiKey(e={}){const r=e.env||process.env,n=e.dir,t=normalizeApiKey(r&&r[KEY_ENV]);if(t&&!fromEnvFile(KEY_ENV,r&&r[KEY_ENV],r))return{key:t,source:"env",from:KEY_ENV};const o=normalizeApiKey(readCredentials(n).aegisApiKey);if(o)return{key:o,source:"credentials",from:credentialsPath(n)};if(t)return{key:t,source:"envfile",from:envFileLabel(r,n)};const i=readLegacyConfig(n).apiKey;return i?{key:i,source:"config",from:configPath(n)}:{key:"",source:"none",from:""}}function hasApiKey(e={}){return!!resolveApiKey(e).key}function saveApiKey(e,r){const n=validateApiKey(e);if(!n.ok)return{ok:!1,key:n.key,path:credentialsPath(r),message:n.message};const t=writeCredentials({aegisApiKey:n.key,savedAt:(new Date).toISOString()},r);return t.ok?{ok:!0,key:n.key,path:credentialsPath(r)}:{ok:!1,key:n.key,path:credentialsPath(r),error:t.error,message:`could not write ${credentialsPath(r)}`}}function clearApiKey(e){return{cleared:!!normalizeApiKey(readCredentials(e).aegisApiKey),ok:writeCredentials({aegisApiKey:"",adoptedFrom:""},e).ok,path:credentialsPath(e)}}function resolveMemoryToken(e={}){const r=e.env||process.env,n=e.dir,t=String(r&&r[MEMORY_ENV]||"").trim();if(t)return{token:t,source:"env"};const o=readCredentials(n),i=String(o.memoryToken||"").trim();if(i)return{token:i,source:"credentials"};const a=readLegacyConfig(n).memoryToken;return a?{token:a,source:"config"}:{token:"",source:"none"}}function saveMemoryToken(e,r={},n){return writeCredentials({memoryToken:String(e||"").trim(),...r},n)}function clearMemoryToken(e){return writeCredentials({memoryToken:"",memorySubscribed:!1},e)}function keyStatus(e={}){const r=e.dir,{key:n,source:t,from:o}=resolveApiKey(e),i=readCredentials(r);let a=null;try{a=511&fs.statSync(credentialsPath(r)).mode}catch{}return{configured:!!n,key:n,source:t,from:o,path:credentialsPath(r),fileMode:null==a?null:"0"+a.toString(8),stored:!!normalizeApiKey(i.aegisApiKey),legacyPlaintext:legacyKeyOnDisk(r),verifiedAt:i.verifiedAt||null,account:i.account||null,memoryToken:!!resolveMemoryToken(e).token,memorySource:resolveMemoryToken(e).source}}function clientOptions(e={}){const{key:r}=resolveApiKey(e),{token:n}=resolveMemoryToken(e),t={};return t.apiKey=r,t.memoryToken=n,e.channel&&(t.channel=e.channel),t}const SOURCE_LABEL={env:`${KEY_ENV}`,credentials:"saved key file",envfile:`~/.aegiscode/.env (${KEY_ENV})`,config:"config.json (aegis CLI)",none:"not set"};function envFileLabel(e,r){try{const e=require("./env-file.js");if("function"==typeof e.envFileFor)return e.envFileFor(r)}catch{}return envFileForFallback(r)}function envFileForFallback(e){return path.join(e||aegisHome(),".env")}function sourceLabel(e){return SOURCE_LABEL[e]||SOURCE_LABEL.none}function preferNewest(e,r,n={}){const t=normalizeApiKey(e),o=Date.parse(r||"")||0,i=readCredentials(n.dir),a=normalizeApiKey(i.aegisApiKey),s=Date.parse(i.savedAt||"")||0;return a?t?t===a?{key:t,source:"host",sharedAt:s,hostAt:o}:s>o?{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:"host",sharedAt:s,hostAt:o}:{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:t?"host":"none",sharedAt:s,hostAt:o}}const HOW_TO_SET="run `aegiscode login` (or /key inside a session) to save one";module.exports={KEY_ENV:KEY_ENV,MEMORY_ENV:MEMORY_ENV,HOME_ENV:HOME_ENV,CREDENTIALS_FILE:CREDENTIALS_FILE,CONFIG_FILE:CONFIG_FILE,aegisHome:aegisHome,credentialsPath:credentialsPath,configPath:configPath,normalizeApiKey:normalizeApiKey,validateApiKey:validateApiKey,readCredentials:readCredentials,writeCredentials:writeCredentials,readLegacyConfig:readLegacyConfig,legacyKeyOnDisk:legacyKeyOnDisk,adoptLegacy:adoptLegacy,resolveApiKey:resolveApiKey,hasApiKey:hasApiKey,fromEnvFile:fromEnvFile,envFileForFallback:envFileForFallback,saveApiKey:saveApiKey,clearApiKey:clearApiKey,resolveMemoryToken:resolveMemoryToken,saveMemoryToken:saveMemoryToken,clearMemoryToken:clearMemoryToken,keyStatus:keyStatus,clientOptions:clientOptions,preferNewest:preferNewest,sourceLabel:sourceLabel,HOW_TO_SET:HOW_TO_SET};
|
|
@@ -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
|
-
const
|
|
3
|
+
"use strict";const DRIVE_FILES_URL="https://www.googleapis.com/drive/v3/files",DRIVE_UPLOAD_URL="https://www.googleapis.com/upload/drive/v3/files",FOLDER_MIME="application/vnd.google-apps.folder",BOUNDARY="aegiscode-drive-upload-boundary",DEFAULT_FOLDER="AEGIS Memory",DEFAULT_FILE="aegis-memory-backup.json",DEFAULT_CONVERSATIONS_FOLDER="conversations";function resolveFetch(e){const n=e||("function"==typeof fetch?fetch:null);if(!n)throw new Error("drive: this Node has no global fetch — upgrade to Node 22+");return n}function escapeQ(e){return String(e).replace(/\\/g,"\\\\").replace(/'/g,"\\'")}async function driveRequest(e,n,{method:t="GET",accessToken:o,body:r,headers:a}={}){const i=resolveFetch(e),d=await i(n,{method:t,headers:{Authorization:`Bearer ${o}`,...a||{}},body:r}),l=await d.text();let s=null;try{s=l?JSON.parse(l):null}catch{s=null}if(!d.ok){const e=s&&s.error&&(s.error.message||s.error)||l.slice(0,200)||`HTTP ${d.status}`,o=new Error(`drive: ${t} ${n.split("?")[0]} failed — ${"string"==typeof e?e:JSON.stringify(e)}`);throw o.status=d.status,o.data=s,o}return s||{}}async function findOne(e,n,t){const o=`${DRIVE_FILES_URL}?q=${encodeURIComponent(t)}&fields=${encodeURIComponent("files(id,name)")}&pageSize=1`,r=await driveRequest(e,o,{accessToken:n});return(Array.isArray(r.files)?r.files:[])[0]||null}async function findOrCreateFolder(e,n,{fetchImpl:t,parentId:o=null}={}){const r=`${o?`'${escapeQ(o)}' in parents and `:""}mimeType='${FOLDER_MIME}' and name='${escapeQ(n)}' and trashed=false`,a=await findOne(t,e,r);if(a)return a.id;const i={name:n,mimeType:FOLDER_MIME};return o&&(i.parents=[o]),(await driveRequest(t,DRIVE_FILES_URL,{method:"POST",accessToken:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})).id}async function findFileInFolder(e,n,t,{fetchImpl:o}={}){return findOne(o,e,`'${escapeQ(t)}' in parents and name='${escapeQ(n)}' and trashed=false`)}async function createFile(e,{name:n,folderId:t,content:o,mimeType:r},{fetchImpl:a}={}){const i=JSON.stringify({name:n,parents:[t]}),d=`--${BOUNDARY}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${i}\r\n--${BOUNDARY}\r\nContent-Type: ${r}\r\n\r\n${o}\r\n--${BOUNDARY}--`;return driveRequest(a,`${DRIVE_UPLOAD_URL}?uploadType=multipart&fields=${encodeURIComponent("id,webViewLink")}`,{method:"POST",accessToken:e,headers:{"Content-Type":`multipart/related; boundary=${BOUNDARY}`},body:d})}async function updateFileContent(e,n,t,o,{fetchImpl:r}={}){return driveRequest(r,`${DRIVE_UPLOAD_URL}/${encodeURIComponent(n)}?uploadType=media&fields=${encodeURIComponent("id,webViewLink")}`,{method:"PATCH",accessToken:e,headers:{"Content-Type":o},body:t})}async function uploadMemoryBackup(e,n,t={}){const o=t.folderName||"AEGIS Memory",r=t.fileName||DEFAULT_FILE,a=t.mimeType||"application/json",i=t.fetchImpl,d=await findOrCreateFolder(e,o,{fetchImpl:i}),l=await findFileInFolder(e,r,d,{fetchImpl:i}),s=l?await updateFileContent(e,l.id,n,a,{fetchImpl:i}):await createFile(e,{name:r,folderId:d,content:n,mimeType:a},{fetchImpl:i});return{fileId:s.id||l&&l.id||null,webViewLink:s.webViewLink||null,updated:Boolean(l)}}async function uploadConversation(e,n={}){const t=n.name,o=n.content;if(!t)throw new Error("drive: uploadConversation needs a file name");if("string"!=typeof o)throw new Error("drive: uploadConversation needs the file content as a string");const r=n.folderName||"AEGIS Memory",a=void 0===n.subfolder?"conversations":n.subfolder,i=n.mimeType||"text/markdown",d=n.fetchImpl,l=await findOrCreateFolder(e,r,{fetchImpl:d}),s=a?await findOrCreateFolder(e,a,{fetchImpl:d,parentId:l}):l,c=await createFile(e,{name:t,folderId:s,content:o,mimeType:i},{fetchImpl:d});return{fileId:c.id||null,webViewLink:c.webViewLink||null,created:!0,folder:a?`${r}/${a}`:r,path:a?`${r}/${a}/${t}`:`${r}/${t}`}}module.exports={DEFAULT_FOLDER:"AEGIS Memory",DEFAULT_FILE:DEFAULT_FILE,DEFAULT_CONVERSATIONS_FOLDER:"conversations",findOrCreateFolder:findOrCreateFolder,findFileInFolder:findFileInFolder,createFile:createFile,updateFileContent:updateFileContent,uploadMemoryBackup:uploadMemoryBackup,uploadConversation:uploadConversation};
|
|
@@ -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
|
-
const e=require("node:fs"),t=require("node:path"),r=require("./credentials.js"),n=require("./platform.js"),o=".env",i="secrets.env",s=Object.freeze(["STRIPE_"]),c=Object.freeze(["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_PRODUCT","STRIPE_PRO_PRICE_ID","STRIPE_S_PRICE_ID","STRIPE_MEMORY_PRICE_ID","PYPI_API_TOKEN","TWINE_PASSWORD","CLAUDE_CODE_OAUTH_TOKEN"]);function a(e){const t=String(null==e?"":e).trim();return!!t&&(!!c.includes(t)||s.some((e=>t.startsWith(e))))}const l=384,d=Object.freeze({google:"GEMINI_API_KEY",gemini:"GEMINI_API_KEY","google-ai":"GEMINI_API_KEY",xai:"XAI_API_KEY","x-ai":"XAI_API_KEY",grok:"XAI_API_KEY",huggingface:"HF_TOKEN",together:"TOGETHER_API_KEY","together-ai":"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY","azure-openai":"AZURE_OPENAI_API_KEY","voyage-ai":"VOYAGE_API_KEY"}),u="AEGIS_API_KEY";function f(e){return t.join(e||r.aegisHome(),o)}function g(e){return t.join(e||r.aegisHome(),i)}function p(e){const t=String(e||"").trim().toLowerCase();if(!t)return"";const r=t.startsWith("byok:")?t.slice(5).trim():t;if(!r)return"";if(d[r])return d[r];const n=r.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return n?`${n}_API_KEY`:""}const m=/^[A-Za-z0-9_+/.-]+$/,h=32;function E(e,t,r){let n=r;if(n.startsWith('"')||n.startsWith("'"))return{value:n,i:t};for(;t+1<e.length;){const r=e[t+1],o=r.trim();if(!o||o.startsWith("#")||o.includes("="))break;if(!m.test(o))break;if(!/^[ \t]/.test(r)&&(n.length<h||!m.test(n)))break;n+=o,t+=1}return{value:n,i:t}}function S(e){const t={},r=String(null==e?"":e).split(/\r?\n/);for(let e=0;e<r.length;e++){const n=r[e].trim();if(!n||n.startsWith("#"))continue;const o=n.indexOf("=");if(o<=0)continue;let i=n.slice(0,o).trim();if(i.startsWith("export ")&&(i=i.slice(7).trim()),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))continue;const s=E(r,e,n.slice(o+1).trim());let c=s.value;e=s.i;const a=c.startsWith('"')&&c.endsWith('"')&&c.length>=2,l=c.startsWith("'")&&c.endsWith("'")&&c.length>=2;if(a)c=c.slice(1,-1).replace(/\\(["\\])/g,"$1");else if(l)c=c.slice(1,-1);else{const e=c.indexOf(" #");-1!==e&&(c=c.slice(0,e).trim())}t[i]=c}return t}const y=new WeakMap;function _(e){let t=y.get(e);return t||(t=new Map,y.set(e,t)),t}function v(t,r={}){if(!a(t))return"";const n=r.file||g(r.dir);try{const r=S(e.readFileSync(n,"utf8"))[String(t)];return"string"==typeof r?r:""}catch{return""}}function I(r,n){e.mkdirSync(t.dirname(r),{recursive:!0,mode:448});const o=`${r}.tmp-${process.pid}-${Date.now()}`;e.writeFileSync(o,n,{mode:l}),e.renameSync(o,r),e.chmodSync(r,l)}function $(e){return"string"==typeof e&&e.trim().length>=8}function k(e){return"string"==typeof e&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function A(e){const t=String(e);return""===t?"":/[\s"'#\\]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function F(e,t,r){const n=String(null==e?"":e),o=""===n||n.endsWith("\n"),i=""!==n&&""===n.split("\n").slice(-1)[0],s=""===n?[]:n.split("\n");i&&s.pop();const c=new RegExp(`^(\\s*(?:export\\s+)?)${t}\\s*=`),a=[];let l=!1;for(const e of s){const n=c.exec(e);n?l||(a.push(`${n[1]}${t}=${A(r)}`),l=!0):a.push(e)}l||a.push(`${t}=${A(r)}`);let d=a.join("\n");return""!==d&&(o||i)&&(d+="\n"),{text:d,replaced:l}}function O(e,t){const r=String(null==e?"":e),n=""===r||r.endsWith("\n"),o=""!==r&&""===r.split("\n").slice(-1)[0],i=""===r?[]:r.split("\n");o&&i.pop();const s=new RegExp(`^(\\s*(?:export\\s+)?)${t}\\s*=`),c=[];let a=0;for(const e of i)s.test(e)?a+=1:c.push(e);let l=c.join("\n");return""!==l&&(n||o)&&(l+="\n"),{text:l,removed:a,changed:a>0}}const P=Object.freeze(["openai","anthropic","deepseek","google","gemini","groq","mistral","openrouter","together","together-ai","xai","x-ai","grok","huggingface","fireworks","voyage-ai","azure-openai"]),T=Object.freeze(P.filter((e=>e.includes("-"))).sort(((e,t)=>t.length-e.length)));function R(e,t){const r=String(null==e?"":e).trim().toLowerCase();if(!r)return"";if(r.includes(":"))return r.slice(0,r.indexOf(":")).trim();for(const e of T)if(r===e||r.startsWith(e+"-"))return e;const n=r.split("-")[0];return P.includes(n)?n:""}module.exports={ENV_FILE:o,ALIASES:d,ACCOUNT_ENV_VAR:u,SECRET_FILE_MODE:l,envFileFor:f,envVarFor:p,parseEnvText:S,loadEnvFile:function(t={}){const r=t.env||process.env,o=t.file||f(t.dir),i=_(r),s={ok:!1,file:o,loaded:[],kept:[],refused:[],reason:"",loose:!1,mode:0};let c;try{c=e.readFileSync(o,"utf8")}catch(e){return s.reason=e&&"ENOENT"===e.code?"absent":"unreadable",s}try{const t=e.statSync(o);s.mode=511&t.mode,s.loose=n.hasPosixModes()&&0!=(63&t.mode)}catch{}const l=S(c);for(const[e,t]of Object.entries(l))a(e)?s.refused.push(e):void 0===r[e]||""===r[e]?(r[e]=t,i.set(e,t),s.loaded.push(e)):s.kept.push(e);return s.ok=!0,s},isFromEnvFile:function(e,t,r={}){const n=r.env||process.env,o=y.get(n);return!(!o||!o.has(e)||void 0!==t&&o.get(e)!==String(t))},providerKeyFromEnv:function(e,t){const r=p(e);if(!r)return{key:"",env:"",rejected:null};const n=(t||process.env)[r],o="string"==typeof n?n.trim():"";return""===o?{key:"",env:r,rejected:null}:$(o)?{key:o,env:r,rejected:null}:{key:"",env:r,rejected:`${r} holds ${o.length} character${1===o.length?"":"s"}, which cannot be a credential`}},MIN_CREDENTIAL_LEN:8,credentialLooksUsable:$,providerForModelId:R,VENDOR_SLUGS:P,isWritableName:k,quoteEnvValue:A,upsertEnvText:F,removeEnvText:O,setEnvValue:function(r,s,c={}){const d=c.env||process.env,u=c.file||f(c.dir),g={ok:!1,file:u,name:String(r||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!k(r))return g.error=`refusing to write "${r}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,g;if(a(r))return g.error=`refusing to write ${r} to ${o} — it is a production secret, not a host key; put it in ${i} (or use loadForeignSecrets)`,g;const p=String(null==s?"":s).trim();if(!p)return g.error=`refusing to write an empty ${r}`,g;if(/[\r\n]/.test(String(s)))return g.error=`refusing to write ${r} — the value contains a line break`,g;let m="",h=0;g.created=!0;try{m=e.readFileSync(u,"utf8"),g.created=!1;try{h=511&e.statSync(u).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return g.error=`could not read ${u}: ${e.code||e.message}`,g}const E=String(m).replace(/\r\n/g,"\n");if(!g.created&&S(E)[r]===p)return g.ok=!0,g.changed=!1,g.replaced=!0,g.mode=h||l,!1!==c.apply&&(d[r]=p,_(d).set(r,p)),g;const{text:y,replaced:v}=F(E,r,p),I=`${u}.tmp-${process.pid}`;try{e.mkdirSync(t.dirname(u),{recursive:!0,mode:448}),e.writeFileSync(I,y,{encoding:"utf8",mode:l}),e.chmodSync(I,l),e.renameSync(I,u)}catch(t){try{e.unlinkSync(I)}catch{}return g.error=`could not write ${u}: ${t.code||t.message}`,g}return g.ok=!0,g.changed=!0,g.replaced=v,g.mode=l,g.tightened=n.hasPosixModes()&&!g.created&&0!==h&&0!=(63&h),!1!==c.apply&&(d[r]=p,_(d).set(r,p)),g},clearEnvValue:function(r,n={}){const o=n.env||process.env,i=n.file||f(n.dir),s={ok:!1,file:i,name:String(r||""),changed:!1,removed:0,mode:0,error:""};if(!k(r))return s.error=`refusing to clear "${r}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,s;let c="",a=!1,d=0;try{c=e.readFileSync(i,"utf8");try{d=511&e.statSync(i).mode}catch{}}catch(e){if(!e||"ENOENT"!==e.code)return s.error=`could not read ${i}: ${e.code||e.message}`,s;a=!0}const{text:u,removed:g,changed:p}=a?{text:"",removed:0,changed:!1}:O(c,r);if(!p)return s.ok=!0,s.mode=d||l,!1!==n.apply&&delete o[String(r)],s;const m=`${i}.tmp-${process.pid}`;try{e.mkdirSync(t.dirname(i),{recursive:!0,mode:448}),e.writeFileSync(m,u,{encoding:"utf8",mode:l}),e.chmodSync(m,l),e.renameSync(m,i)}catch(t){try{e.unlinkSync(m)}catch{}return s.error=`could not write ${i}: ${t.code||t.message}`,s}return s.ok=!0,s.changed=!0,s.removed=g,s.mode=l,!1!==n.apply&&delete o[String(r)],s},keyStatus:function(t,r={}){const n=r.env||process.env,o=r.file||f(r.dir),i=String(t||""),s={name:i,present:!1,inFile:!1,source:"none"};if(!k(i))return s;const c=n[i],a="string"==typeof c&&""!==c.trim();let l=!1;try{const t=S(e.readFileSync(o,"utf8"));l="string"==typeof t[i]&&""!==t[i].trim()}catch{}return s.present=a||l,s.inFile=l,s.source=a&&l?"both":a?"shell":l?"file":"none",s},keyForModelId:function(e,t){const r=String(null==e?"":e).trim();if("pro"===String(t||"").toLowerCase())return{env:"CLAUDE_CODE_OAUTH_TOKEN",provider:"",vendor:"",pooled:!1,foreign:!0};if(("byok"===String(t||"").toLowerCase()||r.includes(":"))&&r.includes(":")){const e=r.slice(0,r.indexOf(":")).trim();return{env:p(e),provider:e,vendor:e,pooled:!1}}return{env:u,provider:"",vendor:R(r),pooled:!0}},SECRETS_FILE:i,FOREIGN_SECRET_NAMES:c,FOREIGN_SECRET_PREFIXES:s,isForeignSecret:a,secretEnvFileFor:g,loadForeignSecrets:function(t={}){const r=t.env||process.env,o=t.file||g(t.dir),i={ok:!1,file:o,loaded:[],reason:"",mode:0,loose:!1},s=Array.isArray(t.only)&&t.only.length?t.only.filter(a):null;let c;try{c=e.readFileSync(o,"utf8")}catch(e){return i.reason=e&&"ENOENT"===e.code?"absent":"unreadable",i}try{const t=e.statSync(o);i.mode=511&t.mode,i.loose=n.hasPosixModes()&&0!=(63&t.mode)}catch{}const l=S(c);for(const[e,t]of Object.entries(l))s&&!s.includes(e)||(r[e]=t,i.loaded.push(e));return i.ok=!0,i},foreignSecretValue:v,resolveForeignSecret:function(t,r={}){if(!a(t))return"";const n=r.env||process.env,o=n&&n[t];if("string"==typeof o&&o.trim())return o.trim();const i=v(t,r);if(i&&i.trim())return i.trim();try{const n=S(e.readFileSync(f(r.dir),"utf8"))[String(t)];return"string"==typeof n?n.trim():""}catch{return""}},setForeignSecret:function(t,r,s={}){const c=s.file||g(s.dir),d={ok:!1,file:c,name:String(t||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!k(t))return d.error=`refusing to write "${t}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,d;if(!a(t))return d.error=`refusing to write ${t} to ${i} — it is a host credential, not a foreign secret; use setEnvValue (${o}) instead`,d;const u=String(null==r?"":r).trim();if(!u)return d.error=`refusing to write an empty ${t}`,d;if(/[\r\n]/.test(String(r)))return d.error=`refusing to write ${t} — the value contains a line break`,d;let f="",p=0;d.created=!0;try{f=e.readFileSync(c,"utf8"),d.created=!1;try{p=511&e.statSync(c).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return d.error=`could not read ${c}: ${e.code||e.message}`,d}const m=String(f).replace(/\r\n/g,"\n");if(!d.created&&S(m)[t]===u)return d.ok=!0,d.changed=!1,d.replaced=!0,d.mode=p||l,d;const{text:h,replaced:E}=F(m,t,u);try{I(c,h)}catch(e){return d.error=`could not write ${c}: ${e.code||e.message}`,d}return d.ok=!0,d.changed=!0,d.replaced=E,d.mode=l,d.tightened=n.hasPosixModes()&&!d.created&&0!==p&&0!=(63&p),d},splitForeignSecrets:function(t={}){const r=t.env||process.env,n=t.file||f(t.dir),o=t.secretsFile||g(t.dir),i=!0===t.apply,s={ok:!1,moved:[],kept:[],envFile:n,secretsFile:o,apply:i};let c;try{c=e.readFileSync(n,"utf8")}catch(e){return s.reason=e&&"ENOENT"===e.code?"absent":"unreadable",s}const l=S(c),d=Object.keys(l).filter(a).sort();if(!d.length)return s.ok=!0,s;let u="";try{u=e.readFileSync(o,"utf8")}catch{}const p=S(u);for(const e of d)Object.prototype.hasOwnProperty.call(p,e)?s.kept.push(e):(u=F(u,e,l[e]).text,s.moved.push(e));if(i){for(const e of d)c=O(c,e).text;s.moved.length&&I(o,u),I(n,c);for(const e of d)r[e]===l[e]&&delete r[e]}else s.moved.length&&(s.secretsFile=o);return s.ok=!0,s}};
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),credentials=require("./credentials.js"),platform=require("./platform.js"),ENV_FILE=".env",SECRETS_FILE="secrets.env",FOREIGN_SECRET_PREFIXES=Object.freeze(["STRIPE_"]),FOREIGN_SECRET_NAMES=Object.freeze(["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_PRODUCT","STRIPE_PRO_PRICE_ID","STRIPE_S_PRICE_ID","STRIPE_MEMORY_PRICE_ID","PYPI_API_TOKEN","TWINE_PASSWORD","CLAUDE_CODE_OAUTH_TOKEN"]);function isForeignSecret(e){const r=String(null==e?"":e).trim();return!!r&&(!!FOREIGN_SECRET_NAMES.includes(r)||FOREIGN_SECRET_PREFIXES.some((e=>r.startsWith(e))))}const SECRET_FILE_MODE=384,SECRET_DIR_MODE=448,ALIASES=Object.freeze({google:"GEMINI_API_KEY",gemini:"GEMINI_API_KEY","google-ai":"GEMINI_API_KEY",xai:"XAI_API_KEY","x-ai":"XAI_API_KEY",grok:"XAI_API_KEY",huggingface:"HF_TOKEN",together:"TOGETHER_API_KEY","together-ai":"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY","azure-openai":"AZURE_OPENAI_API_KEY","voyage-ai":"VOYAGE_API_KEY"}),ACCOUNT_ENV_VAR="AEGIS_API_KEY";function envFileFor(e){return path.join(e||credentials.aegisHome(),ENV_FILE)}function secretEnvFileFor(e){return path.join(e||credentials.aegisHome(),SECRETS_FILE)}function envVarFor(e){const r=String(e||"").trim().toLowerCase();if(!r)return"";const t=r.startsWith("byok:")?r.slice(5).trim():r;if(!t)return"";if(ALIASES[t])return ALIASES[t];const n=t.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return n?`${n}_API_KEY`:""}const ENV_TOKENISH=/^[A-Za-z0-9_+/.-]+$/,ENV_WRAP_MIN_VALUE=32;function foldWrappedEnvValue(e,r,t){let n=t;if(n.startsWith('"')||n.startsWith("'"))return{value:n,i:r};for(;r+1<e.length;){const t=e[r+1],o=t.trim();if(!o||o.startsWith("#")||o.includes("="))break;if(!ENV_TOKENISH.test(o))break;if(!/^[ \t]/.test(t)&&(n.length<ENV_WRAP_MIN_VALUE||!ENV_TOKENISH.test(n)))break;n+=o,r+=1}return{value:n,i:r}}function parseEnvText(e){const r={},t=String(null==e?"":e).split(/\r?\n/);for(let e=0;e<t.length;e++){const n=t[e].trim();if(!n||n.startsWith("#"))continue;const o=n.indexOf("=");if(o<=0)continue;let i=n.slice(0,o).trim();if(i.startsWith("export ")&&(i=i.slice(7).trim()),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))continue;const s=foldWrappedEnvValue(t,e,n.slice(o+1).trim());let c=s.value;e=s.i;const E=c.startsWith('"')&&c.endsWith('"')&&c.length>=2,a=c.startsWith("'")&&c.endsWith("'")&&c.length>=2;if(E)c=c.slice(1,-1).replace(/\\(["\\])/g,"$1");else if(a)c=c.slice(1,-1);else{const e=c.indexOf(" #");-1!==e&&(c=c.slice(0,e).trim())}r[i]=c}return r}const ENV_SOURCED=new WeakMap;function sourcedFrom(e){let r=ENV_SOURCED.get(e);return r||(r=new Map,ENV_SOURCED.set(e,r)),r}function isFromEnvFile(e,r,t={}){const n=t.env||process.env,o=ENV_SOURCED.get(n);return!(!o||!o.has(e)||void 0!==r&&o.get(e)!==String(r))}function loadEnvFile(e={}){const r=e.env||process.env,t=e.file||envFileFor(e.dir),n=sourcedFrom(r),o={ok:!1,file:t,loaded:[],kept:[],refused:[],reason:"",loose:!1,mode:0};let i;try{i=fs.readFileSync(t,"utf8")}catch(e){return o.reason=e&&"ENOENT"===e.code?"absent":"unreadable",o}try{const e=fs.statSync(t);o.mode=511&e.mode,o.loose=platform.hasPosixModes()&&0!=(63&e.mode)}catch{}const s=parseEnvText(i);for(const[e,t]of Object.entries(s))isForeignSecret(e)?o.refused.push(e):void 0===r[e]||""===r[e]?(r[e]=t,n.set(e,t),o.loaded.push(e)):o.kept.push(e);return o.ok=!0,o}function loadForeignSecrets(e={}){const r=e.env||process.env,t=e.file||secretEnvFileFor(e.dir),n={ok:!1,file:t,loaded:[],reason:"",mode:0,loose:!1},o=Array.isArray(e.only)&&e.only.length?e.only.filter(isForeignSecret):null;let i;try{i=fs.readFileSync(t,"utf8")}catch(e){return n.reason=e&&"ENOENT"===e.code?"absent":"unreadable",n}try{const e=fs.statSync(t);n.mode=511&e.mode,n.loose=platform.hasPosixModes()&&0!=(63&e.mode)}catch{}const s=parseEnvText(i);for(const[e,t]of Object.entries(s))o&&!o.includes(e)||(r[e]=t,n.loaded.push(e));return n.ok=!0,n}function foreignSecretValue(e,r={}){if(!isForeignSecret(e))return"";const t=r.file||secretEnvFileFor(r.dir);try{const r=parseEnvText(fs.readFileSync(t,"utf8"))[String(e)];return"string"==typeof r?r:""}catch{return""}}function resolveForeignSecret(e,r={}){if(!isForeignSecret(e))return"";const t=r.env||process.env,n=t&&t[e];if("string"==typeof n&&n.trim())return n.trim();const o=foreignSecretValue(e,r);if(o&&o.trim())return o.trim();try{const t=parseEnvText(fs.readFileSync(envFileFor(r.dir),"utf8"))[String(e)];return"string"==typeof t?t.trim():""}catch{return""}}function writeSecretFile(e,r){fs.mkdirSync(path.dirname(e),{recursive:!0,mode:SECRET_DIR_MODE});const t=`${e}.tmp-${process.pid}-${Date.now()}`;fs.writeFileSync(t,r,{mode:SECRET_FILE_MODE}),fs.renameSync(t,e),fs.chmodSync(e,SECRET_FILE_MODE)}function setForeignSecret(e,r,t={}){const n=t.file||secretEnvFileFor(t.dir),o={ok:!1,file:n,name:String(e||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!isWritableName(e))return o.error=`refusing to write "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,o;if(!isForeignSecret(e))return o.error=`refusing to write ${e} to ${SECRETS_FILE} — it is a host credential, not a foreign secret; use setEnvValue (${ENV_FILE}) instead`,o;const i=String(null==r?"":r).trim();if(!i)return o.error=`refusing to write an empty ${e}`,o;if(/[\r\n]/.test(String(r)))return o.error=`refusing to write ${e} — the value contains a line break`,o;let s="",c=0;o.created=!0;try{s=fs.readFileSync(n,"utf8"),o.created=!1;try{c=511&fs.statSync(n).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return o.error=`could not read ${n}: ${e.code||e.message}`,o}const E=String(s).replace(/\r\n/g,"\n");if(!o.created&&parseEnvText(E)[e]===i)return o.ok=!0,o.changed=!1,o.replaced=!0,o.mode=c||SECRET_FILE_MODE,o;const{text:a,replaced:l}=upsertEnvText(E,e,i);try{writeSecretFile(n,a)}catch(e){return o.error=`could not write ${n}: ${e.code||e.message}`,o}return o.ok=!0,o.changed=!0,o.replaced=l,o.mode=SECRET_FILE_MODE,o.tightened=platform.hasPosixModes()&&!o.created&&0!==c&&0!=(63&c),o}function splitForeignSecrets(e={}){const r=e.env||process.env,t=e.file||envFileFor(e.dir),n=e.secretsFile||secretEnvFileFor(e.dir),o=!0===e.apply,i={ok:!1,moved:[],kept:[],envFile:t,secretsFile:n,apply:o};let s;try{s=fs.readFileSync(t,"utf8")}catch(e){return i.reason=e&&"ENOENT"===e.code?"absent":"unreadable",i}const c=parseEnvText(s),E=Object.keys(c).filter(isForeignSecret).sort();if(!E.length)return i.ok=!0,i;let a="";try{a=fs.readFileSync(n,"utf8")}catch{}const l=parseEnvText(a);for(const e of E)Object.prototype.hasOwnProperty.call(l,e)?i.kept.push(e):(a=upsertEnvText(a,e,c[e]).text,i.moved.push(e));if(o){for(const e of E)s=removeEnvText(s,e).text;i.moved.length&&writeSecretFile(n,a),writeSecretFile(t,s);for(const e of E)r[e]===c[e]&&delete r[e]}else i.moved.length&&(i.secretsFile=n);return i.ok=!0,i}const MIN_CREDENTIAL_LEN=8;function credentialLooksUsable(e){return"string"==typeof e&&e.trim().length>=MIN_CREDENTIAL_LEN}function providerKeyFromEnv(e,r){const t=envVarFor(e);if(!t)return{key:"",env:"",rejected:null};const n=(r||process.env)[t],o="string"==typeof n?n.trim():"";return""===o?{key:"",env:t,rejected:null}:credentialLooksUsable(o)?{key:o,env:t,rejected:null}:{key:"",env:t,rejected:`${t} holds ${o.length} character${1===o.length?"":"s"}, which cannot be a credential`}}function isWritableName(e){return"string"==typeof e&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function quoteEnvValue(e){const r=String(e);return""===r?"":/[\s"'#\\]/.test(r)?`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:r}function upsertEnvText(e,r,t){const n=String(null==e?"":e),o=""===n||n.endsWith("\n"),i=""!==n&&""===n.split("\n").slice(-1)[0],s=""===n?[]:n.split("\n");i&&s.pop();const c=new RegExp(`^(\\s*(?:export\\s+)?)${r}\\s*=`),E=[];let a=!1;for(const e of s){const n=c.exec(e);n?a||(E.push(`${n[1]}${r}=${quoteEnvValue(t)}`),a=!0):E.push(e)}a||E.push(`${r}=${quoteEnvValue(t)}`);let l=E.join("\n");return""!==l&&(o||i)&&(l+="\n"),{text:l,replaced:a}}function setEnvValue(e,r,t={}){const n=t.env||process.env,o=t.file||envFileFor(t.dir),i={ok:!1,file:o,name:String(e||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!isWritableName(e))return i.error=`refusing to write "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,i;if(isForeignSecret(e))return i.error=`refusing to write ${e} to ${ENV_FILE} — it is a production secret, not a host key; put it in ${SECRETS_FILE} (or use loadForeignSecrets)`,i;const s=String(null==r?"":r).trim();if(!s)return i.error=`refusing to write an empty ${e}`,i;if(/[\r\n]/.test(String(r)))return i.error=`refusing to write ${e} — the value contains a line break`,i;let c="",E=0;i.created=!0;try{c=fs.readFileSync(o,"utf8"),i.created=!1;try{E=511&fs.statSync(o).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return i.error=`could not read ${o}: ${e.code||e.message}`,i}const a=String(c).replace(/\r\n/g,"\n");if(!i.created&&parseEnvText(a)[e]===s)return i.ok=!0,i.changed=!1,i.replaced=!0,i.mode=E||SECRET_FILE_MODE,!1!==t.apply&&(n[e]=s,sourcedFrom(n).set(e,s)),i;const{text:l,replaced:d}=upsertEnvText(a,e,s),u=`${o}.tmp-${process.pid}`;try{fs.mkdirSync(path.dirname(o),{recursive:!0,mode:SECRET_DIR_MODE}),fs.writeFileSync(u,l,{encoding:"utf8",mode:SECRET_FILE_MODE}),fs.chmodSync(u,SECRET_FILE_MODE),fs.renameSync(u,o)}catch(e){try{fs.unlinkSync(u)}catch{}return i.error=`could not write ${o}: ${e.code||e.message}`,i}return i.ok=!0,i.changed=!0,i.replaced=d,i.mode=SECRET_FILE_MODE,i.tightened=platform.hasPosixModes()&&!i.created&&0!==E&&0!=(63&E),!1!==t.apply&&(n[e]=s,sourcedFrom(n).set(e,s)),i}function removeEnvText(e,r){const t=String(null==e?"":e),n=""===t||t.endsWith("\n"),o=""!==t&&""===t.split("\n").slice(-1)[0],i=""===t?[]:t.split("\n");o&&i.pop();const s=new RegExp(`^(\\s*(?:export\\s+)?)${r}\\s*=`),c=[];let E=0;for(const e of i)s.test(e)?E+=1:c.push(e);let a=c.join("\n");return""!==a&&(n||o)&&(a+="\n"),{text:a,removed:E,changed:E>0}}function clearEnvValue(e,r={}){const t=r.env||process.env,n=r.file||envFileFor(r.dir),o={ok:!1,file:n,name:String(e||""),changed:!1,removed:0,mode:0,error:""};if(!isWritableName(e))return o.error=`refusing to clear "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,o;let i="",s=!1,c=0;try{i=fs.readFileSync(n,"utf8");try{c=511&fs.statSync(n).mode}catch{}}catch(e){if(!e||"ENOENT"!==e.code)return o.error=`could not read ${n}: ${e.code||e.message}`,o;s=!0}const{text:E,removed:a,changed:l}=s?{text:"",removed:0,changed:!1}:removeEnvText(i,e);if(!l)return o.ok=!0,o.mode=c||SECRET_FILE_MODE,!1!==r.apply&&delete t[String(e)],o;const d=`${n}.tmp-${process.pid}`;try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:SECRET_DIR_MODE}),fs.writeFileSync(d,E,{encoding:"utf8",mode:SECRET_FILE_MODE}),fs.chmodSync(d,SECRET_FILE_MODE),fs.renameSync(d,n)}catch(e){try{fs.unlinkSync(d)}catch{}return o.error=`could not write ${n}: ${e.code||e.message}`,o}return o.ok=!0,o.changed=!0,o.removed=a,o.mode=SECRET_FILE_MODE,!1!==r.apply&&delete t[String(e)],o}function keyStatus(e,r={}){const t=r.env||process.env,n=r.file||envFileFor(r.dir),o=String(e||""),i={name:o,present:!1,inFile:!1,source:"none"};if(!isWritableName(o))return i;const s=t[o],c="string"==typeof s&&""!==s.trim();let E=!1;try{const e=parseEnvText(fs.readFileSync(n,"utf8"));E="string"==typeof e[o]&&""!==e[o].trim()}catch{}return i.present=c||E,i.inFile=E,i.source=c&&E?"both":c?"shell":E?"file":"none",i}function keyForModelId(e,r){const t=String(null==e?"":e).trim();if("pro"===String(r||"").toLowerCase())return{env:"CLAUDE_CODE_OAUTH_TOKEN",provider:"",vendor:"",pooled:!1,foreign:!0};if(("byok"===String(r||"").toLowerCase()||t.includes(":"))&&t.includes(":")){const e=t.slice(0,t.indexOf(":")).trim();return{env:envVarFor(e),provider:e,vendor:e,pooled:!1}}return{env:"AEGIS_API_KEY",provider:"",vendor:providerForModelId(t,r),pooled:!0}}const VENDOR_SLUGS=Object.freeze(["openai","anthropic","deepseek","google","gemini","groq","mistral","openrouter","together","together-ai","xai","x-ai","grok","huggingface","fireworks","voyage-ai","azure-openai"]),VENDOR_COMPOUNDS=Object.freeze(VENDOR_SLUGS.filter((e=>e.includes("-"))).sort(((e,r)=>r.length-e.length)));function providerForModelId(e,r){const t=String(null==e?"":e).trim().toLowerCase();if(!t)return"";if(t.includes(":"))return t.slice(0,t.indexOf(":")).trim();for(const e of VENDOR_COMPOUNDS)if(t===e||t.startsWith(e+"-"))return e;const n=t.split("-")[0];return VENDOR_SLUGS.includes(n)?n:""}module.exports={ENV_FILE:ENV_FILE,ALIASES:ALIASES,ACCOUNT_ENV_VAR:"AEGIS_API_KEY",SECRET_FILE_MODE:SECRET_FILE_MODE,envFileFor:envFileFor,envVarFor:envVarFor,parseEnvText:parseEnvText,loadEnvFile:loadEnvFile,isFromEnvFile:isFromEnvFile,providerKeyFromEnv:providerKeyFromEnv,MIN_CREDENTIAL_LEN:MIN_CREDENTIAL_LEN,credentialLooksUsable:credentialLooksUsable,providerForModelId:providerForModelId,VENDOR_SLUGS:VENDOR_SLUGS,isWritableName:isWritableName,quoteEnvValue:quoteEnvValue,upsertEnvText:upsertEnvText,removeEnvText:removeEnvText,setEnvValue:setEnvValue,clearEnvValue:clearEnvValue,keyStatus:keyStatus,keyForModelId:keyForModelId,SECRETS_FILE:SECRETS_FILE,FOREIGN_SECRET_NAMES:FOREIGN_SECRET_NAMES,FOREIGN_SECRET_PREFIXES:FOREIGN_SECRET_PREFIXES,isForeignSecret:isForeignSecret,secretEnvFileFor:secretEnvFileFor,loadForeignSecrets:loadForeignSecrets,foreignSecretValue:foreignSecretValue,resolveForeignSecret:resolveForeignSecret,setForeignSecret:setForeignSecret,splitForeignSecrets:splitForeignSecrets};
|
package/vendor/client/hooks.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 fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),SETTINGS_DIRS=[".aegis",".aegiscode"];function hookSettingPaths(o={}){const e=platformPath(o.platform),t=homeDir(o),n=o.cwd||process.cwd(),s=[];for(const o of SETTINGS_DIRS)s.push(e.join(t,o,"settings.json")),s.push(e.join(n,o,"settings.json"));return s.push(e.join(t,".claude","settings.json")),dedupe(s)}function platformPath(o){return"win32"===(o||process.platform)?path.win32:path.posix}function homeDir(o={}){if(o.home)return String(o.home);const e=o.env||process.env,t="win32"===(o.platform||process.platform)?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const o of t)if(e&&e[o])return String(e[o]);return os.homedir()}function hookSourceKind(o){const e=path.posix.basename(String(o).replace(/\\/g,"/")),t=path.posix.basename(path.posix.dirname(String(o).replace(/\\/g,"/")));return"settings.json"!==e?"other":".claude"===t?"foreign":SETTINGS_DIRS.includes(t)?"aegis":"other"}function dedupe(o){const e=new Set,t=[];for(const n of o){const o=String(n).replace(/\\/g,"/");e.has(o)||(e.add(o),t.push(n))}return t}function shorten(o,e={}){const t=homeDir(e),n=String(o);if(!t)return n;const s=n.replace(/\\/g,"/"),r=String(t).replace(/\\/g,"/").replace(/\/+$/,"");return s===r?"~":s.startsWith(`${r}/`)?`~${s.slice(r.length)}`:n}function readHookConfig(o={}){const e=o.readFile||defaultReadFile,t=o.paths||hookSettingPaths(o),n={},s=[],r=[],i=[];for(const a of t){let t,c=null;try{c=e(a)}catch{c=null}if(null==c){i.push({path:a,exists:!1,kind:hookSourceKind(a)});continue}try{t=JSON.parse(String(c))}catch{i.push({path:a,exists:!0,parsed:!1,kind:hookSourceKind(a)});continue}const h=hookSourceKind(a),u=eventsOf(t),d=Object.keys(u);if(i.push({path:a,exists:!0,parsed:!0,kind:h,events:d}),"foreign"!==h){if(d.length){s.push(shorten(a,o));for(const[o,e]of Object.entries(u))Array.isArray(e)&&e.length&&(n[o]=[...n[o]||[],...e])}}else r.push(shorten(a,o))}return{hooks:n,from:s,foreign:r,files:i}}function eventsOf(o){if(!o||"object"!=typeof o)return{};if(o.hooks&&"object"==typeof o.hooks&&!Array.isArray(o.hooks)){const e={};for(const[t,n]of Object.entries(o.hooks))Array.isArray(n)&&(e[t]=n);return e}const e={};for(const t of HOOK_EVENTS)Array.isArray(o[t])&&(e[t]=o[t]);return e}const HOOK_EVENTS=["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStop","Notification","Compaction"];function hookStats(o){const e=o&&"object"==typeof o?o:{},t=Object.keys(e);let n=0;const s={};for(const o of t){const t=Array.isArray(e[o])?e[o]:[];s[o]=t.length,n+=t.length}return{enabled:n>0,hooks:n,events:t,byEvent:s}}const REQUIRED_HOOKS=["pre-commit","pre-push"],OPTIONAL_HOOKS=["post-merge","lib-gate.sh","push-policy"];function defaultRunGit(o,{cwd:e,env:t}={}){try{const n=execFileSync("git",o,{cwd:e,env:t||process.env,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});return{ok:!0,out:String(n).trim(),err:""}}catch(o){return{ok:!1,out:String(o&&o.stdout?o.stdout:"").trim(),err:String(o&&o.stderr?o.stderr:o&&o.message||o).trim()}}}function defaultReadFile(o){return fs.readFileSync(o,"utf8")}function defaultExists(o){try{return fs.statSync(o).isFile()}catch{return!1}}function defaultChmod(o){fs.chmodSync(o,493)}function repoHookStatus(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.exists||defaultExists,r=o.runGit||defaultRunGit,i=t.join(n,".githooks"),a=[],c=[];for(const o of[...REQUIRED_HOOKS,...OPTIONAL_HOOKS])s(t.join(i,o))?a.push(o):c.push(o);const h=r(["rev-parse","--is-inside-work-tree"],{cwd:n,env:o.env}),u=h.ok&&"true"===h.out;let d=null;if(u){const e=r(["config","--get","core.hooksPath"],{cwd:n,env:o.env});d=e.ok&&e.out?e.out:null}const f=".githooks";var l;return{repo:n,hooksDir:i,platform:e,inGitRepo:u,configured:d,wanted:f,installed:u&&(null==(l=d)?null:String(l).replace(/\\/g,"/").replace(/\/+$/,""))===f,present:a,missing:c,execBit:"win32"!==e,execNote:"win32"===e?"Windows: the exec bit is not enforced and not needed — git for Windows runs hooks with its bundled sh.":"POSIX: the hooks are chmod 0755 so git can execute them."}}function installRepoHooks(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.runGit||defaultRunGit,r=o.exists||defaultExists,i=o.chmod||defaultChmod,a=Boolean(o.dryRun),c=repoHookStatus({...o,platform:e,cwd:n,runGit:s,exists:r}),h=[];if(!r(t.join(c.hooksDir,"pre-commit")))return{ok:!1,changed:!1,code:"no-hooks",actions:h,status:c,error:`no ${c.wanted}/pre-commit under ${n} — nothing to install. A tree that never had the hooks needs them restored (\`git checkout -- .githooks/\`) or created (\`agent-gate.mjs init --hooks\`).`};if(!c.inGitRepo)return{ok:!1,changed:!1,code:"no-git",actions:h,status:c,error:`${n} is not inside a git work tree (core.hooksPath is a per-repo setting), or git is not on PATH.`};if(!c.installed&&(h.push(`git -C ${n} config core.hooksPath ${c.wanted}`),!a)){const e=s(["config","core.hooksPath",c.wanted],{cwd:n,env:o.env});if(!e.ok)return{ok:!1,changed:!1,code:"git-failed",actions:h,status:c,error:`git config refused: ${e.err||"unknown error"}`};const t=s(["config","--get","core.hooksPath"],{cwd:n,env:o.env}),r=t.ok?String(t.out).replace(/\\/g,"/").replace(/\/+$/,""):null;if(r!==c.wanted)return{ok:!1,changed:!0,code:"verify-failed",actions:h,status:c,error:`core.hooksPath reads back as "${r||"(unset)"}", not "${c.wanted}"`}}const u=[];if("win32"!==e){const
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),SETTINGS_DIRS=[".aegis",".aegiscode"];function hookSettingPaths(o={}){const e=platformPath(o.platform),t=homeDir(o),n=o.cwd||process.cwd(),s=[];for(const o of SETTINGS_DIRS)s.push(e.join(t,o,"settings.json")),s.push(e.join(n,o,"settings.json"));return s.push(e.join(t,".claude","settings.json")),dedupe(s)}function platformPath(o){return"win32"===(o||process.platform)?path.win32:path.posix}function homeDir(o={}){if(o.home)return String(o.home);const e=o.env||process.env,t="win32"===(o.platform||process.platform)?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const o of t)if(e&&e[o])return String(e[o]);return os.homedir()}function hookSourceKind(o){const e=path.posix.basename(String(o).replace(/\\/g,"/")),t=path.posix.basename(path.posix.dirname(String(o).replace(/\\/g,"/")));return"settings.json"!==e?"other":".claude"===t?"foreign":SETTINGS_DIRS.includes(t)?"aegis":"other"}function dedupe(o){const e=new Set,t=[];for(const n of o){const o=String(n).replace(/\\/g,"/");e.has(o)||(e.add(o),t.push(n))}return t}function shorten(o,e={}){const t=homeDir(e),n=String(o);if(!t)return n;const s=n.replace(/\\/g,"/"),r=String(t).replace(/\\/g,"/").replace(/\/+$/,"");return s===r?"~":s.startsWith(`${r}/`)?`~${s.slice(r.length)}`:n}function readHookConfig(o={}){const e=o.readFile||defaultReadFile,t=o.paths||hookSettingPaths(o),n={},s=[],r=[],i=[];for(const a of t){let t,c=null;try{c=e(a)}catch{c=null}if(null==c){i.push({path:a,exists:!1,kind:hookSourceKind(a)});continue}try{t=JSON.parse(String(c))}catch{i.push({path:a,exists:!0,parsed:!1,kind:hookSourceKind(a)});continue}const h=hookSourceKind(a),u=eventsOf(t),d=Object.keys(u);if(i.push({path:a,exists:!0,parsed:!0,kind:h,events:d}),"foreign"!==h){if(d.length){s.push(shorten(a,o));for(const[o,e]of Object.entries(u))Array.isArray(e)&&e.length&&(n[o]=[...n[o]||[],...e])}}else r.push(shorten(a,o))}return{hooks:n,from:s,foreign:r,files:i}}function eventsOf(o){if(!o||"object"!=typeof o)return{};if(o.hooks&&"object"==typeof o.hooks&&!Array.isArray(o.hooks)){const e={};for(const[t,n]of Object.entries(o.hooks))Array.isArray(n)&&(e[t]=n);return e}const e={};for(const t of HOOK_EVENTS)Array.isArray(o[t])&&(e[t]=o[t]);return e}const HOOK_EVENTS=["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStop","Notification","Compaction"];function hookStats(o){const e=o&&"object"==typeof o?o:{},t=Object.keys(e);let n=0;const s={};for(const o of t){const t=Array.isArray(e[o])?e[o]:[];s[o]=t.length,n+=t.length}return{enabled:n>0,hooks:n,events:t,byEvent:s}}const REQUIRED_HOOKS=["pre-commit","pre-push"],OPTIONAL_HOOKS=["post-merge","lib-gate.sh","push-policy"];function defaultRunGit(o,{cwd:e,env:t}={}){try{const n=execFileSync("git",o,{cwd:e,env:t||process.env,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});return{ok:!0,out:String(n).trim(),err:""}}catch(o){return{ok:!1,out:String(o&&o.stdout?o.stdout:"").trim(),err:String(o&&o.stderr?o.stderr:o&&o.message||o).trim()}}}function defaultReadFile(o){return fs.readFileSync(o,"utf8")}function defaultExists(o){try{return fs.statSync(o).isFile()}catch{return!1}}function defaultChmod(o){fs.chmodSync(o,493)}function repoHookStatus(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.exists||defaultExists,r=o.runGit||defaultRunGit,i=t.join(n,".githooks"),a=[],c=[];for(const o of[...REQUIRED_HOOKS,...OPTIONAL_HOOKS])s(t.join(i,o))?a.push(o):c.push(o);const h=r(["rev-parse","--is-inside-work-tree"],{cwd:n,env:o.env}),u=h.ok&&"true"===h.out;let d=null;if(u){const e=r(["config","--get","core.hooksPath"],{cwd:n,env:o.env});d=e.ok&&e.out?e.out:null}const f=".githooks";var l;return{repo:n,hooksDir:i,platform:e,inGitRepo:u,configured:d,wanted:f,installed:u&&(null==(l=d)?null:String(l).replace(/\\/g,"/").replace(/\/+$/,""))===f,present:a,missing:c,execBit:"win32"!==e,execNote:"win32"===e?"Windows: the exec bit is not enforced and not needed — git for Windows runs hooks with its bundled sh.":"POSIX: the hooks are chmod 0755 so git can execute them."}}function installRepoHooks(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.runGit||defaultRunGit,r=o.exists||defaultExists,i=o.chmod||defaultChmod,a=Boolean(o.dryRun),c=repoHookStatus({...o,platform:e,cwd:n,runGit:s,exists:r}),h=[];if(!r(t.join(c.hooksDir,"pre-commit")))return{ok:!1,changed:!1,code:"no-hooks",actions:h,status:c,error:`no ${c.wanted}/pre-commit under ${n} — nothing to install. A tree that never had the hooks needs them restored (\`git checkout -- .githooks/\`) or created (\`agent-gate.mjs init --hooks\`).`};if(!c.inGitRepo)return{ok:!1,changed:!1,code:"no-git",actions:h,status:c,error:`${n} is not inside a git work tree (core.hooksPath is a per-repo setting), or git is not on PATH.`};if(!c.installed&&(h.push(`git -C ${n} config core.hooksPath ${c.wanted}`),!a)){const e=s(["config","core.hooksPath",c.wanted],{cwd:n,env:o.env});if(!e.ok)return{ok:!1,changed:!1,code:"git-failed",actions:h,status:c,error:`git config refused: ${e.err||"unknown error"}`};const t=s(["config","--get","core.hooksPath"],{cwd:n,env:o.env}),r=t.ok?String(t.out).replace(/\\/g,"/").replace(/\/+$/,""):null;if(r!==c.wanted)return{ok:!1,changed:!0,code:"verify-failed",actions:h,status:c,error:`core.hooksPath reads back as "${r||"(unset)"}", not "${c.wanted}"`}}const u=[];if("win32"!==e){const e=o.modeOf||(o=>{try{return 511&fs.statSync(o).mode}catch{return null}});for(const o of c.present.filter((o=>"push-policy"!==o))){const n=t.join(c.hooksDir,o);if(493!==e(n))if(a)u.push(`chmod 0755 ${n}`);else try{i(n,493),u.push(`chmod 0755 ${o}`)}catch(e){u.push(`chmod 0755 ${o} FAILED: ${e&&e.message||e}`)}}h.push(...u)}return d={modes:u,note:c.execNote},{ok:!0,changed:h.length>0,code:"installed",actions:h,status:c,...d};var d}function hooksSummary(o={}){const e=o.platform||process.platform,t=o.config||readHookConfig({...o,platform:e}),n=o.stats||hookStats(t.hooks),s=o.repo||repoHookStatus({...o,platform:e}),r=[];if(r.push(`hooks: ${n.enabled?"enabled":"disabled"} · ${n.hooks} matcher(s) in ${n.events.length} event(s)`),n.events.length)for(const o of n.events)r.push(` ${o}: ${n.byEvent[o]}`);else r.push(" (no settings.json declares hooks — checked "+hookSettingPaths({...o,platform:e}).map((e=>shorten(e,o))).join(", ")+")");return t.from.length&&r.push(` from: ${t.from.join(", ")}`),t.foreign&&t.foreign.length&&r.push(` foreign host files (read, listed—${n.hooks&&t.foreign.length?"may outrank ours":"no hooks"}): ${t.foreign.join(", ")}`),r.push(""),r.push(`repo guard hooks (${s.wanted}/): ${s.present.length?s.present.join(", "):"none found"}`),s.missing.length&&r.push(` missing: ${s.missing.join(", ")}`),r.push(" core.hooksPath: "+(s.installed?`${s.wanted} (installed)`:`${s.configured||"(unset)"} — NOT installed, so a commit runs NO guard hooks`)),r.push(` ${s.execNote}`),r.join("\n")}module.exports={HOOK_EVENTS:HOOK_EVENTS,SETTINGS_DIRS:SETTINGS_DIRS,hooksSummary:hooksSummary,REQUIRED_HOOKS:REQUIRED_HOOKS,OPTIONAL_HOOKS:OPTIONAL_HOOKS,hookSettingPaths:hookSettingPaths,hookSourceKind:hookSourceKind,homeDir:homeDir,platformPath:platformPath,shorten:shorten,readHookConfig:readHookConfig,hookStats:hookStats,repoHookStatus:repoHookStatus,installRepoHooks:installRepoHooks};
|
|
@@ -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{sanitizeModel:sanitizeModel}=require("./user-models.js"),DISCOVERY_TIMEOUT_MS=8e3;function bearer(e){return{authorization:`Bearer ${e}`}}const ENDPOINTS=Object.freeze({anthropic:Object.freeze({url:"https://api.anthropic.com/v1/models",headers:e=>({"x-api-key":e,"anthropic-version":"2023-06-01"}),note:"the vendor requires anthropic-version; the console key is sent as x-api-key"}),openai:Object.freeze({url:"https://api.openai.com/v1/models",headers:bearer,note:"OpenAI-compatible: { data: [ { id } ] }"}),deepseek:Object.freeze({url:"https://api.deepseek.com/models",headers:bearer,note:"OpenAI-compatible; /v1/models answers the same list"}),grok:Object.freeze({url:"https://api.x.ai/v1/models",headers:bearer,note:"xAI answers on /v1/models under the vendor id grok"}),gemini:Object.freeze({url:"https://generativelanguage.googleapis.com/v1beta/models",headers:()=>({}),query:e=>({key:e}),note:'the key travels in the query string; ids come back as "models/<id>"'}),groq:Object.freeze({url:"https://api.groq.com/openai/v1/models",headers:bearer,note:"OpenAI-compatible under /openai/v1"}),mistral:Object.freeze({url:"https://api.mistral.ai/v1/models",headers:bearer,note:"OpenAI-compatible"}),openrouter:Object.freeze({url:"https://openrouter.ai/api/v1/models",headers:bearer,note:'OpenAI-compatible; ids are prefixed "vendor/model"'}),together:Object.freeze({url:"https://api.together.xyz/v1/models",headers:bearer,note:"OpenAI-compatible"}),cerebras:Object.freeze({url:"https://api.cerebras.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"}),fireworks:Object.freeze({url:"https://api.fireworks.ai/inference/v1/models",headers:bearer,note:'OpenAI-compatible under /inference/v1; ids are "accounts/fireworks/models/<id>"'}),nvidia_nim:Object.freeze({url:"https://integrate.api.nvidia.com/v1/models",headers:bearer,note:'OpenAI-compatible; ids are "<vendor>/<model>"'}),sakana:Object.freeze({url:"https://api.sakana.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"})}),ALIASES=Object.freeze({"x.ai":"grok",xai:"grok",google:"gemini","google-ai":"gemini",googleai:"gemini","open-ai":"openai","deep-seek":"deepseek","openai-gpt4o-mini":"openai","anthropic-haiku":"anthropic"}),NON_CHAT_RE=/embed|whisper|\btts\b|dall-e|moderation|rerank|imagen|\bveo\b|\baqa\b|transcribe|audio|speech|synthia|guard-content/i;function endpointFor(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)return null;const o=ALIASES[r]||r,t=ENDPOINTS[o];return t?Object.freeze({id:o,...t}):null}function canDiscover(e){return Boolean(endpointFor(e))}function discoverableProviders(){return Object.keys(ENDPOINTS).sort()}function looksNonChat(e){return NON_CHAT_RE.test(String(e))}function idsFromPayload(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.data)?e.data:Array.isArray(e&&e.models)?e.models:null;if(!r)return null;const o=[],t=[];for(const e of r){if(null==e)continue;const r="string"==typeof e?e:e.id||e.name||e.model;if("string"!=typeof r||!r.trim())continue;const n=r.trim().replace(/^models\//,""),i=e&&Array.isArray(e.supportedGenerationMethods)?e.supportedGenerationMethods:e&&Array.isArray(e.supported_actions)?e.supported_actions:null,s=i?i.includes("generateContent")||i.includes("generate"):null;let a;try{a=sanitizeModel(n)}catch{continue}!1===s||null===s&&looksNonChat(a)?t.push(a):o.push(a)}const n=e=>[...new Set(e)];return{ids:n(o),others:n(t).filter((e=>!o.includes(e)))}}async function discoverModels(e,r={}){const o=endpointFor(e),t=String(null==e?"":e).trim().toLowerCase(),n=String(null==r.key?"":r.key).trim();if(!o)return{ok:!1,provider:t,supported:!1,error:`${t||"that provider"} has no model-list endpoint this client knows`};if(!n)return{ok:!1,provider:o.id,supported:!0,error:`no ${o.id} key on this machine`};const i=r.fetchImpl||("function"==typeof fetch?fetch:null);if(!i)return{ok:!1,provider:o.id,supported:!0,error:"no fetch implementation available"};const s=Number.isFinite(r.timeoutMs)?r.timeoutMs:8e3,a="function"==typeof AbortController?new AbortController:null,d=a?setTimeout((()=>a.abort()),s):null,l=()=>a&&a.abort();a&&r.signal&&(r.signal.aborted?l():"function"==typeof r.signal.addEventListener&&r.signal.addEventListener("abort",l,{once:!0}));try{const
|
|
3
|
+
"use strict";const{sanitizeModel:sanitizeModel}=require("./user-models.js"),DISCOVERY_TIMEOUT_MS=8e3;function bearer(e){return{authorization:`Bearer ${e}`}}const ENDPOINTS=Object.freeze({anthropic:Object.freeze({url:"https://api.anthropic.com/v1/models",headers:e=>({"x-api-key":e,"anthropic-version":"2023-06-01"}),note:"the vendor requires anthropic-version; the console key is sent as x-api-key"}),openai:Object.freeze({url:"https://api.openai.com/v1/models",headers:bearer,note:"OpenAI-compatible: { data: [ { id } ] }"}),deepseek:Object.freeze({url:"https://api.deepseek.com/models",headers:bearer,note:"OpenAI-compatible; /v1/models answers the same list"}),grok:Object.freeze({url:"https://api.x.ai/v1/models",headers:bearer,note:"xAI answers on /v1/models under the vendor id grok"}),gemini:Object.freeze({url:"https://generativelanguage.googleapis.com/v1beta/models",headers:()=>({}),query:e=>({key:e}),note:'the key travels in the query string; ids come back as "models/<id>"'}),groq:Object.freeze({url:"https://api.groq.com/openai/v1/models",headers:bearer,note:"OpenAI-compatible under /openai/v1"}),mistral:Object.freeze({url:"https://api.mistral.ai/v1/models",headers:bearer,note:"OpenAI-compatible"}),openrouter:Object.freeze({url:"https://openrouter.ai/api/v1/models",headers:bearer,note:'OpenAI-compatible; ids are prefixed "vendor/model"'}),together:Object.freeze({url:"https://api.together.xyz/v1/models",headers:bearer,note:"OpenAI-compatible"}),cerebras:Object.freeze({url:"https://api.cerebras.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"}),fireworks:Object.freeze({url:"https://api.fireworks.ai/inference/v1/models",headers:bearer,note:'OpenAI-compatible under /inference/v1; ids are "accounts/fireworks/models/<id>"'}),nvidia_nim:Object.freeze({url:"https://integrate.api.nvidia.com/v1/models",headers:bearer,note:'OpenAI-compatible; ids are "<vendor>/<model>"'}),sakana:Object.freeze({url:"https://api.sakana.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"})}),ALIASES=Object.freeze({"x.ai":"grok",xai:"grok",google:"gemini","google-ai":"gemini",googleai:"gemini","open-ai":"openai","deep-seek":"deepseek","openai-gpt4o-mini":"openai","anthropic-haiku":"anthropic"}),NON_CHAT_RE=/embed|whisper|\btts\b|dall-e|moderation|rerank|imagen|\bveo\b|\baqa\b|transcribe|audio|speech|synthia|guard-content/i;function endpointFor(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)return null;const o=ALIASES[r]||r,t=ENDPOINTS[o];return t?Object.freeze({id:o,...t}):null}function canDiscover(e){return Boolean(endpointFor(e))}function discoverableProviders(){return Object.keys(ENDPOINTS).sort()}function looksNonChat(e){return NON_CHAT_RE.test(String(e))}function idsFromPayload(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.data)?e.data:Array.isArray(e&&e.models)?e.models:null;if(!r)return null;const o=[],t=[];for(const e of r){if(null==e)continue;const r="string"==typeof e?e:e.id||e.name||e.model;if("string"!=typeof r||!r.trim())continue;const n=r.trim().replace(/^models\//,""),i=e&&Array.isArray(e.supportedGenerationMethods)?e.supportedGenerationMethods:e&&Array.isArray(e.supported_actions)?e.supported_actions:null,s=i?i.includes("generateContent")||i.includes("generate"):null;let a;try{a=sanitizeModel(n)}catch{continue}!1===s||null===s&&looksNonChat(a)?t.push(a):o.push(a)}const n=e=>[...new Set(e)];return{ids:n(o),others:n(t).filter((e=>!o.includes(e)))}}async function discoverModels(e,r={}){const o=endpointFor(e),t=String(null==e?"":e).trim().toLowerCase(),n=String(null==r.key?"":r.key).trim();if(!o)return{ok:!1,provider:t,supported:!1,error:`${t||"that provider"} has no model-list endpoint this client knows`};if(!n)return{ok:!1,provider:o.id,supported:!0,error:`no ${o.id} key on this machine`};const i=r.fetchImpl||("function"==typeof fetch?fetch:null);if(!i)return{ok:!1,provider:o.id,supported:!0,error:"no fetch implementation available"};const s=Number.isFinite(r.timeoutMs)?r.timeoutMs:8e3,a="function"==typeof AbortController?new AbortController:null,d=a?setTimeout((()=>a.abort()),s):null,l=()=>a&&a.abort();a&&r.signal&&(r.signal.aborted?l():"function"==typeof r.signal.addEventListener&&r.signal.addEventListener("abort",l,{once:!0}));try{const e=new URL(o.url);if("function"==typeof o.query)for(const[r,t]of Object.entries(o.query(n)||{}))e.searchParams.set(r,t);const r={accept:"application/json"};for(const[e,t]of Object.entries(o.headers(n)||{}))r["authorization"===e?"Authorization":e]=t;const t=await i(e.toString(),{method:"GET",headers:r,signal:a?a.signal:void 0}),s=t&&"number"==typeof t.status?t.status:0;if(!t||"boolean"==typeof t.ok&&!t.ok){const r=401===s||403===s?`the vendor refused the key (HTTP ${s})`:404===s?`the vendor has no model list at ${e.pathname} (HTTP 404)`:`the vendor answered HTTP ${s||"nothing"}`;return{ok:!1,provider:o.id,supported:!0,status:s,error:r}}let d;try{d=await t.json()}catch(e){return{ok:!1,provider:o.id,supported:!0,status:s,error:`the vendor's reply was not JSON (${e&&e.message||e})`}}const l=idsFromPayload(d);return l?{ok:!0,provider:o.id,endpoint:o.url,ids:l.ids,others:l.others,count:l.ids.length}:{ok:!1,provider:o.id,supported:!0,status:s,error:'the vendor answered in a shape this client does not know (no "data" or "models" list)'}}catch(e){const r=e&&("AbortError"===e.name||"ABORT_ERR"===e.code)||a&&a.signal.aborted;return{ok:!1,provider:o.id,supported:!0,error:r?`the vendor did not answer within ${s} ms`:`could not reach the vendor (${e&&e.message||e})`}}finally{d&&clearTimeout(d),a&&r.signal&&"function"==typeof r.signal.removeEventListener&&r.signal.removeEventListener("abort",l)}}module.exports={DISCOVERY_TIMEOUT_MS:8e3,ENDPOINTS:ENDPOINTS,ALIASES:ALIASES,NON_CHAT_RE:NON_CHAT_RE,endpointFor:endpointFor,canDiscover:canDiscover,discoverableProviders:discoverableProviders,looksNonChat:looksNonChat,idsFromPayload:idsFromPayload,discoverModels:discoverModels};
|
package/vendor/client/naming.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
|
-
const
|
|
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
|
-
const t=require("node:fs"),e=require("node:os"),r=require("node:path"),{spawnSync:n}=require("node:child_process"),o="win32"===process.platform,i=".COM;.EXE;.BAT;.CMD";function s(e){try{return t.statSync(e).isFile()}catch{return!1}}function u(t,e=[],r={}){try{const o=n(t,e,{encoding:"utf8",timeout:r.timeout||5e3,windowsHide:!0,env:r.env});return o.error||0!==o.status?null:"string"==typeof o.stdout?o.stdout:""}catch{return null}}function c(e){try{return t.statSync(e).isDirectory()}catch{return!1}}function l(e){try{return t.readdirSync(e).length>0}catch{return!1}}function f(e){try{return t.readFileSync(e,"utf8")}catch{return null}}function a(t,e=[],r={}){try{const o=n(t,e,{encoding:"utf8",windowsHide:!0,timeout:r.timeout||1e4,env:r.env});if(o.error)return{ok:!1,error:o.error,output:""};if(0!==o.status){const e=String(o.stderr||"").trim();return{ok:!1,error:new Error(`${t} exited ${o.status}${e?`: ${e}`:""}`),status:o.status,output:String(o.stdout||"")}}return{ok:!0,error:null,output:String(o.stdout||"")}}catch(t){return{ok:!1,error:t,output:""}}}function p(t){const e=t&&"object"==typeof t?t:{},r="string"==typeof e.platform&&e.platform?e.platform:process.platform;return{o:e,platform:r,env:e.env&&"object"==typeof e.env?e.env:process.env,win32:"win32"===r,exists:"function"==typeof e.exists?e.exists:s,probe:"function"==typeof e.probe?e.probe:u,injectedProbe:"function"==typeof e.probe,kill:"function"==typeof e.kill?e.kill:(...t)=>process.kill(...t),run:"function"==typeof e.run?e.run:a}}function d(t,e,r){if(!t||"object"!=typeof t)return;const n=void 0!==t[e]?t[e]:t[e.toUpperCase()];if(void 0!==n)return n;if("win32"!==r)return;const o=e.toLowerCase();for(const e of Object.keys(t))if(e.toLowerCase()===o)return t[e]}function m(t,e){const r=String(d(t,"PATHEXT",e)||i).split(";").map((t=>t.trim())).filter(Boolean).map((t=>t.startsWith(".")?t:`.${t}`));return r.length?r:i.split(";")}function h(t){if(null==t)return"";const e=String(t).trim();if(!e)return"";const r=e.split("@")[0].split(".")[0];if(/^(c|posix)$/i.test(r))return"";const n=/^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(r);if(!n)return"";const o=n[1].toLowerCase();return"c"===o||"posix"===o?"":n[2]?`${o}-${n[2].toUpperCase()}`:o}function g(t={}){const{platform:r,env:n,o:o}=p(t);if("string"==typeof o.home)return o.home.trim();const i="win32"===r?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const t of i){const e=d(n,t,r);if(e&&String(e).trim())return String(e).trim()}try{return e.homedir()||""}catch{return""}}const y=/^[A-Za-z]:[\\/]/,w=/^[A-Za-z]:$/,k=/^\\\\[^\\?.]/,S={IS_WIN32:o,seams:p,resolveExecutable:function(t,e={}){const{platform:n,env:o,exists:i,win32:s,o:u}=p(e);if("string"!=typeof t||!t.trim())return null;const c=t.trim(),l="string"==typeof u.cwd&&u.cwd?u.cwd:process.cwd(),f=s?r.win32:r;if(s?c.includes("/")||c.includes("\\")||/^[a-zA-Z]:/.test(c):c.includes("/")){const t=f.isAbsolute(c)?c:f.join(l,c);return i(t)?t:null}const a=s?["",...m(o,n)]:[""];for(const t of function(t,e,r,n){const o=String(d(t,"PATH",e)||"").split("win32"===e?";":":"),i=[];for(const t of o){const e=t.trim().replace(/^"|"$/g,"");e&&i.push(n.isAbsolute(e)?e:n.join(r,e))}return i}(o,n,l,f))for(const e of a){const r=f.join(t,c+e);if(i(r))return r}return null},shellSpec:function(t={}){const{platform:e,env:r,win32:n}=p(t);return n?{cmd:d(r,"ComSpec",e)||d(r,"COMSPEC",e)||"cmd.exe",arg:"/d /s /c",kind:"cmd"}:{cmd:d(r,"SHELL",e)||"/bin/sh",arg:"-c",kind:"posix"}},killTree:function(t,e={}){const{platform:r,env:n,win32:o,kill:i,run:s,o:u}=p(e),c="number"==typeof t?t:t&&t.pid,l=u.signal||"SIGTERM",f=!1!==u.detached,a=u.timeout||1e4;if(!Number.isInteger(c)||c<=0)return{ok:!1,method:"none",pid:Number.isInteger(c)?c:null,error:new Error(`killTree: no usable pid (got ${JSON.stringify(t&&t.pid)})`),gone:!1};if(o){const t=s("taskkill",["/PID",String(c),"/T","/F"],{env:n,platform:r,timeout:a})||{};return!1===t.ok?{ok:!1,method:"taskkill",pid:c,error:t.error||new Error("taskkill failed"),gone:!1}:{ok:!0,method:"taskkill",pid:c,error:null,gone:!1}}let d=null;if(f)try{return i(-c,l),{ok:!0,method:"group",pid:c,error:null,gone:!1}}catch(t){d=t;const e=t&&t.code;if("ESRCH"!==e&&"EPERM"!==e)return{ok:!1,method:"group",pid:c,error:t,gone:!1}}try{return i(c,l),{ok:!0,method:"signal",pid:c,error:null,groupError:d,gone:!1}}catch(t){return{ok:!1,method:"signal",pid:c,error:t,groupError:d,gone:"ESRCH"===(t&&t.code)}}},isAlive:function(t,e={}){const{platform:r,env:n,win32:o,probe:i,kill:s}=p(e),u="number"==typeof t?t:Number(t);if(!Number.isInteger(u)||u<=0)return!1;if(o){const t=i("tasklist",["/FI",`PID eq ${u}`,"/NH","/FO","CSV"],{env:n,platform:r});if(null==t)return!1;const e=String(t).trim();return!!e&&new RegExp(`(^|[^0-9])${u}([^0-9]|$)`).test(e)}try{return s(u,0),!0}catch(t){return Boolean(t&&"EPERM"===t.code)}},hasDisplay:function(t={}){const{platform:e,env:r,win32:n,probe:o,injectedProbe:i}=p(t);return!!(n||"darwin"===e||d(r,"DISPLAY",e)||d(r,"WAYLAND_DISPLAY",e)||i&&null!==o("xdpyinfo",[],{env:r,platform:e}))},homeDir:g,desktopDir:function(t={}){const{platform:e,env:n,win32:o,probe:i,o:s}=p(t),u=o?r.win32:r.posix,a=g(t),m="function"==typeof s.dirExists?s.dirExists:c,h="function"==typeof s.dirNonEmpty?s.dirNonEmpty:l;if(o){const t=function(t,e){const r=t("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders","/v","Desktop"]);if(!r)return"";const n=/^\s*Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(r),o=n&&n[1].trim();return o&&e(o)?o:""}(i,m);if(t)return t}const y="function"==typeof s.readText?s.readText:f,w=[],k=t=>{t&&String(t).trim()&&w.push(String(t).trim())};if(o){const t=d(n,"OneDrive",e)||d(n,"OneDriveConsumer",e);t&&k(u.join(t,"Desktop")),a&&k(u.join(a,"OneDrive","Desktop")),a&&k(u.join(a,"Desktop"));const r=a?u.join(a,"Desktop"):"",o=w.indexOf(r);o>0&&m(r)&&h(r)&&w.slice(0,o).every((t=>!m(t)||!h(t)))&&(w.splice(o,1),w.unshift(r))}else if("darwin"===e)a&&k(u.join(a,"Desktop"));else{if(k(d(n,"XDG_DESKTOP_DIR",e)),a){const t=y(u.join(a,".config","user-dirs.dirs")),e=t&&/^\s*XDG_DESKTOP_DIR\s*=\s*"?([^"\n]+)"?\s*$/m.exec(t);e&&k(e[1].replace(/\$HOME\b|\${HOME}/g,a))}a&&k(u.join(a,"Desktop"))}for(const t of w)if(m(t))return t;return a&&(o||"darwin"===e)?u.join(a,"Desktop"):""},resolvePath:function(t,e={}){const{platform:n,win32:o,o:i}=p(e),s=o?r.win32:r.posix,u=t=>({ok:!1,path:null,error:t,expandedHome:!1});if("string"!=typeof t||!t.trim())return u(`a path is required (got ${JSON.stringify(t)})`);const c=t.trim();let l=c,f=!1;if("~"===c||c.startsWith("~/")||o&&c.startsWith("~\\")){const t=g(e);if(!t)return u(`cannot expand "~" in ${JSON.stringify(c)}: this machine reports no home directory. Pass a full absolute path instead.`);l="~"===c?t:s.join(t,c.slice(2)),f=!0}else if(c.startsWith("~"))return u(`${JSON.stringify(c)} names another user's home directory, which cannot be resolved from here. Use "~" for this user, or pass a full absolute path.`);if(l=function(t,{home:e,desktopdir:r,win32:n,P:o}){if(!e||!r)return t;const i=o.join(e,"Desktop"),s=t=>n?t.toLowerCase():t;if(s(i)===s(r))return t;if(s(t)===s(i))return r;const u=i+o.sep;return s(t).startsWith(s(u))?r+o.sep+t.slice(u.length):t}(l,{home:g(e),desktopdir:i.desktopdir,win32:o,P:s}),!f){const t=g(e),r=t?` This machine's home directory is ${t}.`:"";if(o){if((l.startsWith("/")||l.startsWith("\\"))&&!k.test(l))return u(`${JSON.stringify(c)} is not an absolute path on this machine, which runs ${n}. A leading slash here means "the root of the current drive", so writing to it would silently land somewhere other than where you meant. Use a drive-qualified path (C:\\Users\\you\\Desktop\\file.txt) or "~/…".${r}`)}else if(y.test(l)||w.test(l)||k.test(l))return u(`${JSON.stringify(c)} is a Windows path, but this machine runs ${n}. Use a posix path (/home/you/file.txt) or "~/…".${r}`)}const a="string"==typeof i.cwd&&i.cwd.trim()?i.cwd.trim():process.cwd(),d=s.isAbsolute(l)?s.resolve(l):s.resolve(a,l);return s.isAbsolute(d)?{ok:!0,path:d,error:null,expandedHome:f}:u(`${JSON.stringify(c)} is relative and the working directory (${JSON.stringify(a)}) is not absolute, so it cannot be resolved. Pass an absolute path.`)},baseName:function(t){if("string"!=typeof t)return"";const e=t.trim().replace(/[/\\]+$/,"");if(!e)return"";if(/^[A-Za-z]:$/.test(e))return"";const r=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return-1===r?e:e.slice(r+1)},hasPosixModes:function(t={}){const{win32:e}=p(t);return!e},appLocale:function(t={}){const{platform:e,env:r,o:n}=p(t);if("string"==typeof n.locale)return h(n.locale);const o=n.env&&"object"==typeof n.env;for(const t of["LC_ALL","LC_CTYPE","LC_MESSAGES","LANG"]){const n=h(d(r,t,e));if(n)return n}const i=String(d(r,"LANGUAGE",e)||"");if(i)for(const t of i.split(":")){const e=h(t);if(e)return e}if(o)return"";try{return h((new Intl.DateTimeFormat).resolvedOptions().locale)}catch{return""}},languageName:function(t,e={}){const{o:r}=p(e);if("string"==typeof r.languageName)return r.languageName;const n=h(t);if(!n)return"";const o=n.split("-")[0];try{return new Intl.DisplayNames(["en"],{type:"language"}).of(o)||""}catch{return""}},normalizeLocale:h};module.exports=S;
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{spawnSync:spawnSync}=require("node:child_process"),IS_WIN32="win32"===process.platform,DEFAULT_PATHEXT=".COM;.EXE;.BAT;.CMD";function defaultExists(e){try{return fs.statSync(e).isFile()}catch{return!1}}function defaultProbe(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",timeout:r.timeout||5e3,windowsHide:!0,env:r.env});return n.error||0!==n.status?null:"string"==typeof n.stdout?n.stdout:""}catch{return null}}function defaultDirExists(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function defaultDirNonEmpty(e){try{return fs.readdirSync(e).length>0}catch{return!1}}function defaultReadText(e){try{return fs.readFileSync(e,"utf8")}catch{return null}}function defaultRun(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeout||1e4,env:r.env});if(n.error)return{ok:!1,error:n.error,output:""};if(0!==n.status){const t=String(n.stderr||"").trim();return{ok:!1,error:new Error(`${e} exited ${n.status}${t?`: ${t}`:""}`),status:n.status,output:String(n.stdout||"")}}return{ok:!0,error:null,output:String(n.stdout||"")}}catch(e){return{ok:!1,error:e,output:""}}}function seams(e){const t=e&&"object"==typeof e?e:{},r="string"==typeof t.platform&&t.platform?t.platform:process.platform;return{o:t,platform:r,env:t.env&&"object"==typeof t.env?t.env:process.env,win32:"win32"===r,exists:"function"==typeof t.exists?t.exists:defaultExists,probe:"function"==typeof t.probe?t.probe:defaultProbe,injectedProbe:"function"==typeof t.probe,kill:"function"==typeof t.kill?t.kill:(...e)=>process.kill(...e),run:"function"==typeof t.run?t.run:defaultRun}}function envValue(e,t,r){if(!e||"object"!=typeof e)return;const n=void 0!==e[t]?e[t]:e[t.toUpperCase()];if(void 0!==n)return n;if("win32"!==r)return;const o=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===o)return e[t]}function pathEntries(e,t,r,n){const o=String(envValue(e,"PATH",t)||"").split("win32"===t?";":":"),s=[];for(const e of o){const t=e.trim().replace(/^"|"$/g,"");t&&s.push(n.isAbsolute(t)?t:n.join(r,t))}return s}function extList(e,t){const r=String(envValue(e,"PATHEXT",t)||DEFAULT_PATHEXT).split(";").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith(".")?e:`.${e}`));return r.length?r:DEFAULT_PATHEXT.split(";")}function resolveExecutable(e,t={}){const{platform:r,env:n,exists:o,win32:s,o:i}=seams(t);if("string"!=typeof e||!e.trim())return null;const a=e.trim(),l="string"==typeof i.cwd&&i.cwd?i.cwd:process.cwd(),u=s?path.win32:path;if(s?a.includes("/")||a.includes("\\")||/^[a-zA-Z]:/.test(a):a.includes("/")){const e=u.isAbsolute(a)?a:u.join(l,a);return o(e)?e:null}const c=s?["",...extList(n,r)]:[""];for(const e of pathEntries(n,r,l,u))for(const t of c){const r=u.join(e,a+t);if(o(r))return r}return null}function shellSpec(e={}){const{platform:t,env:r,win32:n}=seams(e);return n?{cmd:envValue(r,"ComSpec",t)||envValue(r,"COMSPEC",t)||"cmd.exe",arg:"/d /s /c",kind:"cmd"}:{cmd:envValue(r,"SHELL",t)||"/bin/sh",arg:"-c",kind:"posix"}}function killTree(e,t={}){const{platform:r,env:n,win32:o,kill:s,run:i,o:a}=seams(t),l="number"==typeof e?e:e&&e.pid,u=a.signal||"SIGTERM",c=!1!==a.detached,f=a.timeout||1e4;if(!Number.isInteger(l)||l<=0)return{ok:!1,method:"none",pid:Number.isInteger(l)?l:null,error:new Error(`killTree: no usable pid (got ${JSON.stringify(e&&e.pid)})`),gone:!1};if(o){const e=i("taskkill",["/PID",String(l),"/T","/F"],{env:n,platform:r,timeout:f})||{};return!1===e.ok?{ok:!1,method:"taskkill",pid:l,error:e.error||new Error("taskkill failed"),gone:!1}:{ok:!0,method:"taskkill",pid:l,error:null,gone:!1}}let p=null;if(c)try{return s(-l,u),{ok:!0,method:"group",pid:l,error:null,gone:!1}}catch(e){p=e;const t=e&&e.code;if("ESRCH"!==t&&"EPERM"!==t)return{ok:!1,method:"group",pid:l,error:e,gone:!1}}try{return s(l,u),{ok:!0,method:"signal",pid:l,error:null,groupError:p,gone:!1}}catch(e){return{ok:!1,method:"signal",pid:l,error:e,groupError:p,gone:"ESRCH"===(e&&e.code)}}}function isAlive(e,t={}){const{platform:r,env:n,win32:o,probe:s,kill:i}=seams(t),a="number"==typeof e?e:Number(e);if(!Number.isInteger(a)||a<=0)return!1;if(o){const e=s("tasklist",["/FI",`PID eq ${a}`,"/NH","/FO","CSV"],{env:n,platform:r});if(null==e)return!1;const t=String(e).trim();return!!t&&new RegExp(`(^|[^0-9])${a}([^0-9]|$)`).test(t)}try{return i(a,0),!0}catch(e){return Boolean(e&&"EPERM"===e.code)}}function hasDisplay(e={}){const{platform:t,env:r,win32:n,probe:o,injectedProbe:s}=seams(e);return!!(n||"darwin"===t||envValue(r,"DISPLAY",t)||envValue(r,"WAYLAND_DISPLAY",t)||s&&null!==o("xdpyinfo",[],{env:r,platform:t}))}function normalizeLocale(e){if(null==e)return"";const t=String(e).trim();if(!t)return"";const r=t.split("@")[0].split(".")[0];if(/^(c|posix)$/i.test(r))return"";const n=/^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(r);if(!n)return"";const o=n[1].toLowerCase();return"c"===o||"posix"===o?"":n[2]?`${o}-${n[2].toUpperCase()}`:o}function appLocale(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.locale)return normalizeLocale(n.locale);const o=n.env&&"object"==typeof n.env;for(const e of["LC_ALL","LC_CTYPE","LC_MESSAGES","LANG"]){const n=normalizeLocale(envValue(r,e,t));if(n)return n}const s=String(envValue(r,"LANGUAGE",t)||"");if(s)for(const e of s.split(":")){const t=normalizeLocale(e);if(t)return t}if(o)return"";try{return normalizeLocale((new Intl.DateTimeFormat).resolvedOptions().locale)}catch{return""}}function languageName(e,t={}){const{o:r}=seams(t);if("string"==typeof r.languageName)return r.languageName;const n=normalizeLocale(e);if(!n)return"";const o=n.split("-")[0];try{return new Intl.DisplayNames(["en"],{type:"language"}).of(o)||""}catch{return""}}function homeDir(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.home)return n.home.trim();const o="win32"===t?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const e of o){const n=envValue(r,e,t);if(n&&String(n).trim())return String(n).trim()}try{return os.homedir()||""}catch{return""}}function hasPosixModes(e={}){const{win32:t}=seams(e);return!t}function winShellFolderDesktop(e,t){const r=e("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders","/v","Desktop"]);if(!r)return"";const n=/^\s*Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(r),o=n&&n[1].trim();return o&&t(o)?o:""}function desktopDir(e={}){const{platform:t,env:r,win32:n,probe:o,o:s}=seams(e),i=n?path.win32:path.posix,a=homeDir(e),l="function"==typeof s.dirExists?s.dirExists:defaultDirExists,u="function"==typeof s.dirNonEmpty?s.dirNonEmpty:defaultDirNonEmpty;if(n){const e=winShellFolderDesktop(o,l);if(e)return e}const c="function"==typeof s.readText?s.readText:defaultReadText,f=[],p=e=>{e&&String(e).trim()&&f.push(String(e).trim())};if(n){const e=envValue(r,"OneDrive",t)||envValue(r,"OneDriveConsumer",t);e&&p(i.join(e,"Desktop")),a&&p(i.join(a,"OneDrive","Desktop")),a&&p(i.join(a,"Desktop"));const n=a?i.join(a,"Desktop"):"",o=f.indexOf(n);o>0&&l(n)&&u(n)&&f.slice(0,o).every((e=>!l(e)||!u(e)))&&(f.splice(o,1),f.unshift(n))}else if("darwin"===t)a&&p(i.join(a,"Desktop"));else{if(p(envValue(r,"XDG_DESKTOP_DIR",t)),a){const e=c(i.join(a,".config","user-dirs.dirs")),t=e&&/^\s*XDG_DESKTOP_DIR\s*=\s*"?([^"\n]+)"?\s*$/m.exec(e);t&&p(t[1].replace(/\$HOME\b|\${HOME}/g,a))}a&&p(i.join(a,"Desktop"))}for(const e of f)if(l(e))return e;return a&&(n||"darwin"===t)?i.join(a,"Desktop"):""}function applyDesktopAlias(e,{home:t,desktopdir:r,win32:n,P:o}){if(!t||!r)return e;const s=o.join(t,"Desktop"),i=e=>n?e.toLowerCase():e;if(i(s)===i(r))return e;if(i(e)===i(s))return r;const a=s+o.sep;return i(e).startsWith(i(a))?r+o.sep+e.slice(a.length):e}const WIN_DRIVE_RE=/^[A-Za-z]:[\\/]/,WIN_BARE_DRIVE_RE=/^[A-Za-z]:$/,WIN_UNC_RE=/^\\\\[^\\?.]/;function resolvePath(e,t={}){const{platform:r,win32:n,o:o}=seams(t),s=n?path.win32:path.posix,i=e=>({ok:!1,path:null,error:e,expandedHome:!1});if("string"!=typeof e||!e.trim())return i(`a path is required (got ${JSON.stringify(e)})`);const a=e.trim();let l=a,u=!1;if("~"===a||a.startsWith("~/")||n&&a.startsWith("~\\")){const e=homeDir(t);if(!e)return i(`cannot expand "~" in ${JSON.stringify(a)}: this machine reports no home directory. Pass a full absolute path instead.`);l="~"===a?e:s.join(e,a.slice(2)),u=!0}else if(a.startsWith("~"))return i(`${JSON.stringify(a)} names another user's home directory, which cannot be resolved from here. Use "~" for this user, or pass a full absolute path.`);if(l=applyDesktopAlias(l,{home:homeDir(t),desktopdir:o.desktopdir,win32:n,P:s}),!u){const e=homeDir(t),o=e?` This machine's home directory is ${e}.`:"";if(n){if((l.startsWith("/")||l.startsWith("\\"))&&!WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is not an absolute path on this machine, which runs ${r}. A leading slash here means "the root of the current drive", so writing to it would silently land somewhere other than where you meant. Use a drive-qualified path (C:\\Users\\you\\Desktop\\file.txt) or "~/…".${o}`)}else if(WIN_DRIVE_RE.test(l)||WIN_BARE_DRIVE_RE.test(l)||WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is a Windows path, but this machine runs ${r}. Use a posix path (/home/you/file.txt) or "~/…".${o}`)}const c="string"==typeof o.cwd&&o.cwd.trim()?o.cwd.trim():process.cwd(),f=s.isAbsolute(l)?s.resolve(l):s.resolve(c,l);return s.isAbsolute(f)?{ok:!0,path:f,error:null,expandedHome:u}:i(`${JSON.stringify(a)} is relative and the working directory (${JSON.stringify(c)}) is not absolute, so it cannot be resolved. Pass an absolute path.`)}function baseName(e){if("string"!=typeof e)return"";const t=e.trim().replace(/[/\\]+$/,"");if(!t)return"";if(/^[A-Za-z]:$/.test(t))return"";const r=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return-1===r?t:t.slice(r+1)}const api={IS_WIN32:IS_WIN32,seams:seams,resolveExecutable:resolveExecutable,shellSpec:shellSpec,killTree:killTree,isAlive:isAlive,hasDisplay:hasDisplay,homeDir:homeDir,desktopDir:desktopDir,resolvePath:resolvePath,baseName:baseName,hasPosixModes:hasPosixModes,appLocale:appLocale,languageName:languageName,normalizeLocale:normalizeLocale};module.exports=api;
|
|
@@ -95,11 +95,11 @@
|
|
|
95
95
|
* user's Drive or their account. The remote/root are overridable the same way
|
|
96
96
|
* (`AEGIS_VAULT_REMOTE`/`AEGIS_VAULT_ROOT`, `AEGIS_VAULT_BACKEND`), which is
|
|
97
97
|
* also what keeps a misconfigured vault from writing into an unrelated folder.
|
|
98
|
-
*/const crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),BACKEND_CLOUD="aegiscloud",BACKEND_RCLONE="rclone",DEFAULT_BACKEND=BACKEND_CLOUD,DEFAULT_REMOTE="gdrive",DEFAULT_ROOT="AEGIS-AGPL",RECORDS_DIR="records",INDEX_NAME="index.jsonl",ANCHOR_SUFFIX=".anchor.json",ANCHOR_VERSION=1,ANCHOR_KIND="aegiscode.record.anchor",INDEX_KIND="aegiscode.record.index",RCLONE_ENV="AEGIS_VAULT_RCLONE",REMOTE_ENV="AEGIS_VAULT_REMOTE",ROOT_ENV="AEGIS_VAULT_ROOT",BACKEND_ENV="AEGIS_VAULT_BACKEND",API_BASE_ENV="AEGIS_API_BASE",CLOUD_PREFIX="/api/v1/vault",RCLONE_TIMEOUT_MS=6e4,MAX_INSPECT_BYTES=2097152,MAX_AUDIT_FILES=500,KEY_PATH_PATTERNS=[/(^|\/)keys?\//i,/\.key$/i,/\.pem$/i,/(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.|$)/i,/(^|\/)agent\.key(\.|$)/i],BARE_TOKEN=/^[A-Za-z0-9_\-+/=]{40,}$/,BARE_HEX=/^[0-9a-fA-F]{32,}$/,PEM_PRIVATE=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;function flag(e,t,r=null){const n=Array.isArray(e)?e:[],o=n.indexOf(t);return-1===o||void 0===n[o+1]||String(n[o+1]).startsWith("--")?r:n[o+1]}function has(e,t){return(Array.isArray(e)?e:[]).includes(t)}function rcloneBinary(e=process.env,t=[]){return flag(t,"--rclone")||e[RCLONE_ENV]||"rclone"}function vaultTarget(e=process.env,t=[],r=null){const n=flag(t,"--remote")||e[REMOTE_ENV]||r&&r.remote||DEFAULT_REMOTE;return{backend:backendFor(e,t,n,r),remote:n,root:flag(t,"--root")||e[ROOT_ENV]||r&&r.root||DEFAULT_ROOT,apiBase:String(flag(t,"--base")||e[API_BASE_ENV]||"https://aegiscloud.org").replace(/\/+$/,""),rclone:rcloneBinary(e,t),env:e}}function backendFor(e,t,r,n=null){const o=String(flag(t,"--backend")||e[BACKEND_ENV]||"").trim().toLowerCase();if(o){if(o!==BACKEND_CLOUD&&o!==BACKEND_RCLONE)throw new Error(`vault: unknown backend "${o}" — expected ${BACKEND_CLOUD} or ${BACKEND_RCLONE}`);return o}return flag(t,"--remote")||e[REMOTE_ENV]?BACKEND_RCLONE:!n||n.backend!==BACKEND_CLOUD&&n.backend!==BACKEND_RCLONE?n&&void 0===n.backend&&n.remote&&n.remote!==DEFAULT_REMOTE?BACKEND_RCLONE:DEFAULT_BACKEND:n.backend}function remoteSpec(e,...t){return`${e.remote}:${[e.root,...t].filter(Boolean).join("/")}`
|
|
98
|
+
*/const crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),BACKEND_CLOUD="aegiscloud",BACKEND_RCLONE="rclone",DEFAULT_BACKEND=BACKEND_CLOUD,DEFAULT_REMOTE="gdrive",DEFAULT_ROOT="AEGIS-AGPL",RECORDS_DIR="records",INDEX_NAME="index.jsonl",ANCHOR_SUFFIX=".anchor.json",ANCHOR_VERSION=1,ANCHOR_KIND="aegiscode.record.anchor",INDEX_KIND="aegiscode.record.index",RCLONE_ENV="AEGIS_VAULT_RCLONE",REMOTE_ENV="AEGIS_VAULT_REMOTE",ROOT_ENV="AEGIS_VAULT_ROOT",BACKEND_ENV="AEGIS_VAULT_BACKEND",API_BASE_ENV="AEGIS_API_BASE",CLOUD_PREFIX="/api/v1/vault",RCLONE_TIMEOUT_MS=6e4,MAX_INSPECT_BYTES=2097152,MAX_AUDIT_FILES=500,KEY_PATH_PATTERNS=[/(^|\/)keys?\//i,/\.key$/i,/\.pem$/i,/(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.|$)/i,/(^|\/)agent\.key(\.|$)/i],BARE_TOKEN=/^[A-Za-z0-9_\-+/=]{40,}$/,BARE_HEX=/^[0-9a-fA-F]{32,}$/,PEM_PRIVATE=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;function flag(e,t,r=null){const n=Array.isArray(e)?e:[],o=n.indexOf(t);return-1===o||void 0===n[o+1]||String(n[o+1]).startsWith("--")?r:n[o+1]}function has(e,t){return(Array.isArray(e)?e:[]).includes(t)}function rcloneBinary(e=process.env,t=[]){return flag(t,"--rclone")||e[RCLONE_ENV]||"rclone"}function vaultTarget(e=process.env,t=[],r=null){const n=flag(t,"--remote")||e[REMOTE_ENV]||r&&r.remote||DEFAULT_REMOTE;return{backend:backendFor(e,t,n,r),remote:n,root:flag(t,"--root")||e[ROOT_ENV]||r&&r.root||DEFAULT_ROOT,apiBase:String(flag(t,"--base")||e[API_BASE_ENV]||"https://aegiscloud.org").replace(/\/+$/,""),rclone:rcloneBinary(e,t),env:e}}function backendFor(e,t,r,n=null){const o=String(flag(t,"--backend")||e[BACKEND_ENV]||"").trim().toLowerCase();if(o){if(o!==BACKEND_CLOUD&&o!==BACKEND_RCLONE)throw new Error(`vault: unknown backend "${o}" — expected ${BACKEND_CLOUD} or ${BACKEND_RCLONE}`);return o}return flag(t,"--remote")||e[REMOTE_ENV]?BACKEND_RCLONE:!n||n.backend!==BACKEND_CLOUD&&n.backend!==BACKEND_RCLONE?n&&void 0===n.backend&&n.remote&&n.remote!==DEFAULT_REMOTE?BACKEND_RCLONE:DEFAULT_BACKEND:n.backend}function remoteSpec(e,...t){return`${e.remote}:${[e.root,...t].filter(Boolean).join("/")}`}
|
|
99
99
|
/**
|
|
100
100
|
* A path *below* the root, however it was written: `records/x.json`,
|
|
101
101
|
* `<root>/records/x.json`, or an absolute `remote:…` spec. Everything that
|
|
102
102
|
* reads tolerates all three, because the anchor stores the browsable
|
|
103
103
|
* root-prefixed form (a human reads `AEGIS-AGPL/records/x.json`) while rclone
|
|
104
104
|
* wants it relative.
|
|
105
|
-
*/}function relativeToRoot(e,t){let r=String(t||"").replace(/^\/+/,"");const n=`${e.remote}:`;return r.startsWith(n)&&(r=r.slice(n.length)),r===e.root?"":(r.startsWith(`${e.root}/`)&&(r=r.slice(e.root.length+1)),r)}function remoteSpecOf(e,t){const r=relativeToRoot(e,t);return r?remoteSpec(e,r):remoteSpec(e)}function rcloneRun(e,t,{timeout:r=RCLONE_TIMEOUT_MS}={}){try{return execFileSync(e.rclone,t,{encoding:"utf8",timeout:r,stdio:["ignore","pipe","pipe"],maxBuffer:33554432,env:e.env?{...process.env,...e.env}:process.env})}catch(e){const r=String(e&&e.stderr||"").trim().split("\n").filter((e=>!/NOTICE:/.test(e))).pop()||e&&e.message||String(e),n=new Error(`vault: rclone ${t[0]} failed — ${r}`);throw n.code="ERCLONE",n.stderr=String(e&&e.stderr||""),n}}function tempDir(){return fs.mkdtempSync(path.join(os.tmpdir(),"aegis-vault-"))}function cloudApiKey(e={}){if(e.apiKey)return String(e.apiKey).trim();const t=e.env||process.env;try{const e=require("./credentials.js");return String(e.resolveApiKey({env:t,dir:e.aegisHome(t)}).key||"").trim()}catch{return""}}async function cloudRun(e,t,r,{body:n=null,raw:o=!1,timeout:a=RCLONE_TIMEOUT_MS,fetchImpl:s=null,apiKey:i=null}={}){const c=i||"";if(!c){const e=new Error("vault: no AEGIS account key on this machine — the aegiscloud vault is the account you already have. Run `aegiscode login`, or publish to a folder you own with `--backend rclone --remote <name>`.");throw e.code="ENOKEY",e}const l=s||("function"==typeof fetch?fetch:null);if(!l){const e=new Error("vault: this Node has no global fetch — upgrade to Node 22+ to use the aegiscloud vault");throw e.code="ENOFETCH",e}const u=new AbortController,d=setTimeout((()=>u.abort()),a);let h;try{h=await l(`${e.apiBase}${CLOUD_PREFIX}${r}`,{method:t,headers:{"Content-Type":"application/json","X-API-Key":c,Authorization:`Bearer ${c}`},body:null===n?void 0:JSON.stringify(n),signal:u.signal})}catch(t){const r=new Error(`vault: could not reach ${e.apiBase} — ${t&&t.message||t}`);throw r.code="ENETWORK",r}finally{clearTimeout(d)}const E=await h.text();let p=null;try{p=E?JSON.parse(E):null}catch{p=null}if(!h.ok){if(404===h.status&&(""===r||r.startsWith("?"))){const t=new Error(`vault: ${e.apiBase} does not serve the account vault yet (${CLOUD_PREFIX} is missing on this server). Publish to a folder you own instead: \`--backend rclone --remote <name> --root <folder>\`.`);throw t.code="ENOVAULT",t.status=404,t}const n=p&&(p.error||p.message)||E.slice(0,200)||`HTTP ${h.status}`,o=new Error(`vault: ${t} ${CLOUD_PREFIX}${r} failed — ${n}`);throw o.code="ECLOUD",o.status=h.status,o}return o?E:null===p?{}:p}function cloudObject(e,t){return`/${String(t||"").split("/").filter(Boolean).map((e=>encodeURIComponent(e))).join("/")}`}function transportFor(e,t={}){if(e.backend===BACKEND_CLOUD){const r=cloudApiKey(t),n=(n,o,a)=>cloudRun(e,n,o,{...a,fetchImpl:t.fetch,apiKey:r});return{backend:BACKEND_CLOUD,async put(t,r){await n("PUT",cloudObject(e,remoteObjectName(t)),{body:{content:r}})},async putFile(e,t){await this.put(e,fs.readFileSync(t,"utf8"))},async cat(t){try{const r=await n("GET",cloudObject(e,remoteObjectName(t)));return r&&"string"==typeof r.content?r.content:null}catch(e){if(404===e.status)return null;throw e}},async list(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}`);return Array.isArray(r&&r.files)?r.files:[]},async listRecursive(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}&recursive=1`);return Array.isArray(r&&r.files)?r.files:[]},describe:`${e.apiBase} (account vault)`}}return{backend:BACKEND_RCLONE,async put(t,r,{name:n="object"}={}){const o=tempDir();try{const a=path.join(o,n);fs.writeFileSync(a,r),rcloneRun(e,["copyto",a,remoteSpecOf(e,t)])}finally{fs.rmSync(o,{recursive:!0,force:!0})}},async putFile(t,r){rcloneRun(e,["copyto",r,remoteSpecOf(e,t)])},async cat(t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}},list:async t=>listRaw(e,t),listRecursive:async t=>rcloneLsjsonRecursive(e,t),describe:`${e.remote}:${e.root}`}}function remoteObjectName(e){return relativeToRoot({remote:"",root:""},e).replace(/^\/+/,"")}function inspect(e,t,{secret:r=null,keyPath:n=null}={}){const o=String(e||"");for(const e of KEY_PATH_PATTERNS)if(e.test(o))return{dangerous:!0,reason:`the path looks like key material (${e})`};if(n&&path.resolve(o)===path.resolve(n))return{dangerous:!0,reason:"this path IS the authorship key"};const a=String(null==t?"":t),s=a.trim();if(r&&s.includes(String(r)))return{dangerous:!0,reason:"the content carries the authorship key verbatim"};if(PEM_PRIVATE.test(a))return{dangerous:!0,reason:"the content is a PEM private key"};const i=1===s.split("\n").length;if(i&&BARE_TOKEN.test(s)&&!BARE_HEX.test(s))return{dangerous:!0,reason:"the content is a bare high-entropy token (a raw secret)"};if(i&&BARE_HEX.test(s))return{dangerous:!0,reason:"the content is an unlabelled hex blob (a raw digest or key)"};let c=null;try{c=JSON.parse(a)}catch{c=null}if(c&&"object"==typeof c&&!Array.isArray(c)){if("string"==typeof c.kind&&c.kind.startsWith("aegiscode."))return inspectArtifact(c,r);try{fp.assertNoLeak(c,r||"")}catch(e){return{dangerous:!0,reason:e&&e.message||"failed the leak check"}}}return{dangerous:!1,reason:null}}function inspectArtifact(e,t){const r=new Set(["sha256","attestation","code"]);for(const[n,o]of Object.entries(e)){if(null==o)continue;const e=Array.isArray(o)?o.join("\0"):String(o);if(t&&e.includes(String(t)))return{dangerous:!0,reason:`the link carries the authorship key verbatim in "${n}"`};if(!r.has(n)&&fp.longHexRun(e))return{dangerous:!0,reason:`the link carries a long hex run in "${n}"`}}return void 0===e.sha256||/^[0-9a-f]{64}$/.test(String(e.sha256))?void 0===e.attestation||/^[0-9a-f]{32}$/.test(String(e.attestation))?{dangerous:!1,reason:null}:{dangerous:!0,reason:"the link's attestation is not a 32-hex tag"}:{dangerous:!0,reason:"the link's sha256 is not a 64-hex digest"}}function assertPublishable(e,t,r={}){const n=inspect(e,t,r);if(n.dangerous)throw new Error(`vault: refusing to publish ${e} — ${n.reason}. The vault carries sealed records only: a key that reaches cloud storage can mint records indistinguishable from yours, so it is never a backup. Keep it in ${authorship.defaultKeyPath(r.env||process.env)} (0600) and back it up to a local disk or a password manager.`);return!0}function baseName(e,t=null){const r=e&&e.behaviour?String(e.behaviour):"unobserved",n=String(t||e&&e.createdAt||(new Date).toISOString()).replace(/[:.]/g,"-");return`${e.keyFingerprint}-${r}.${n}`}function driveUrl(e){return e?`https://drive.google.com/open?id=${encodeURIComponent(e)}`:null}function sha256(e){return crypto.createHash("sha256").update(e,"utf8").digest("hex")}function readRecord({file:e=null,record:t=null,secret:r=null,env:n=process.env}){if(e){const t=path.resolve(e);if(!fs.existsSync(t))throw new Error(`vault: no record at ${t}`);const o=fs.readFileSync(t,"utf8");let a;assertPublishable(t,o,{secret:r,keyPath:authorship.defaultKeyPath(n),env:n});try{a=JSON.parse(o)}catch(e){throw new Error(`vault: ${t} is not JSON — ${e.message}`)}return{text:o,record:a,file:t,serialised:o}}if(t){const e=JSON.stringify(t,null,2)+"\n";return{text:e,record:t,file:null,serialised:e}}throw new Error("vault: publish needs a record file or a record")}async function publish(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=Boolean(e.dryRun)||has(r,"--dry-run"),a=void 0===e.index?!has(r,"--no-index"):Boolean(e.index),s=e.secret||null,{text:i,record:c,file:l}=readRecord({...e,secret:s,env:t});let u;try{u=fp.id(c)}catch(e){throw new Error(`vault: not a sealed φ(α) record — ${e&&e.message||e}`)}const d=authorship.defaultKeyPath(t);assertPublishable(path.basename(l||"record.json"),i,{secret:s,keyPath:d,env:t});const h=`${baseName(c)}.json`,E=`${h}${ANCHOR_SUFFIX}`,p=`${RECORDS_DIR}/${h}`,f=`${RECORDS_DIR}/${E}`,N=sha256(i),y={v:1,kind:ANCHOR_KIND,id:u,keyFingerprint:c.keyFingerprint,behaviour:c.behaviour||null,code:c.code||null,createdAt:c.createdAt,attestation:c.attestation,sha256:N,bytes:Buffer.byteLength(i,"utf8"),backend:n.backend,remote:n.remote,root:n.root,path:n.backend===BACKEND_CLOUD?`${CLOUD_PREFIX}/${p}`:`${n.root}/${p}`,key:p,emittedAt:new Date(e.now||Date.now()).toISOString(),driveId:null,url:null,index:a?`${n.root}/${RECORDS_DIR}/${INDEX_NAME}`:null},A=transportFor(n,e);if(o)return{ok:!0,dryRun:!0,backend:n.backend,anchor:y,url:null,remotePath:y.path,commands:n.backend===BACKEND_CLOUD?[`PUT ${n.apiBase}${CLOUD_PREFIX}/${p}`,`PUT ${n.apiBase}${CLOUD_PREFIX}/${f}`]:[`rclone copyto ${l||"<record>"} ${remoteSpec(n,p)}`,`rclone copyto <anchor> ${remoteSpec(n,f)}`]};l?await A.putFile(p,l):await A.put(p,i,{name:h});const g=(await A.list(RECORDS_DIR)).find((e=>String(e.Name)===h))||null;g&&(y.driveId=g.ID||null,y.url=g.url||(n.backend===BACKEND_CLOUD?null:driveUrl(g.ID)));const O=l?`${l}${ANCHOR_SUFFIX}`:null,R=JSON.stringify(y,null,2)+"\n";await A.put(f,R,{name:E}),O&&fs.writeFileSync(O,R);let _=null;return a&&(_=await appendIndex(n,y,A)),{ok:!0,dryRun:!1,backend:n.backend,anchor:y,url:y.url,localAnchor:O,remotePath:y.path,bytes:y.bytes,sha256:N,indexLines:_}}function rcloneCat(e,t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}}function listRaw(e,t){let r;try{r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only"])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404|directory not found/i.test(e.stderr||e.message))return[];throw e}const n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}async function appendIndex(e,t,r=transportFor(e)){const n=`${RECORDS_DIR}/${INDEX_NAME}`,o=await r.cat(n)||"",a=JSON.stringify({kind:INDEX_KIND,id:t.id,keyFingerprint:t.keyFingerprint,sha256:t.sha256,path:t.path,url:t.url,driveId:t.driveId,emittedAt:t.emittedAt});return await r.put(n,o+a+"\n",{name:INDEX_NAME}),(o.trim()?o.trim().split("\n").length:0)+1}function localAnchor(e){const t=`${path.resolve(e)}${ANCHOR_SUFFIX}`;if(!fs.existsSync(t))return null;try{return JSON.parse(fs.readFileSync(t,"utf8"))}catch{return null}}async function checkAnchor(e={}){const t=e.env||process.env,r=e.argv||[],n=e.anchor||(e.file?localAnchor(e.file):null);if(!n)return{ok:!1,reason:"not linked — no anchor beside this record (publish it first)",present:!1,unchanged:null,attested:null};const o=transportFor(vaultTarget(t,r,n),e),a=await o.cat(n.key||n.path);if(null===a)return{ok:!1,reason:`no copy at ${n.path}`,present:!1,unchanged:!1,attested:null,anchor:n};const s=sha256(a)===n.sha256;let i=null,c=null;try{const n=e.key||authorship.resolveKey({argv:r,env:t});if(n.secret){const e=fp.verify(JSON.parse(a),n.secret);i=e.ok,c=e.reason}else c="no authorship key on this machine to recompute with"}catch(e){c=e&&e.message||String(e)}return{ok:s&&!1!==i,anchor:n,present:!0,unchanged:s,attested:i,attestationReason:c,remotePath:n.path,url:n.url,reason:s?!1===i?`the published copy does not verify: ${c}`:null:"the published copy is not the bytes that were sealed (sha256 differs)"}}async function list(e={}){const t=vaultTarget(e.env||process.env,e.argv||[]),r=transportFor(t,e),n=RECORDS_DIR,o=await r.list(n),a=o.filter((e=>String(e.Name).endsWith(ANCHOR_SUFFIX))),s=o.filter((e=>!String(e.Name).endsWith(ANCHOR_SUFFIX)&&String(e.Name).endsWith(".json")&&e.Name!==INDEX_NAME)),i=[];for(const e of s){const t=a.find((t=>String(t.Name)===`${e.Name}${ANCHOR_SUFFIX}`));let o=null;if(t){const e=await r.cat(`${n}/${t.Name}`);try{o=JSON.parse(e)}catch{o={unreadable:!0}}}i.push({name:e.Name,bytes:e.Size,emittedAt:e.ModTime,id:o?o.id:null,keyFingerprint:o?o.keyFingerprint:null,sha256:o?o.sha256:null,driveId:o&&o.driveId||e.ID||null,url:o&&o.url||e.url||driveUrl(e.ID),linked:Boolean(o)})}return{ok:!0,backend:t.backend,remote:t.remote,root:t.root,where:r.describe,records:i}}async function audit(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=transportFor(n,e),a=Number(flag(r,"--max"))||500;let s;try{s=await o.listRecursive("")}catch(e){return{ok:!1,backend:n.backend,where:o.describe,error:e&&e.message||String(e),findings:[],checked:0}}const i=e.secret||null,c=[],l=[];let u=0;for(const t of s){const r=String(t.Path||t.Name);if(u>=a){l.push({path:r,reason:`stopped after ${a} files`});continue}if(Number(t.Size)>2097152){l.push({path:r,reason:"larger than 2097152 bytes"});continue}let n;u+=1;try{n=await o.cat(r)}catch(e){l.push({path:r,reason:e&&e.message||String(e)});continue}const s=inspect(r,n,{secret:i});s.dangerous&&c.push({path:r,reason:s.reason})}return{ok:0===c.length,backend:n.backend,remote:n.remote,root:n.root,where:o.describe,checked:u,files:s.length,uninspected:l,findings:c}}function rcloneLsjsonRecursive(e,t){const r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only","--recursive"]),n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}module.exports={DEFAULT_REMOTE:DEFAULT_REMOTE,DEFAULT_ROOT:DEFAULT_ROOT,DEFAULT_BACKEND:DEFAULT_BACKEND,BACKEND_CLOUD:BACKEND_CLOUD,BACKEND_RCLONE:BACKEND_RCLONE,CLOUD_PREFIX:CLOUD_PREFIX,BACKEND_ENV:BACKEND_ENV,API_BASE_ENV:API_BASE_ENV,RECORDS_DIR:RECORDS_DIR,INDEX_NAME:INDEX_NAME,ANCHOR_SUFFIX:ANCHOR_SUFFIX,ANCHOR_KIND:ANCHOR_KIND,INDEX_KIND:INDEX_KIND,RCLONE_ENV:RCLONE_ENV,REMOTE_ENV:REMOTE_ENV,ROOT_ENV:ROOT_ENV,inspect:inspect,assertPublishable:assertPublishable,publish:publish,checkAnchor:checkAnchor,list:list,audit:audit,localAnchor:localAnchor,relativeToRoot:relativeToRoot,remoteSpecOf:remoteSpecOf,baseName:baseName,driveUrl:driveUrl,vaultTarget:vaultTarget,rcloneBinary:rcloneBinary,rcloneCat:rcloneCat,transportFor:transportFor,cloudApiKey:cloudApiKey,backendFor:backendFor,sha256:sha256,flag:flag,has:has};
|
|
105
|
+
*/function relativeToRoot(e,t){let r=String(t||"").replace(/^\/+/,"");const n=`${e.remote}:`;return r.startsWith(n)&&(r=r.slice(n.length)),r===e.root?"":(r.startsWith(`${e.root}/`)&&(r=r.slice(e.root.length+1)),r)}function remoteSpecOf(e,t){const r=relativeToRoot(e,t);return r?remoteSpec(e,r):remoteSpec(e)}function rcloneRun(e,t,{timeout:r=RCLONE_TIMEOUT_MS}={}){try{return execFileSync(e.rclone,t,{encoding:"utf8",timeout:r,stdio:["ignore","pipe","pipe"],maxBuffer:33554432,env:e.env?{...process.env,...e.env}:process.env})}catch(e){const r=String(e&&e.stderr||"").trim().split("\n").filter((e=>!/NOTICE:/.test(e))).pop()||e&&e.message||String(e),n=new Error(`vault: rclone ${t[0]} failed — ${r}`);throw n.code="ERCLONE",n.stderr=String(e&&e.stderr||""),n}}function tempDir(){return fs.mkdtempSync(path.join(os.tmpdir(),"aegis-vault-"))}function cloudApiKey(e={}){if(e.apiKey)return String(e.apiKey).trim();const t=e.env||process.env;try{const e=require("./credentials.js");return String(e.resolveApiKey({env:t,dir:e.aegisHome(t)}).key||"").trim()}catch{return""}}async function cloudRun(e,t,r,{body:n=null,raw:o=!1,timeout:a=RCLONE_TIMEOUT_MS,fetchImpl:s=null,apiKey:i=null}={}){const c=i||"";if(!c){const e=new Error("vault: no AEGIS account key on this machine — the aegiscloud vault is the account you already have. Run `aegiscode login`, or publish to a folder you own with `--backend rclone --remote <name>`.");throw e.code="ENOKEY",e}const l=s||("function"==typeof fetch?fetch:null);if(!l){const e=new Error("vault: this Node has no global fetch — upgrade to Node 22+ to use the aegiscloud vault");throw e.code="ENOFETCH",e}const u=new AbortController,d=setTimeout((()=>u.abort()),a);let h;try{h=await l(`${e.apiBase}${CLOUD_PREFIX}${r}`,{method:t,headers:{"Content-Type":"application/json","X-API-Key":c,Authorization:`Bearer ${c}`},body:null===n?void 0:JSON.stringify(n),signal:u.signal})}catch(t){const r=new Error(`vault: could not reach ${e.apiBase} — ${t&&t.message||t}`);throw r.code="ENETWORK",r}finally{clearTimeout(d)}const E=await h.text();let p=null;try{p=E?JSON.parse(E):null}catch{p=null}if(!h.ok){if(404===h.status&&(""===r||r.startsWith("?"))){const t=new Error(`vault: ${e.apiBase} does not serve the account vault yet (${CLOUD_PREFIX} is missing on this server). Publish to a folder you own instead: \`--backend rclone --remote <name> --root <folder>\`.`);throw t.code="ENOVAULT",t.status=404,t}const n=p&&(p.error||p.message)||E.slice(0,200)||`HTTP ${h.status}`,o=new Error(`vault: ${t} ${CLOUD_PREFIX}${r} failed — ${n}`);throw o.code="ECLOUD",o.status=h.status,o}return o?E:null===p?{}:p}function cloudObject(e,t){return`/${String(t||"").split("/").filter(Boolean).map((e=>encodeURIComponent(e))).join("/")}`}function transportFor(e,t={}){if(e.backend===BACKEND_CLOUD){const r=cloudApiKey(t),n=(n,o,a)=>cloudRun(e,n,o,{...a,fetchImpl:t.fetch,apiKey:r});return{backend:BACKEND_CLOUD,async put(t,r){await n("PUT",cloudObject(e,remoteObjectName(t)),{body:{content:r}})},async putFile(e,t){await this.put(e,fs.readFileSync(t,"utf8"))},async cat(t){try{const r=await n("GET",cloudObject(e,remoteObjectName(t)));return r&&"string"==typeof r.content?r.content:null}catch(e){if(404===e.status)return null;throw e}},async list(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}`);return Array.isArray(r&&r.files)?r.files:[]},async listRecursive(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}&recursive=1`);return Array.isArray(r&&r.files)?r.files:[]},describe:`${e.apiBase} (account vault)`}}return{backend:BACKEND_RCLONE,async put(t,r,{name:n="object"}={}){const o=tempDir();try{const a=path.join(o,n);fs.writeFileSync(a,r),rcloneRun(e,["copyto",a,remoteSpecOf(e,t)])}finally{fs.rmSync(o,{recursive:!0,force:!0})}},async putFile(t,r){rcloneRun(e,["copyto",r,remoteSpecOf(e,t)])},async cat(t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}},list:async t=>listRaw(e,t),listRecursive:async t=>rcloneLsjsonRecursive(e,t),describe:`${e.remote}:${e.root}`}}function remoteObjectName(e){return relativeToRoot({remote:"",root:""},e).replace(/^\/+/,"")}function inspect(e,t,{secret:r=null,keyPath:n=null}={}){const o=String(e||"");for(const e of KEY_PATH_PATTERNS)if(e.test(o))return{dangerous:!0,reason:`the path looks like key material (${e})`};if(n&&path.resolve(o)===path.resolve(n))return{dangerous:!0,reason:"this path IS the authorship key"};const a=String(null==t?"":t),s=a.trim();if(r&&s.includes(String(r)))return{dangerous:!0,reason:"the content carries the authorship key verbatim"};if(PEM_PRIVATE.test(a))return{dangerous:!0,reason:"the content is a PEM private key"};const i=1===s.split("\n").length;if(i&&BARE_TOKEN.test(s)&&!BARE_HEX.test(s))return{dangerous:!0,reason:"the content is a bare high-entropy token (a raw secret)"};if(i&&BARE_HEX.test(s))return{dangerous:!0,reason:"the content is an unlabelled hex blob (a raw digest or key)"};let c=null;try{c=JSON.parse(a)}catch{c=null}if(c&&"object"==typeof c&&!Array.isArray(c)){if("string"==typeof c.kind&&c.kind.startsWith("aegiscode."))return inspectArtifact(c,r);try{fp.assertNoLeak(c,r||"")}catch(e){return{dangerous:!0,reason:e&&e.message||"failed the leak check"}}}return{dangerous:!1,reason:null}}function inspectArtifact(e,t){const r=new Set(["sha256","attestation","code"]);for(const[n,o]of Object.entries(e)){if(null==o)continue;const e=Array.isArray(o)?o.join("\0"):String(o);if(t&&e.includes(String(t)))return{dangerous:!0,reason:`the link carries the authorship key verbatim in "${n}"`};if(!r.has(n)&&fp.longHexRun(e))return{dangerous:!0,reason:`the link carries a long hex run in "${n}"`}}return void 0===e.sha256||/^[0-9a-f]{64}$/.test(String(e.sha256))?void 0===e.attestation||/^[0-9a-f]{32}$/.test(String(e.attestation))?{dangerous:!1,reason:null}:{dangerous:!0,reason:"the link's attestation is not a 32-hex tag"}:{dangerous:!0,reason:"the link's sha256 is not a 64-hex digest"}}function assertPublishable(e,t,r={}){const n=inspect(e,t,r);if(n.dangerous)throw new Error(`vault: refusing to publish ${e} — ${n.reason}. The vault carries sealed records only: a key that reaches cloud storage can mint records indistinguishable from yours, so it is never a backup. Keep it in ${authorship.defaultKeyPath(r.env||process.env)} (0600) and back it up to a local disk or a password manager.`);return!0}function baseName(e,t=null){const r=e&&e.behaviour?String(e.behaviour):"unobserved",n=String(t||e&&e.createdAt||(new Date).toISOString()).replace(/[:.]/g,"-");return`${e.keyFingerprint}-${r}.${n}`}function driveUrl(e){return e?`https://drive.google.com/open?id=${encodeURIComponent(e)}`:null}function sha256(e){return crypto.createHash("sha256").update(e,"utf8").digest("hex")}function readRecord({file:e=null,record:t=null,secret:r=null,env:n=process.env}){if(e){const t=path.resolve(e);if(!fs.existsSync(t))throw new Error(`vault: no record at ${t}`);const o=fs.readFileSync(t,"utf8");let a;assertPublishable(t,o,{secret:r,keyPath:authorship.defaultKeyPath(n),env:n});try{a=JSON.parse(o)}catch(e){throw new Error(`vault: ${t} is not JSON — ${e.message}`)}return{text:o,record:a,file:t,serialised:o}}if(t){const e=JSON.stringify(t,null,2)+"\n";return{text:e,record:t,file:null,serialised:e}}throw new Error("vault: publish needs a record file or a record")}async function publish(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=Boolean(e.dryRun)||has(r,"--dry-run"),a=void 0===e.index?!has(r,"--no-index"):Boolean(e.index),s=e.secret||null,{text:i,record:c,file:l}=readRecord({...e,secret:s,env:t});let u;try{u=fp.id(c)}catch(e){throw new Error(`vault: not a sealed φ(α) record — ${e&&e.message||e}`)}const d=authorship.defaultKeyPath(t);assertPublishable(path.basename(l||"record.json"),i,{secret:s,keyPath:d,env:t});const h=`${baseName(c)}.json`,E=`${h}${ANCHOR_SUFFIX}`,p=`${RECORDS_DIR}/${h}`,f=`${RECORDS_DIR}/${E}`,N=sha256(i),y={v:1,kind:ANCHOR_KIND,id:u,keyFingerprint:c.keyFingerprint,behaviour:c.behaviour||null,code:c.code||null,createdAt:c.createdAt,attestation:c.attestation,sha256:N,bytes:Buffer.byteLength(i,"utf8"),backend:n.backend,remote:n.remote,root:n.root,path:n.backend===BACKEND_CLOUD?`${CLOUD_PREFIX}/${p}`:`${n.root}/${p}`,key:p,emittedAt:new Date(e.now||Date.now()).toISOString(),driveId:null,url:null,index:a?`${n.root}/${RECORDS_DIR}/${INDEX_NAME}`:null},A=transportFor(n,e);if(o)return{ok:!0,dryRun:!0,backend:n.backend,anchor:y,url:null,remotePath:y.path,commands:n.backend===BACKEND_CLOUD?[`PUT ${n.apiBase}${CLOUD_PREFIX}/${p}`,`PUT ${n.apiBase}${CLOUD_PREFIX}/${f}`]:[`rclone copyto ${l||"<record>"} ${remoteSpec(n,p)}`,`rclone copyto <anchor> ${remoteSpec(n,f)}`]};l?await A.putFile(p,l):await A.put(p,i,{name:h});const g=(await A.list(RECORDS_DIR)).find((e=>String(e.Name)===h))||null;g&&(y.driveId=g.ID||null,y.url=g.url||(n.backend===BACKEND_CLOUD?null:driveUrl(g.ID)));const O=l?`${l}${ANCHOR_SUFFIX}`:null,R=JSON.stringify(y,null,2)+"\n";await A.put(f,R,{name:E}),O&&fs.writeFileSync(O,R);let _=null;return a&&(_=await appendIndex(n,y,A)),{ok:!0,dryRun:!1,backend:n.backend,anchor:y,url:y.url,localAnchor:O,remotePath:y.path,bytes:y.bytes,sha256:N,indexLines:_}}function rcloneCat(e,t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}}function listRaw(e,t){let r;try{r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only"])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404|directory not found/i.test(e.stderr||e.message))return[];throw e}const n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}async function appendIndex(e,t,r=transportFor(e)){const n=`${RECORDS_DIR}/${INDEX_NAME}`,o=await r.cat(n)||"",a=JSON.stringify({kind:INDEX_KIND,id:t.id,keyFingerprint:t.keyFingerprint,sha256:t.sha256,path:t.path,url:t.url,driveId:t.driveId,emittedAt:t.emittedAt});return await r.put(n,o+a+"\n",{name:INDEX_NAME}),(o.trim()?o.trim().split("\n").length:0)+1}function localAnchor(e){const t=`${path.resolve(e)}${ANCHOR_SUFFIX}`;if(!fs.existsSync(t))return null;try{return JSON.parse(fs.readFileSync(t,"utf8"))}catch{return null}}async function checkAnchor(e={}){const t=e.env||process.env,r=e.argv||[],n=e.anchor||(e.file?localAnchor(e.file):null);if(!n)return{ok:!1,reason:"not linked — no anchor beside this record (publish it first)",present:!1,unchanged:null,attested:null};const o=transportFor(vaultTarget(t,r,n),e),a=await o.cat(n.key||n.path);if(null===a)return{ok:!1,reason:`no copy at ${n.path}`,present:!1,unchanged:!1,attested:null,anchor:n};const s=sha256(a)===n.sha256;let i=null,c=null;try{const n=e.key||authorship.resolveKey({argv:r,env:t});if(n.secret){const e=fp.verify(JSON.parse(a),n.secret);i=e.ok,c=e.reason}else c="no authorship key on this machine to recompute with"}catch(e){c=e&&e.message||String(e)}return{ok:s&&!1!==i,anchor:n,present:!0,unchanged:s,attested:i,attestationReason:c,remotePath:n.path,url:n.url,reason:s?!1===i?`the published copy does not verify: ${c}`:null:"the published copy is not the bytes that were sealed (sha256 differs)"}}async function list(e={}){const t=vaultTarget(e.env||process.env,e.argv||[]),r=transportFor(t,e),n=RECORDS_DIR,o=await r.list(n),a=o.filter((e=>String(e.Name).endsWith(ANCHOR_SUFFIX))),s=o.filter((e=>!String(e.Name).endsWith(ANCHOR_SUFFIX)&&String(e.Name).endsWith(".json")&&e.Name!==INDEX_NAME)),i=[];for(const e of s){const t=a.find((t=>String(t.Name)===`${e.Name}${ANCHOR_SUFFIX}`));let o=null;if(t){const e=await r.cat(`${n}/${t.Name}`);try{o=JSON.parse(e)}catch{o={unreadable:!0}}}i.push({name:e.Name,bytes:e.Size,emittedAt:e.ModTime,id:o?o.id:null,keyFingerprint:o?o.keyFingerprint:null,sha256:o?o.sha256:null,driveId:o&&o.driveId||e.ID||null,url:o&&o.url||e.url||driveUrl(e.ID),linked:Boolean(o)})}return{ok:!0,backend:t.backend,remote:t.remote,root:t.root,where:r.describe,records:i}}async function audit(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=transportFor(n,e),a=Number(flag(r,"--max"))||500;let s;try{s=await o.listRecursive("")}catch(e){return{ok:!1,backend:n.backend,where:o.describe,error:e&&e.message||String(e),findings:[],checked:0}}const i=e.secret||null,c=[],l=[];let u=0;for(const e of s){const t=String(e.Path||e.Name);if(u>=a){l.push({path:t,reason:`stopped after ${a} files`});continue}if(Number(e.Size)>2097152){l.push({path:t,reason:"larger than 2097152 bytes"});continue}let r;u+=1;try{r=await o.cat(t)}catch(e){l.push({path:t,reason:e&&e.message||String(e)});continue}const n=inspect(t,r,{secret:i});n.dangerous&&c.push({path:t,reason:n.reason})}return{ok:0===c.length,backend:n.backend,remote:n.remote,root:n.root,where:o.describe,checked:u,files:s.length,uninspected:l,findings:c}}function rcloneLsjsonRecursive(e,t){const r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only","--recursive"]),n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}module.exports={DEFAULT_REMOTE:DEFAULT_REMOTE,DEFAULT_ROOT:DEFAULT_ROOT,DEFAULT_BACKEND:DEFAULT_BACKEND,BACKEND_CLOUD:BACKEND_CLOUD,BACKEND_RCLONE:BACKEND_RCLONE,CLOUD_PREFIX:CLOUD_PREFIX,BACKEND_ENV:BACKEND_ENV,API_BASE_ENV:API_BASE_ENV,RECORDS_DIR:RECORDS_DIR,INDEX_NAME:INDEX_NAME,ANCHOR_SUFFIX:ANCHOR_SUFFIX,ANCHOR_KIND:ANCHOR_KIND,INDEX_KIND:INDEX_KIND,RCLONE_ENV:RCLONE_ENV,REMOTE_ENV:REMOTE_ENV,ROOT_ENV:ROOT_ENV,inspect:inspect,assertPublishable:assertPublishable,publish:publish,checkAnchor:checkAnchor,list:list,audit:audit,localAnchor:localAnchor,relativeToRoot:relativeToRoot,remoteSpecOf:remoteSpecOf,baseName:baseName,driveUrl:driveUrl,vaultTarget:vaultTarget,rcloneBinary:rcloneBinary,rcloneCat:rcloneCat,transportFor:transportFor,cloudApiKey:cloudApiKey,backendFor:backendFor,sha256:sha256,flag:flag,has:has};
|
|
@@ -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
|
-
const
|
|
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,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"),credentials=require("./credentials.js"),USER_MODELS_FILE="models.json",FILE_MODE=384,MAX_MODELS_PER_PROVIDER=32,MAX_PROVIDERS=64,PROVIDER_RE=/^[a-z0-9][a-z0-9._-]{0,63}$/,MODEL_RE=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,95}$/;function userModelsDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function userModelsPath(e){return path.join(userModelsDir(e),USER_MODELS_FILE)}function badValue(e,r,o){return new Error(`aegiscode: ${e} ${JSON.stringify(String(r))} is not usable — ${o}`)}function sanitizeProvider(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)throw badValue("provider",e,"the provider id is empty");if(!PROVIDER_RE.test(r))throw badValue("provider",e,"a provider id is lowercase letters, digits, dot, dash or underscore (the id `/byok` prints)");return r}function sanitizeModel(e){const r=String(null==e?"":e).trim();if(!r)throw badValue("model id",e,"the model id is empty");if(/:/.test(r))throw badValue("model id",e,"'provider:model' is how a picked model is addressed, so a model id cannot contain a colon");if(!MODEL_RE.test(r))throw badValue("model id",e,"a model id has no spaces — it is the string sent to the vendor (e.g. deepseek-v4.2-preview, claude-opus-9-1)");return r}function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function load(e){const r=userModelsPath(e),o=[];let s;try{s=JSON.parse(fs.readFileSync(r,"utf8"))}catch(s){return s&&"ENOENT"===s.code||o.push({provider:null,model:null,reason:`unreadable: ${s&&s.message||s}`}),{dir:userModelsDir(e),file:r,map:{},invalid:o}}const i={};if(!isPlainObject(s))return o.push({provider:null,model:null,reason:"the file must be an object of provider → [model ids]"}),{dir:userModelsDir(e),file:r,map:i,invalid:o};for(const[e,
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),credentials=require("./credentials.js"),USER_MODELS_FILE="models.json",FILE_MODE=384,MAX_MODELS_PER_PROVIDER=32,MAX_PROVIDERS=64,PROVIDER_RE=/^[a-z0-9][a-z0-9._-]{0,63}$/,MODEL_RE=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,95}$/;function userModelsDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function userModelsPath(e){return path.join(userModelsDir(e),USER_MODELS_FILE)}function badValue(e,r,o){return new Error(`aegiscode: ${e} ${JSON.stringify(String(r))} is not usable — ${o}`)}function sanitizeProvider(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)throw badValue("provider",e,"the provider id is empty");if(!PROVIDER_RE.test(r))throw badValue("provider",e,"a provider id is lowercase letters, digits, dot, dash or underscore (the id `/byok` prints)");return r}function sanitizeModel(e){const r=String(null==e?"":e).trim();if(!r)throw badValue("model id",e,"the model id is empty");if(/:/.test(r))throw badValue("model id",e,"'provider:model' is how a picked model is addressed, so a model id cannot contain a colon");if(!MODEL_RE.test(r))throw badValue("model id",e,"a model id has no spaces — it is the string sent to the vendor (e.g. deepseek-v4.2-preview, claude-opus-9-1)");return r}function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function load(e){const r=userModelsPath(e),o=[];let s;try{s=JSON.parse(fs.readFileSync(r,"utf8"))}catch(s){return s&&"ENOENT"===s.code||o.push({provider:null,model:null,reason:`unreadable: ${s&&s.message||s}`}),{dir:userModelsDir(e),file:r,map:{},invalid:o}}const i={};if(!isPlainObject(s))return o.push({provider:null,model:null,reason:"the file must be an object of provider → [model ids]"}),{dir:userModelsDir(e),file:r,map:i,invalid:o};for(const[e,r]of Object.entries(s)){if("version"===e||"$schema"===e)continue;let s;try{s=sanitizeProvider(e)}catch(r){o.push({provider:e,model:null,reason:r.message});continue}const t=Array.isArray(r)?r:[r],d=new Set,n=[];for(const e of t){let r;try{r=sanitizeModel(e)}catch(r){o.push({provider:s,model:e,reason:r.message});continue}d.has(r)||(d.add(r),n.push(r))}n.length&&(i[s]=n)}return{dir:userModelsDir(e),file:r,map:i,invalid:o}}function readUserModels(e){return load(e).map}function userModelIdsFor(e,r){let o;try{o=sanitizeProvider(e)}catch{return[]}const s=readUserModels(r);return Array.isArray(s[o])?s[o].slice():[]}function writeMap(e,r){const o=userModelsPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0});const s=`${o}.tmp-${process.pid}`;fs.writeFileSync(s,JSON.stringify(e,null,2)+"\n",{mode:FILE_MODE}),fs.renameSync(s,o);try{fs.chmodSync(o,FILE_MODE)}catch{}return e}function addUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(d.includes(i))return{file:userModelsPath(o),provider:s,model:i,added:!1,models:d};if(d.length>=32)throw new Error(`aegiscode: ${s} already carries ${d.length} user models (the cap) — remove one with /model-rm before adding another.`);if(!t[s]&&Object.keys(t).length>=64)throw new Error(`aegiscode: ${Object.keys(t).length} providers already carry user models (the cap).`);const n=[...d,i];return writeMap({...t,[s]:n},o),{file:userModelsPath(o),provider:s,model:i,added:!0,models:n}}function removeUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(!d.includes(i))return{file:userModelsPath(o),provider:s,model:i,removed:!1,models:d};const n=d.filter((e=>e!==i)),a={...t};return n.length?a[s]=n:delete a[s],writeMap(a,o),{file:userModelsPath(o),provider:s,model:i,removed:!0,models:n}}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function withUserModels(e,r){const o=providerArray(e);if(!o)return[];const s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=[];for(const e of o){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",o=r&&Array.isArray(s[r])?s[r]:null;if(!o||!o.length){i.push(e);continue}const t=new Set(modelIdsOf(e)),d=o.map((e=>String(e).trim())).filter((e=>e&&!t.has(e)));if(!d.length){i.push(e);continue}const n=Array.isArray(e.models)?e.models:[];i.push({...e,models:[...n,...d]})}return i}function unmatchedUserProviders(e,r){const o=providerArray(e)||[],s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=new Set(o.map((e=>e&&"string"==typeof e.id?e.id.trim():"")).filter(Boolean));return Object.keys(s).filter((e=>!i.has(e)))}module.exports={USER_MODELS_FILE:USER_MODELS_FILE,MAX_MODELS_PER_PROVIDER:32,userModelsDir:userModelsDir,userModelsPath:userModelsPath,sanitizeProvider:sanitizeProvider,sanitizeModel:sanitizeModel,load:load,readUserModels:readUserModels,userModelIdsFor:userModelIdsFor,addUserModel:addUserModel,removeUserModel:removeUserModel,withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders};
|