aegisone 1.0.39 → 1.0.41
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/LICENSING.md +186 -0
- package/README.md +2 -2
- package/bin/aegis.js +1 -1
- package/package.json +3 -2
- package/scripts/predist.mjs +1 -1
- package/src/child.js +1 -1
- package/src/permissions.js +1 -1
- package/vendor/cli/package.json +4 -2
- package/vendor/cli/src/app.js +1 -1
- package/vendor/cli/src/chatflow.js +1 -1
- package/vendor/cli/src/commands.js +3 -1
- package/vendor/cli/src/config.js +1 -1
- package/vendor/cli/src/diff.js +1 -1
- package/vendor/cli/src/diffview.js +1 -1
- package/vendor/cli/src/engine.js +1 -1
- package/vendor/cli/src/history.js +1 -1
- package/vendor/cli/src/models.js +1 -1
- package/vendor/cli/src/overlays.js +1 -1
- package/vendor/cli/src/panels.js +1 -1
- package/vendor/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/cli/vendor/client/credits.js +45 -0
- package/vendor/cli/vendor/client/foreign-sessions.js +3 -0
- package/vendor/cli/vendor/client/naming.js +1 -1
- package/vendor/cli/vendor/client/prefs.js +1 -1
- package/vendor/cli/vendor/client/session-search.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +42 -2
- package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +206 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-store.js +298 -0
- package/vendor/cli/vendor/desktop/lib/local/perm-write.js +199 -0
- package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
- package/vendor/cli/vendor/desktop/lib/local/sandbox.js +493 -0
- package/vendor/cli/vendor/desktop/lib/local/shell.js +155 -20
- package/vendor/cli/vendor/desktop/lib/local/tools.js +29 -4
- package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/cli/vendor/desktop/main.js +774 -37
- package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/cli/vendor/mcp/admission.js +3 -0
- package/vendor/cli/vendor/mcp/server.js +1 -1
- package/vendor/cli/vendor/one/src/child.js +1 -1
- package/vendor/cli/vendor/one/src/permissions.js +1 -1
- package/vendor/desktop/bin/aegis.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/integrity.js +42 -2
- package/vendor/desktop/lib/local/perm-rules.js +206 -0
- package/vendor/desktop/lib/local/perm-store.js +298 -0
- package/vendor/desktop/lib/local/perm-write.js +199 -0
- package/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/desktop/lib/local/sandbox-appcontainer.js +242 -0
- package/vendor/desktop/lib/local/sandbox-bwrap.js +316 -0
- package/vendor/desktop/lib/local/sandbox-seatbelt.js +380 -0
- package/vendor/desktop/lib/local/sandbox.js +493 -0
- package/vendor/desktop/lib/local/shell.js +155 -20
- package/vendor/desktop/lib/local/tools.js +29 -4
- package/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/lib/sync/memory-store.js +3 -0
- package/vendor/desktop/main.js +774 -37
- package/vendor/desktop/package.json +19 -7
- package/vendor/desktop/preload.js +1 -1
- package/vendor/desktop/renderer/app.js +5 -1
- package/vendor/desktop/renderer/diff.js +1 -1
- package/vendor/desktop/renderer/diffview.js +1 -1
- package/vendor/desktop/renderer/index.html +221 -5
- package/vendor/desktop/renderer/provider-mark.js +1 -1
- package/vendor/desktop/renderer/provider-toolbar.js +1 -1
- package/vendor/desktop/renderer/providers.js +1 -1
- package/vendor/desktop/renderer/style.css +223 -6
- package/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/vendor/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/credits.js +45 -0
- package/vendor/desktop/vendor/faces/cli/package.json +3 -2
- package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/commands.js +3 -1
- package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +45 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-bwrap.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/sandbox.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +4 -2
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/permissions.js +1 -1
- package/vendor/desktop/vendor/foreign-sessions.js +3 -0
- package/vendor/desktop/vendor/naming.js +1 -1
- package/vendor/desktop/vendor/prefs.js +1 -1
- package/vendor/desktop/vendor/sandbox/provenance.json +20 -0
- package/vendor/desktop/vendor/sandbox/x64-linux/bwrap +0 -0
- package/vendor/desktop/vendor/session-search.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
|
-
"use strict";const{spawn:spawn}=require("node:child_process"),crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{pathToFileURL:pathToFileURL}=require("node:url"),{agentRoles:agentRoles}=require("./agents.js");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`tools.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const OUTPUT_CAP=3e4,PATH_ARG_DESC='Absolute path on THIS machine; "~"/"~/…" = home. Relative resolves against the working directory.',pathDesc=e=>`${e}. ${PATH_ARG_DESC}`,shells=require("./shell.js"),integrity=require("./integrity.js"),READ_LINE_CAP=2e3,MATCH_CAP=100,READ_SIZE_CAP=26214400,GREP_SIZE_CAP=10485760,EXEC_TIMEOUT_DEFAULT=12e4,EXEC_TIMEOUT_CAP=6e5,EXEC_MAX_BUFFER=1048576,DIFF_MAX_CELLS=4e6,DIFF_MAX_LINES=2e4,spill=require("./spill.js");function cap(e){return spill.cap(e,3e4)}const ok=e=>({ok:!0,output:cap(e)}),fail=e=>({ok:!1,error:cap(e)}),SCHEMAS={readFile:{name:"readFile",description:"Read a file. Returns line-numbered content.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to read")},offset:{type:"number",description:"Start line (0-based)"},limit:{type:"number",description:"The number of lines to read (max 10000, default 2000)"}},required:["file_path"],additionalProperties:!1}},writeFile:{name:"writeFile",description:"Write a whole file, overwriting it. Parent dirs are created. Use editFile to change part of one.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to write")},content:{type:"string",description:"Full file contents"}},required:["file_path","content"],additionalProperties:!1}},editFile:{name:"editFile",description:"Exact string replacement. old_string must be unique unless replace_all. Fails loudly on a missing or ambiguous match rather than guessing. Pass `edits` to apply several hunks to one file in ONE call — they are applied in order, each against the result of the last, which is cheaper than one call per hunk.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to edit")},old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"},edits:{type:"array",description:"Several hunks for this one file, applied in order. Use instead of old_string/new_string.",items:{type:"object",properties:{old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"}},required:["old_string","new_string"],additionalProperties:!1}}},required:["file_path"],additionalProperties:!1}},listDir:{name:"listDir",description:"List one directory (non-recursive). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{path:{type:"string",description:pathDesc("The directory to list (default: the working directory)")}},required:[],additionalProperties:!1}},glob:{name:"glob",description:"Find files by glob (**, *, ?). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob, e.g. "**/*.test.js"'},path:{type:"string",description:pathDesc("Search root (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},grep:{name:"grep",description:"Search file contents by regex. Returns file:line matches. Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression to search for"},path:{type:"string",description:pathDesc("The directory to search in (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},exec:{name:"exec",description:"Run a shell command in a PERSISTENT session: cd and exported env carry across calls in this turn. Returns stdout+stderr and the exit code. Use for git, packages, system ops.",parameters:{type:"object",properties:{command:{type:"string",description:"Command to run"},cwd:{type:"string",description:pathDesc("Run this one command elsewhere; session cwd unchanged")},timeout:{type:"number",description:`Timeout in milliseconds (max ${EXEC_TIMEOUT_CAP}, default ${EXEC_TIMEOUT_DEFAULT})`},description:{type:"string",description:"A brief description of what the command does (for display)"}},required:["command"],additionalProperties:!1}},hooks:{name:"hooks",description:"Hook status for this machine, from the same shared implementation the CLI's /hooks uses: the merged settings.json hook config (~/.aegis, ./.aegis, ~/.aegiscode, ./.aegiscode, ~/.claude) and whether this repo's .githooks/ guard hooks are actually installed (core.hooksPath). Read-only. Use installHooks to install them.",parameters:{type:"object",properties:{sub:{type:"string",enum:["status","list"],description:"status (default) or the full config listing"},cwd:{type:"string",description:pathDesc("Repo to inspect (default: the working directory)")}},required:[],additionalProperties:!1}},installHooks:{name:"installHooks",description:"Install this repo's guard hooks: point git's core.hooksPath at .githooks/ (the agent-key gate, the secret scan, the invariant lock) and make them executable. Idempotent, and verified by reading the config back. Pass dry_run to see the exact commands without running them. Without this, a fresh clone runs NO guard hooks.",parameters:{type:"object",properties:{cwd:{type:"string",description:pathDesc("Repo to install into (default: the working directory)")},dry_run:{type:"boolean",description:"Print the commands instead of running them"}},required:[],additionalProperties:!1}},task:{name:"task",description:"Delegate a focused multi-step sub-task to a subagent with its own tool loop; it returns a final report. Give it a complete, self-contained prompt — it cannot ask follow-ups.",parameters:{type:"object",properties:{description:{type:"string",description:"Short label (3-5 words)"},subagent_type:{type:"string",enum:[...agentRoles(),"general"],description:"Which specialist preset to spawn (general = a capable all-purpose agent)"},prompt:{type:"string",description:"The full, self-contained task instructions for the subagent"}},required:["description","prompt"],additionalProperties:!1}}},SUBAGENT_TOOL="task",HOOK_TOOLS=new Set(["hooks","installHooks"]);function toolNames({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>e.name))}function schemaList({includeSubagent:e=!0,includeHooks:t=!1}={}){return Object.values(SCHEMAS).filter((r=>(e||r.name!==SUBAGENT_TOOL)&&(t||!HOOK_TOOLS.has(r.name))))}function openaiTools({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}})))}function toolsFor({includeSubagent:e=!0,includeHooks:t=!1}={}){return openaiTools({includeSubagent:e,includeHooks:t})}const TOOL_PATH_ARGS=Object.freeze({readFile:["file_path"],writeFile:["file_path"],editFile:["file_path"],listDir:["path"],glob:["path"],grep:["path"],exec:["cwd"],hooks:["cwd"],installHooks:["cwd"]});function normalizeArgs(e,t,r={}){const i=t&&"object"==typeof t?t:{},o=TOOL_PATH_ARGS[e];if(!o)return{ok:!0,args:i,error:null};let n=i;for(const t of o){const o=i[t];if("string"!=typeof o||!o.trim())continue;const s=platform.resolvePath(o,{platform:r&&r.platform?r.platform:void 0,cwd:r&&r.cwd?r.cwd:void 0,desktopdir:r&&r.desktopdir?r.desktopdir:void 0});if(!s.ok)return{ok:!1,args:i,error:`${e}: ${t} — ${s.error}`};s.path!==o&&(n===i&&(n={...i}),n[t]=s.path)}return{ok:!0,args:n,error:null}}function baseDir(e){return e&&"string"==typeof e.cwd&&e.cwd||process.cwd()}function readFile({file_path:e,offset:t=0,limit:r}={}){try{if(!e)return fail("file_path is required");const i=fs.statSync(e);if(i.isDirectory())return fail(`${e} is a directory (use listDir)`);if(i.size>26214400){const t=(i.size/1048576).toFixed(1);return fail(`${e} is ${t} MB — too large to read (limit 25 MB). Use exec with grep/head to inspect it instead.`)}const o=fs.readFileSync(e,"utf8").split("\n"),n=Math.max(0,Number(t)||0),s=Math.max(1,Math.min(Number(r)||2e3,1e4)),a=o.slice(n,n+s),l=a.map(((e,t)=>`${t+n+1}| ${e}`)).join("\n"),c=n+a.length<o.length?`\n… (${o.length-n-a.length} more lines)`:"";return ok(l+c)}catch(e){return fail(e&&e.message?e.message:String(e))}}function writeFile({file_path:e,content:t}={}){try{return e?(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail("file_path is required")}catch(e){return fail(e&&e.message?e.message:String(e))}}function editFile(e={}){try{const t=previewEditFile(e);if(!t.ok)return fail(t.error);fs.writeFileSync(e.file_path,t.after,"utf8");const r=Array.isArray(e.edits)?e.edits.length:1,i=r>1?`${r} hunks, ${t.count} occurrence${t.count>1?"s":""} replaced`:`${t.count} occurrence${t.count>1?"s":""} replaced`;return ok(`Edited ${e.file_path} (${i})`)}catch(e){return fail(e&&e.message?e.message:String(e))}}const MUTATING_TOOLS=new Set(["exec","writeFile","editFile","installHooks"]);function sha256(e){return crypto.createHash("sha256").update(null==e?"":e,"utf8").digest("hex")}function readForPreview(e){try{return fs.existsSync(e)?fs.statSync(e).isDirectory()?{ok:!1,error:`${e} is a directory`}:{ok:!0,exists:!0,content:fs.readFileSync(e,"utf8")}:{ok:!0,exists:!1,content:null}}catch(e){return{ok:!1,error:e&&e.message?e.message:String(e)}}}function diffLines(e,t){const r=e.length,i=t.length,o=new Array(r+1);for(let e=0;e<=r;e++)o[e]=new Int32Array(i+1);for(let n=r-1;n>=0;n--)for(let r=i-1;r>=0;r--)o[n][r]=e[n]===t[r]?o[n+1][r+1]+1:Math.max(o[n+1][r],o[n][r+1]);const n=[];let s=0,a=0;for(;s<r&&a<i;)e[s]===t[a]?(n.push({type:"equal",a:s,b:a}),s++,a++):o[s+1][a]>=o[s][a+1]?(n.push({type:"delete",a:s}),s++):(n.push({type:"insert",b:a}),a++);for(;s<r;)n.push({type:"delete",a:s++});for(;a<i;)n.push({type:"insert",b:a++});return n}function formatUnifiedDiff(e,t,r,{label:i,context:o}){const n=e.length,s=new Array(n).fill(!1);for(let t=0;t<n;t++)if("equal"!==e[t].type){s[t]=!0;for(let e=1;e<=o;e++)t-e>=0&&(s[t-e]=!0),t+e<n&&(s[t+e]=!0)}const a=[];let l=-1;for(let e=0;e<=n;e++)e<n&&s[e]?-1===l&&(l=e):-1!==l&&(a.push([l,e-1]),l=-1);if(!a.length)return`--- ${i}\n+++ ${i}\n(no changes)`;const c=[`--- ${i}`,`+++ ${i}`];for(const[i,o]of a){let n=1,s=1;for(let t=0;t<i;t++)"insert"!==e[t].type&&n++,"delete"!==e[t].type&&s++;let a=0,l=0;const d=[];for(let n=i;n<=o;n++){const i=e[n];"equal"===i.type?(d.push(` ${t[i.a]}`),a++,l++):"delete"===i.type?(d.push(`-${t[i.a]}`),a++):(d.push(`+${r[i.b]}`),l++)}c.push(`@@ -${n},${a} +${s},${l} @@`),c.push(...d)}return c.join("\n")}function unifiedDiff(e,t,{label:r="file",context:i=3}={}){const o=null==e?[]:String(e).split("\n"),n=null==t?[]:String(t).split("\n");return o.length>DIFF_MAX_LINES||n.length>DIFF_MAX_LINES||o.length*n.length>DIFF_MAX_CELLS?`--- ${r}\n+++ ${r}\n@@ file too large to preview — approx +${Math.max(0,n.length-o.length)}/-${Math.max(0,o.length-n.length)} lines @@`:formatUnifiedDiff(diffLines(o,n),o,n,{label:r,context:i})}function previewWriteFile({file_path:e,content:t}={}){if(!e)return{ok:!1,error:"file_path is required"};const r=readForPreview(e);if(!r.ok)return{ok:!1,error:r.error};const i=r.exists?r.content:null,o=String(null==t?"":t);return{ok:!0,before:i,after:o,diff:unifiedDiff(i,o,{label:e}),hash:null==i?null:sha256(i)}}function editPairList({edits:e,old_string:t,new_string:r,replace_all:i}={}){if(null==e)return{ok:!0,edits:[{old_string:t,new_string:r,replace_all:i}]};if(!Array.isArray(e)||!e.length)return{ok:!1,error:"edits must be a non-empty array of {old_string, new_string, replace_all?}"};const o=[];for(let t=0;t<e.length;t++){const r=e[t];if(!r||"object"!=typeof r)return{ok:!1,error:`edits[${t}] must be an object`};if("string"!=typeof r.old_string||""===r.old_string)return{ok:!1,error:`edits[${t}].old_string is required and must be non-empty`};o.push({old_string:r.old_string,new_string:r.new_string,replace_all:r.replace_all})}return{ok:!0,edits:o}}function previewEditFile({file_path:e,old_string:t,new_string:r,replace_all:i,edits:o}={}){if(!e)return{ok:!1,error:"file_path is required"};const n=editPairList({edits:o,old_string:t,new_string:r,replace_all:i});if(!n.ok)return{ok:!1,error:n.error};if(!o&&(void 0===t||""===t))return{ok:!1,error:"old_string is required and must be non-empty"};const s=readForPreview(e);if(!s.ok)return{ok:!1,error:s.error};if(!s.exists)return{ok:!1,error:`${e} does not exist`};const a=s.content;let l=a,c=0;for(let t=0;t<n.edits.length;t++){const r=n.edits[t],i=l.split(r.old_string).length-1,o=n.edits.length>1?`edits[${t}]: `:"";if(0===i)return{ok:!1,error:`${o}old_string not found in ${e}`};if(i>1&&!r.replace_all)return{ok:!1,error:`${o}old_string is not unique (${i} matches) — use replace_all or more context`};l=r.replace_all?l.split(r.old_string).join(null==r.new_string?"":r.new_string):l.replace(r.old_string,null==r.new_string?"":r.new_string),c+=i}return{ok:!0,before:a,after:l,diff:unifiedDiff(a,l,{label:e}),hash:sha256(a),count:c}}function previewMutation(e,t,r={}){const i=normalizeArgs(e,t,r);return i.ok?"writeFile"===e?previewWriteFile(i.args):"editFile"===e?previewEditFile(i.args):{ok:!1,error:`no diff preview for ${e}`}:{ok:!1,error:i.error}}function applyWriteChecked({file_path:e,content:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale write. Re-run writeFile to get an updated diff.`):(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyEditChecked({file_path:e,after:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale edit. Re-run editFile to get an updated diff.`):(fs.writeFileSync(e,t,"utf8"),ok(`Edited ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyChecked(e,t,r,i={}){const o=normalizeArgs(e,t,i);return o.ok?"writeFile"===e?applyWriteChecked(o.args,r.hash):applyEditChecked({file_path:o.args.file_path,after:r.after},r.hash):fail(o.error)}const IGNORED_DIRS=new Set(["node_modules",".git","dist",".aegiscode"]);function listDir({path:e}={},t={}){try{const r=e||baseDir(t),i=fs.readdirSync(r,{withFileTypes:!0}).filter((e=>!IGNORED_DIRS.has(e.name))).map((e=>e.isDirectory()?`${e.name}/`:e.name)).sort(((e,t)=>e.localeCompare(t)));return ok(i.join("\n")||"(empty directory)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function globToRegex(e){let t="^";for(let r=0;r<e.length;r++){const i=e[r];"*"===i?"*"===e[r+1]?(t+=".*",r++):t+="[^/]*":"?"===i?t+="[^/]":/[.+^${}()|[\]\\]/.test(i)?t+=`\\${i}`:t+=i}return new RegExp(t+"$")}function walk(e,t,r=0){if(r>12)return;let i;try{i=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const o of i){if(IGNORED_DIRS.has(o.name))continue;const i=path.join(e,o.name);o.isDirectory()?walk(i,t,r+1):t(i)}}function glob({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=t||baseDir(r),o=globToRegex(String(e)),n=[];return walk(i,(e=>{if(n.length>=100)return;const t=path.relative(i,e).split(path.sep).join("/");o.test(t)&&n.push(t)})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function grep({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=new RegExp(e),o=t||baseDir(r),n=[];return walk(o,(e=>{if(n.length>=100)return;let t;try{if(fs.statSync(e).size>10485760)return;t=fs.readFileSync(e,"utf8")}catch{return}const r=path.relative(o,e).split(path.sep).join("/");for(const[e,o]of t.split("\n").entries()){if(n.length>=100)return;i.test(o)&&n.push(`${r}:${e+1}: ${o.slice(0,160)}`)}})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i}={}){return new Promise((o=>{const n=Math.min(Number(i)||EXEC_MAX_BUFFER,EXEC_MAX_BUFFER),s=Math.min(Number(r)||EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP),a=shells.oneShotShellSpec();if(!a.ok)return void o(fail(a.error));const{cmd:l,arg:c}=a;let d;try{d=spawn(l,[c,e],{cwd:t||process.cwd(),timeout:s,killSignal:"SIGKILL",windowsHide:!0})}catch(e){return void o(fail(`spawn failed: ${e&&e.message?e.message:e}`))}let u="",p=0,h=!1,f=!1,g=!1;const m=setTimeout((()=>{f=!0;try{d.kill("SIGKILL")}catch{}}),s),_=e=>{if(p+=e.length,p>n){h=!0;try{d.kill("SIGKILL")}catch{}}else u+=e};d.stdout&&d.stdout.on("data",_),d.stderr&&d.stderr.on("data",_);const y=e=>{g||(g=!0,clearTimeout(m),o(e))};d.on("error",(e=>y(fail(`spawn failed: ${e&&e.message?e.message:e}`)))),d.on("close",((e,t)=>{const r=u.trim();if(f)return void y(fail(`command timed out after ${s}ms${r?`\n${r}`:""}`));if(h)return void y(fail(`output exceeded ${n} bytes and was truncated\n${r}`));const i=`exit ${null==e?`signal ${t}`:e}`;y(0===e?ok(r||`(${i}, no output)`):fail(`${i}${r?`\n${r}`:""}`))}))}))}function execInShell(e,{command:t,cwd:r,timeout:i},o){return o&&o.aborted?(e.dispose(),Promise.resolve(fail("aborted"))):new Promise((n=>{const s=()=>e.dispose();o&&o.addEventListener("abort",s,{once:!0});const a=()=>{o&&o.removeEventListener("abort",s)};e.run(t,{timeout:i,working_directory:r}).then((e=>{a(),n(e.isError?fail(e.content):ok(e.content))}),(e=>{a(),n(fail(`shell session failed: ${e&&e.message?e.message:e}`))}))}))}function exec({command:e,cwd:t,timeout:r,maxBuffer:i}={},o={}){if(!e||"string"!=typeof e)return Promise.resolve(fail("command is required"));if(o.oneShotExec)return execOneShot({command:e,cwd:t||o.cwd,timeout:r,maxBuffer:i});const n="function"==typeof o.getShell?o.getShell():null;return n?execInShell(n,{command:e,cwd:t,timeout:r},o.signal):execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i})}let hooksLib=null;try{hooksLib=require("../../../client/hooks.js")}catch{try{hooksLib=require("../../vendor/hooks.js")}catch{hooksLib=null}}const HOOKS_LIB_MISSING="the shared hook module could not be loaded (tried client/hooks.js beside the app and vendor/hooks.js inside it) — run scripts/predist.mjs before packaging.";function hooksListing(e){const t=[],r=e&&e.hooks?e.hooks:{};for(const[e,i]of Object.entries(r)){t.push(`${e} (${i.length})`);for(const e of i){if(!e)continue;t.push(` - ${e.name||"(unnamed)"}`);const r=e.matcher;r&&r.tools&&t.push(` tools: ${r.tools}`),r&&r.paths&&t.push(` paths: ${r.paths}`),r&&r.commands&&t.push(` commands: ${r.commands}`)}}return t.length?t.join("\n"):"(no hooks declared in any settings file)"}function hooks({sub:e,cwd:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);try{const r={cwd:t||process.cwd()},i=hooksLib.readHookConfig(r);if("list"===String(e||"status").toLowerCase())return ok(hooksListing(i));const o=hooksLib.hookStats(i.hooks);return ok(hooksLib.hooksSummary({...r,config:i,stats:o}))}catch(e){return fail(e&&e.message?e.message:String(e))}}function installHooks({cwd:e,dry_run:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);let r;try{r=hooksLib.installRepoHooks({cwd:e||process.cwd(),dryRun:Boolean(t)})}catch(e){return fail(e&&e.message?e.message:String(e))}const i=r.actions.length?`\n ${r.actions.join("\n ")}`:"";return r.ok?t?ok(`would install the guard hooks in ${r.status.repo}${i||"\n (already installed — nothing to do)"}`+(r.status.installed?"":"\n re-run without dry_run to apply")):r.changed?ok(`guard hooks installed in ${r.status.repo}\n core.hooksPath = .githooks (verified by reading it back)${i}\n ${r.status.execNote}\n a commit and a push in this tree are now gated.`):ok(`guard hooks already installed in ${r.status.repo}: core.hooksPath = .githooks\n ${r.status.execNote}`):fail(`${r.error}${i}`)}const EXECUTORS={readFile:readFile,writeFile:writeFile,editFile:editFile,listDir:listDir,glob:glob,grep:grep,exec:exec,hooks:hooks,installHooks:installHooks};function isTool(e){return Object.prototype.hasOwnProperty.call(EXECUTORS,e)}let agentGatePromise;function agentGateCandidates({resourcesPath:e=process.resourcesPath,dirname:t=__dirname}={}){const r=["../../../tools/agent-gate.mjs"];return"string"==typeof e&&e&&r.push(pathToFileURL(path.join(e,"tools","agent-gate.mjs")).href),r.push("../../vendor/agent-gate.mjs"),r}function loadAgentGate(){if(!agentGatePromise){const e=agentGateCandidates(),t=r=>r>=e.length?null:import(e[r]).catch((()=>t(r+1)));agentGatePromise=t(0)}return agentGatePromise}function nearestManifest(e){let t=path.resolve(e||process.cwd());try{fs.statSync(t).isFile()&&(t=path.dirname(t))}catch{}for(;;){const e=path.join(t,".aegis","guard.json");if(fs.existsSync(e))return e;const r=path.dirname(t);if(r===t)return null;t=r}}async function executeTool(e,t,r){if(integrity.armed())return fail("exec: unavailable in this build");if(!isTool(e))return fail(`unknown tool "${e}" (known: ${toolNames().join(", ")})`);const i=normalizeArgs(e,t,r||{});if(!i.ok)return fail(i.error);const o=i.args;let n=null;try{n=await loadAgentGate()}catch{}if(n){const t=n.guardTool({tool:e,args:o,cwd:r&&r.cwd||process.cwd(),env:process.env,unattended:Boolean(r&&r.autonomous)});if(!t.allowed)return fail(n.refusalText(t));if("skipped"===t.code){const i=await EXECUTORS[e](o,r||{});return i&&"object"==typeof i?{...i,output:`⚠ ${t.reason}\n${i.output||""}`}:i}}else if(MUTATING_TOOLS.has(e)){const t=nearestManifest(r&&r.cwd||process.cwd());if(t)return fail(`error: refused — ${t} declares an agent-gated tree, but the agent-key gate module could not be loaded (tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this ${e} cannot be authorised. A build that missed the staged copy is the usual cause: run scripts/predist.mjs before packaging.`)}try{return await EXECUTORS[e](o,r||{})}catch(e){return fail(e&&e.message?e.message:String(e))}}function toolResultText(e){return e?e.ok?String(null==e.output?"":e.output):`error: ${e.error}`:"error: tool produced no result"}module.exports={SCHEMAS:SCHEMAS,SUBAGENT_TOOL:SUBAGENT_TOOL,HOOK_TOOLS:HOOK_TOOLS,toolNames:toolNames,openaiTools:openaiTools,toolsFor:toolsFor,executeTool:executeTool,isTool:isTool,toolResultText:toolResultText,MUTATING_TOOLS:MUTATING_TOOLS,previewMutation:previewMutation,applyChecked:applyChecked,normalizeArgs:normalizeArgs,TOOL_PATH_ARGS:TOOL_PATH_ARGS,PATH_ARG_DESC:PATH_ARG_DESC,OUTPUT_CAP:3e4,READ_LINE_CAP:2e3,MATCH_CAP:100,READ_SIZE_CAP:26214400,GREP_SIZE_CAP:10485760,EXEC_TIMEOUT_DEFAULT:EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP:EXEC_TIMEOUT_CAP,EXEC_MAX_BUFFER:EXEC_MAX_BUFFER,DIFF_MAX_CELLS:DIFF_MAX_CELLS,DIFF_MAX_LINES:DIFF_MAX_LINES};
|
|
3
|
+
"use strict";const{spawn:spawn}=require("node:child_process"),crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{pathToFileURL:pathToFileURL}=require("node:url"),{agentRoles:agentRoles}=require("./agents.js");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`tools.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const OUTPUT_CAP=3e4,PATH_ARG_DESC='Absolute path on THIS machine; "~"/"~/…" = home. Relative resolves against the working directory.',pathDesc=e=>`${e}. ${PATH_ARG_DESC}`,shells=require("./shell.js"),sandbox=require("./sandbox.js"),integrity=require("./integrity.js"),READ_LINE_CAP=2e3,MATCH_CAP=100,READ_SIZE_CAP=26214400,GREP_SIZE_CAP=10485760,EXEC_TIMEOUT_DEFAULT=12e4,EXEC_TIMEOUT_CAP=6e5,EXEC_MAX_BUFFER=1048576,DIFF_MAX_CELLS=4e6,DIFF_MAX_LINES=2e4,spill=require("./spill.js");function cap(e){return spill.cap(e,3e4)}const ok=e=>({ok:!0,output:cap(e)}),fail=e=>({ok:!1,error:cap(e)}),SCHEMAS={readFile:{name:"readFile",description:"Read a file. Returns line-numbered content.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to read")},offset:{type:"number",description:"Start line (0-based)"},limit:{type:"number",description:"The number of lines to read (max 10000, default 2000)"}},required:["file_path"],additionalProperties:!1}},writeFile:{name:"writeFile",description:"Write a whole file, overwriting it. Parent dirs are created. Use editFile to change part of one.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to write")},content:{type:"string",description:"Full file contents"}},required:["file_path","content"],additionalProperties:!1}},editFile:{name:"editFile",description:"Exact string replacement. old_string must be unique unless replace_all. Fails loudly on a missing or ambiguous match rather than guessing. Pass `edits` to apply several hunks to one file in ONE call — they are applied in order, each against the result of the last, which is cheaper than one call per hunk.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to edit")},old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"},edits:{type:"array",description:"Several hunks for this one file, applied in order. Use instead of old_string/new_string.",items:{type:"object",properties:{old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"}},required:["old_string","new_string"],additionalProperties:!1}}},required:["file_path"],additionalProperties:!1}},listDir:{name:"listDir",description:"List one directory (non-recursive). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{path:{type:"string",description:pathDesc("The directory to list (default: the working directory)")}},required:[],additionalProperties:!1}},glob:{name:"glob",description:"Find files by glob (**, *, ?). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob, e.g. "**/*.test.js"'},path:{type:"string",description:pathDesc("Search root (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},grep:{name:"grep",description:"Search file contents by regex. Returns file:line matches. Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression to search for"},path:{type:"string",description:pathDesc("The directory to search in (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},exec:{name:"exec",description:"Run a shell command in a PERSISTENT session: cd and exported env carry across calls in this turn. Returns stdout+stderr and the exit code. Use for git, packages, system ops.",parameters:{type:"object",properties:{command:{type:"string",description:"Command to run"},cwd:{type:"string",description:pathDesc("Run this one command elsewhere; session cwd unchanged")},timeout:{type:"number",description:`Timeout in milliseconds (max ${EXEC_TIMEOUT_CAP}, default ${EXEC_TIMEOUT_DEFAULT})`},description:{type:"string",description:"A brief description of what the command does (for display)"}},required:["command"],additionalProperties:!1}},hooks:{name:"hooks",description:"Hook status for this machine, from the same shared implementation the CLI's /hooks uses: the merged settings.json hook config (~/.aegis, ./.aegis, ~/.aegiscode, ./.aegiscode, ~/.claude) and whether this repo's .githooks/ guard hooks are actually installed (core.hooksPath). Read-only. Use installHooks to install them.",parameters:{type:"object",properties:{sub:{type:"string",enum:["status","list"],description:"status (default) or the full config listing"},cwd:{type:"string",description:pathDesc("Repo to inspect (default: the working directory)")}},required:[],additionalProperties:!1}},installHooks:{name:"installHooks",description:"Install this repo's guard hooks: point git's core.hooksPath at .githooks/ (the agent-key gate, the secret scan, the invariant lock) and make them executable. Idempotent, and verified by reading the config back. Pass dry_run to see the exact commands without running them. Without this, a fresh clone runs NO guard hooks.",parameters:{type:"object",properties:{cwd:{type:"string",description:pathDesc("Repo to install into (default: the working directory)")},dry_run:{type:"boolean",description:"Print the commands instead of running them"}},required:[],additionalProperties:!1}},task:{name:"task",description:"Delegate a focused multi-step sub-task to a subagent with its own tool loop; it returns a final report. Give it a complete, self-contained prompt — it cannot ask follow-ups.",parameters:{type:"object",properties:{description:{type:"string",description:"Short label (3-5 words)"},subagent_type:{type:"string",enum:[...agentRoles(),"general"],description:"Which specialist preset to spawn (general = a capable all-purpose agent)"},prompt:{type:"string",description:"The full, self-contained task instructions for the subagent"}},required:["description","prompt"],additionalProperties:!1}}},SUBAGENT_TOOL="task",HOOK_TOOLS=new Set(["hooks","installHooks"]);function toolNames({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>e.name))}function schemaList({includeSubagent:e=!0,includeHooks:t=!1}={}){return Object.values(SCHEMAS).filter((r=>(e||r.name!==SUBAGENT_TOOL)&&(t||!HOOK_TOOLS.has(r.name))))}function openaiTools({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}})))}function toolsFor({includeSubagent:e=!0,includeHooks:t=!1}={}){return openaiTools({includeSubagent:e,includeHooks:t})}const TOOL_PATH_ARGS=Object.freeze({readFile:["file_path"],writeFile:["file_path"],editFile:["file_path"],listDir:["path"],glob:["path"],grep:["path"],exec:["cwd"],hooks:["cwd"],installHooks:["cwd"]});function normalizeArgs(e,t,r={}){const i=t&&"object"==typeof t?t:{},o=TOOL_PATH_ARGS[e];if(!o)return{ok:!0,args:i,error:null};let n=i;for(const t of o){const o=i[t];if("string"!=typeof o||!o.trim())continue;const s=platform.resolvePath(o,{platform:r&&r.platform?r.platform:void 0,cwd:r&&r.cwd?r.cwd:void 0,desktopdir:r&&r.desktopdir?r.desktopdir:void 0});if(!s.ok)return{ok:!1,args:i,error:`${e}: ${t} — ${s.error}`};s.path!==o&&(n===i&&(n={...i}),n[t]=s.path)}return{ok:!0,args:n,error:null}}function baseDir(e){return e&&"string"==typeof e.cwd&&e.cwd||process.cwd()}function readFile({file_path:e,offset:t=0,limit:r}={}){try{if(!e)return fail("file_path is required");const i=fs.statSync(e);if(i.isDirectory())return fail(`${e} is a directory (use listDir)`);if(i.size>26214400){const t=(i.size/1048576).toFixed(1);return fail(`${e} is ${t} MB — too large to read (limit 25 MB). Use exec with grep/head to inspect it instead.`)}const o=fs.readFileSync(e,"utf8").split("\n"),n=Math.max(0,Number(t)||0),s=Math.max(1,Math.min(Number(r)||2e3,1e4)),a=o.slice(n,n+s),l=a.map(((e,t)=>`${t+n+1}| ${e}`)).join("\n"),c=n+a.length<o.length?`\n… (${o.length-n-a.length} more lines)`:"";return ok(l+c)}catch(e){return fail(e&&e.message?e.message:String(e))}}function writeFile({file_path:e,content:t}={}){try{return e?(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail("file_path is required")}catch(e){return fail(e&&e.message?e.message:String(e))}}function editFile(e={}){try{const t=previewEditFile(e);if(!t.ok)return fail(t.error);fs.writeFileSync(e.file_path,t.after,"utf8");const r=Array.isArray(e.edits)?e.edits.length:1,i=r>1?`${r} hunks, ${t.count} occurrence${t.count>1?"s":""} replaced`:`${t.count} occurrence${t.count>1?"s":""} replaced`;return ok(`Edited ${e.file_path} (${i})`)}catch(e){return fail(e&&e.message?e.message:String(e))}}const MUTATING_TOOLS=new Set(["exec","writeFile","editFile","installHooks"]);function sha256(e){return crypto.createHash("sha256").update(null==e?"":e,"utf8").digest("hex")}function readForPreview(e){try{return fs.existsSync(e)?fs.statSync(e).isDirectory()?{ok:!1,error:`${e} is a directory`}:{ok:!0,exists:!0,content:fs.readFileSync(e,"utf8")}:{ok:!0,exists:!1,content:null}}catch(e){return{ok:!1,error:e&&e.message?e.message:String(e)}}}function diffLines(e,t){const r=e.length,i=t.length,o=new Array(r+1);for(let e=0;e<=r;e++)o[e]=new Int32Array(i+1);for(let n=r-1;n>=0;n--)for(let r=i-1;r>=0;r--)o[n][r]=e[n]===t[r]?o[n+1][r+1]+1:Math.max(o[n+1][r],o[n][r+1]);const n=[];let s=0,a=0;for(;s<r&&a<i;)e[s]===t[a]?(n.push({type:"equal",a:s,b:a}),s++,a++):o[s+1][a]>=o[s][a+1]?(n.push({type:"delete",a:s}),s++):(n.push({type:"insert",b:a}),a++);for(;s<r;)n.push({type:"delete",a:s++});for(;a<i;)n.push({type:"insert",b:a++});return n}function formatUnifiedDiff(e,t,r,{label:i,context:o}){const n=e.length,s=new Array(n).fill(!1);for(let t=0;t<n;t++)if("equal"!==e[t].type){s[t]=!0;for(let e=1;e<=o;e++)t-e>=0&&(s[t-e]=!0),t+e<n&&(s[t+e]=!0)}const a=[];let l=-1;for(let e=0;e<=n;e++)e<n&&s[e]?-1===l&&(l=e):-1!==l&&(a.push([l,e-1]),l=-1);if(!a.length)return`--- ${i}\n+++ ${i}\n(no changes)`;const c=[`--- ${i}`,`+++ ${i}`];for(const[i,o]of a){let n=1,s=1;for(let t=0;t<i;t++)"insert"!==e[t].type&&n++,"delete"!==e[t].type&&s++;let a=0,l=0;const d=[];for(let n=i;n<=o;n++){const i=e[n];"equal"===i.type?(d.push(` ${t[i.a]}`),a++,l++):"delete"===i.type?(d.push(`-${t[i.a]}`),a++):(d.push(`+${r[i.b]}`),l++)}c.push(`@@ -${n},${a} +${s},${l} @@`),c.push(...d)}return c.join("\n")}function unifiedDiff(e,t,{label:r="file",context:i=3}={}){const o=null==e?[]:String(e).split("\n"),n=null==t?[]:String(t).split("\n");return o.length>DIFF_MAX_LINES||n.length>DIFF_MAX_LINES||o.length*n.length>DIFF_MAX_CELLS?`--- ${r}\n+++ ${r}\n@@ file too large to preview — approx +${Math.max(0,n.length-o.length)}/-${Math.max(0,o.length-n.length)} lines @@`:formatUnifiedDiff(diffLines(o,n),o,n,{label:r,context:i})}function previewWriteFile({file_path:e,content:t}={}){if(!e)return{ok:!1,error:"file_path is required"};const r=readForPreview(e);if(!r.ok)return{ok:!1,error:r.error};const i=r.exists?r.content:null,o=String(null==t?"":t);return{ok:!0,before:i,after:o,diff:unifiedDiff(i,o,{label:e}),hash:null==i?null:sha256(i)}}function editPairList({edits:e,old_string:t,new_string:r,replace_all:i}={}){if(null==e)return{ok:!0,edits:[{old_string:t,new_string:r,replace_all:i}]};if(!Array.isArray(e)||!e.length)return{ok:!1,error:"edits must be a non-empty array of {old_string, new_string, replace_all?}"};const o=[];for(let t=0;t<e.length;t++){const r=e[t];if(!r||"object"!=typeof r)return{ok:!1,error:`edits[${t}] must be an object`};if("string"!=typeof r.old_string||""===r.old_string)return{ok:!1,error:`edits[${t}].old_string is required and must be non-empty`};o.push({old_string:r.old_string,new_string:r.new_string,replace_all:r.replace_all})}return{ok:!0,edits:o}}function previewEditFile({file_path:e,old_string:t,new_string:r,replace_all:i,edits:o}={}){if(!e)return{ok:!1,error:"file_path is required"};const n=editPairList({edits:o,old_string:t,new_string:r,replace_all:i});if(!n.ok)return{ok:!1,error:n.error};if(!o&&(void 0===t||""===t))return{ok:!1,error:"old_string is required and must be non-empty"};const s=readForPreview(e);if(!s.ok)return{ok:!1,error:s.error};if(!s.exists)return{ok:!1,error:`${e} does not exist`};const a=s.content;let l=a,c=0;for(let t=0;t<n.edits.length;t++){const r=n.edits[t],i=l.split(r.old_string).length-1,o=n.edits.length>1?`edits[${t}]: `:"";if(0===i)return{ok:!1,error:`${o}old_string not found in ${e}`};if(i>1&&!r.replace_all)return{ok:!1,error:`${o}old_string is not unique (${i} matches) — use replace_all or more context`};l=r.replace_all?l.split(r.old_string).join(null==r.new_string?"":r.new_string):l.replace(r.old_string,null==r.new_string?"":r.new_string),c+=i}return{ok:!0,before:a,after:l,diff:unifiedDiff(a,l,{label:e}),hash:sha256(a),count:c}}function previewMutation(e,t,r={}){const i=normalizeArgs(e,t,r);return i.ok?"writeFile"===e?previewWriteFile(i.args):"editFile"===e?previewEditFile(i.args):{ok:!1,error:`no diff preview for ${e}`}:{ok:!1,error:i.error}}function applyWriteChecked({file_path:e,content:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale write. Re-run writeFile to get an updated diff.`):(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyEditChecked({file_path:e,after:t}={},r){try{if(!e)return fail("file_path is required");const i=readForPreview(e);return i.ok?(i.exists?sha256(i.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale edit. Re-run editFile to get an updated diff.`):(fs.writeFileSync(e,t,"utf8"),ok(`Edited ${e}`)):fail(i.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyChecked(e,t,r,i={}){const o=normalizeArgs(e,t,i);return o.ok?"writeFile"===e?applyWriteChecked(o.args,r.hash):applyEditChecked({file_path:o.args.file_path,after:r.after},r.hash):fail(o.error)}const IGNORED_DIRS=new Set(["node_modules",".git","dist",".aegiscode"]);function listDir({path:e}={},t={}){try{const r=e||baseDir(t),i=fs.readdirSync(r,{withFileTypes:!0}).filter((e=>!IGNORED_DIRS.has(e.name))).map((e=>e.isDirectory()?`${e.name}/`:e.name)).sort(((e,t)=>e.localeCompare(t)));return ok(i.join("\n")||"(empty directory)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function globToRegex(e){let t="^";for(let r=0;r<e.length;r++){const i=e[r];"*"===i?"*"===e[r+1]?(t+=".*",r++):t+="[^/]*":"?"===i?t+="[^/]":/[.+^${}()|[\]\\]/.test(i)?t+=`\\${i}`:t+=i}return new RegExp(t+"$")}function walk(e,t,r=0){if(r>12)return;let i;try{i=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const o of i){if(IGNORED_DIRS.has(o.name))continue;const i=path.join(e,o.name);o.isDirectory()?walk(i,t,r+1):t(i)}}function glob({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=t||baseDir(r),o=globToRegex(String(e)),n=[];return walk(i,(e=>{if(n.length>=100)return;const t=path.relative(i,e).split(path.sep).join("/");o.test(t)&&n.push(t)})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function grep({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const i=new RegExp(e),o=t||baseDir(r),n=[];return walk(o,(e=>{if(n.length>=100)return;let t;try{if(fs.statSync(e).size>10485760)return;t=fs.readFileSync(e,"utf8")}catch{return}const r=path.relative(o,e).split(path.sep).join("/");for(const[e,o]of t.split("\n").entries()){if(n.length>=100)return;i.test(o)&&n.push(`${r}:${e+1}: ${o.slice(0,160)}`)}})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i,sandboxCfg:o}={}){return new Promise((n=>{const s=Math.min(Number(i)||EXEC_MAX_BUFFER,EXEC_MAX_BUFFER),a=Math.min(Number(r)||EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP),l=shells.oneShotShellSpec();if(!l.ok)return void n(fail(l.error));const{cmd:c,arg:d}=l,u=sandbox.spawnPlan(o,c,[d,e],{cwd:t||process.cwd()});if(!u.ok)return void n(fail(`sandbox: ${u.reason}`));const p=u.degraded?`[sandbox_unavailable] ran UNCONFINED: ${u.degraded}\n`:"";let f;try{f=spawn(u.file,u.args,{cwd:t||process.cwd(),timeout:a,killSignal:"SIGKILL",windowsHide:!0})}catch(e){return void n(fail(`spawn failed: ${e&&e.message?e.message:e}`))}let h="",g=0,m=!1,_=!1,y=!1;const k=setTimeout((()=>{_=!0;try{f.kill("SIGKILL")}catch{}}),a),w=e=>{if(g+=e.length,g>s){m=!0;try{f.kill("SIGKILL")}catch{}}else h+=e};f.stdout&&f.stdout.on("data",w),f.stderr&&f.stderr.on("data",w);const S=e=>{y||(y=!0,clearTimeout(k),n(p?e.ok?ok(`${p}${e.output}`):fail(`${p}${e.error}`):e))};f.on("error",(e=>S(fail(`spawn failed: ${e&&e.message?e.message:e}`)))),f.on("close",((e,t)=>{const r=h.trim();if(_)return void S(fail(`command timed out after ${a}ms${r?`\n${r}`:""}`));if(m)return void S(fail(`output exceeded ${s} bytes and was truncated\n${r}`));const i=`exit ${null==e?`signal ${t}`:e}`;S(0===e?ok(r||`(${i}, no output)`):fail(`${i}${r?`\n${r}`:""}`))}))}))}function execInShell(e,{command:t,cwd:r,timeout:i},o){return o&&o.aborted?(e.dispose(),Promise.resolve(fail("aborted"))):new Promise((n=>{const s=()=>e.dispose();o&&o.addEventListener("abort",s,{once:!0});const a=()=>{o&&o.removeEventListener("abort",s)};e.run(t,{timeout:i,working_directory:r}).then((e=>{a(),n(e.isError?fail(e.content):ok(e.content))}),(e=>{a(),n(fail(`shell session failed: ${e&&e.message?e.message:e}`))}))}))}function exec({command:e,cwd:t,timeout:r,maxBuffer:i}={},o={}){if(!e||"string"!=typeof e)return Promise.resolve(fail("command is required"));if(o.oneShotExec)return execOneShot({command:e,cwd:t||o.cwd,timeout:r,maxBuffer:i,sandboxCfg:o.sandbox});const n="function"==typeof o.getShell?o.getShell():null;return n?execInShell(n,{command:e,cwd:t,timeout:r},o.signal):execOneShot({command:e,cwd:t,timeout:r,maxBuffer:i,sandboxCfg:o.sandbox})}let hooksLib=null;try{hooksLib=require("../../../client/hooks.js")}catch{try{hooksLib=require("../../vendor/hooks.js")}catch{hooksLib=null}}const HOOKS_LIB_MISSING="the shared hook module could not be loaded (tried client/hooks.js beside the app and vendor/hooks.js inside it) — run scripts/predist.mjs before packaging.";function hooksListing(e){const t=[],r=e&&e.hooks?e.hooks:{};for(const[e,i]of Object.entries(r)){t.push(`${e} (${i.length})`);for(const e of i){if(!e)continue;t.push(` - ${e.name||"(unnamed)"}`);const r=e.matcher;r&&r.tools&&t.push(` tools: ${r.tools}`),r&&r.paths&&t.push(` paths: ${r.paths}`),r&&r.commands&&t.push(` commands: ${r.commands}`)}}return t.length?t.join("\n"):"(no hooks declared in any settings file)"}function hooks({sub:e,cwd:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);try{const r={cwd:t||process.cwd()},i=hooksLib.readHookConfig(r);if("list"===String(e||"status").toLowerCase())return ok(hooksListing(i));const o=hooksLib.hookStats(i.hooks);return ok(hooksLib.hooksSummary({...r,config:i,stats:o}))}catch(e){return fail(e&&e.message?e.message:String(e))}}function installHooks({cwd:e,dry_run:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);let r;try{r=hooksLib.installRepoHooks({cwd:e||process.cwd(),dryRun:Boolean(t)})}catch(e){return fail(e&&e.message?e.message:String(e))}const i=r.actions.length?`\n ${r.actions.join("\n ")}`:"";return r.ok?t?ok(`would install the guard hooks in ${r.status.repo}${i||"\n (already installed — nothing to do)"}`+(r.status.installed?"":"\n re-run without dry_run to apply")):r.changed?ok(`guard hooks installed in ${r.status.repo}\n core.hooksPath = .githooks (verified by reading it back)${i}\n ${r.status.execNote}\n a commit and a push in this tree are now gated.`):ok(`guard hooks already installed in ${r.status.repo}: core.hooksPath = .githooks\n ${r.status.execNote}`):fail(`${r.error}${i}`)}const EXECUTORS={readFile:readFile,writeFile:writeFile,editFile:editFile,listDir:listDir,glob:glob,grep:grep,exec:exec,hooks:hooks,installHooks:installHooks};function isTool(e){return Object.prototype.hasOwnProperty.call(EXECUTORS,e)}let agentGatePromise;function agentGateCandidates({resourcesPath:e=process.resourcesPath,dirname:t=__dirname}={}){const r=["../../../tools/agent-gate.mjs"];return"string"==typeof e&&e&&r.push(pathToFileURL(path.join(e,"tools","agent-gate.mjs")).href),r.push("../../vendor/agent-gate.mjs"),r}function loadAgentGate(){if(!agentGatePromise){const e=agentGateCandidates(),t=r=>r>=e.length?null:import(e[r]).catch((()=>t(r+1)));agentGatePromise=t(0)}return agentGatePromise}function nearestManifest(e){let t=path.resolve(e||process.cwd());try{fs.statSync(t).isFile()&&(t=path.dirname(t))}catch{}for(;;){const e=path.join(t,".aegis","guard.json");if(fs.existsSync(e))return e;const r=path.dirname(t);if(r===t)return null;t=r}}async function executeTool(e,t,r){if(integrity.armed())return fail("exec: unavailable in this build");if(!isTool(e))return fail(`unknown tool "${e}" (known: ${toolNames().join(", ")})`);const i=normalizeArgs(e,t,r||{});if(!i.ok)return fail(i.error);const o=i.args;let n=null;try{n=await loadAgentGate()}catch{}if(n){const t=n.guardTool({tool:e,args:o,cwd:r&&r.cwd||process.cwd(),env:process.env,unattended:Boolean(r&&r.autonomous)});if(!t.allowed)return fail(n.refusalText(t));if("skipped"===t.code){const i=await EXECUTORS[e](o,r||{});return i&&"object"==typeof i?{...i,output:`⚠ ${t.reason}\n${i.output||""}`}:i}}else if(MUTATING_TOOLS.has(e)){const t=nearestManifest(r&&r.cwd||process.cwd());if(t)return fail(`error: refused — ${t} declares an agent-gated tree, but the agent-key gate module could not be loaded (tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this ${e} cannot be authorised. A build that missed the staged copy is the usual cause: run scripts/predist.mjs before packaging.`)}try{return await EXECUTORS[e](o,r||{})}catch(e){return fail(e&&e.message?e.message:String(e))}}function toolResultText(e){return e?e.ok?String(null==e.output?"":e.output):`error: ${e.error}`:"error: tool produced no result"}module.exports={SCHEMAS:SCHEMAS,SUBAGENT_TOOL:SUBAGENT_TOOL,HOOK_TOOLS:HOOK_TOOLS,toolNames:toolNames,openaiTools:openaiTools,toolsFor:toolsFor,executeTool:executeTool,isTool:isTool,toolResultText:toolResultText,MUTATING_TOOLS:MUTATING_TOOLS,previewMutation:previewMutation,applyChecked:applyChecked,normalizeArgs:normalizeArgs,TOOL_PATH_ARGS:TOOL_PATH_ARGS,PATH_ARG_DESC:PATH_ARG_DESC,OUTPUT_CAP:3e4,READ_LINE_CAP:2e3,MATCH_CAP:100,READ_SIZE_CAP:26214400,GREP_SIZE_CAP:10485760,EXEC_TIMEOUT_DEFAULT:EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP:EXEC_TIMEOUT_CAP,EXEC_MAX_BUFFER:EXEC_MAX_BUFFER,DIFF_MAX_CELLS:DIFF_MAX_CELLS,DIFF_MAX_LINES:DIFF_MAX_LINES};
|
|
@@ -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"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const t=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!t)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${t}:(F)`],{stdio:"ignore"})}catch(t){console.error(`[settings] failed to restrict ACL on ${e}: ${t.message}`)}}else try{fs.chmodSync(e,384)}catch(t){console.error(`[settings] failed to chmod ${e} to 0600: ${t.message}`)}}function createSettingsStore({dir:e,safeStorage:t,prefsDir:n,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==n?"":String(n).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const t=a()[e];return void 0===t?null:t}const u=()=>Boolean(t&&"function"==typeof t.isEncryptionAvailable&&t.isEncryptionAvailable());function _(e){return null==e?null:u()?t.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function l(e){if(!e)return null;try{const n=Buffer.from(String(e),"base64");return u()?t.decryptString(n):n.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function A(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const t=`${o}.tmp-${process.pid}`;fs.writeFileSync(t,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(t,o),restrictFile(o)}function f(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const t=d()[e]||{},n=l(t.key);return{provider:e,baseURL:t.baseURL||"",configured:Boolean(n),keyMask:maskKey(n)}}function S(){const e=l((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(){const e=d().__quickLauncher||{},t="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:t}}function M(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function g(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const t=d().__confirmMode||{};return void 0===t.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(t.enabled),source:"config"}}function y(){return!0===(d().__telemetry||{}).enabled}function N(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const t=d().__memoryPersist||{};return void 0===t.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(t.enabled),source:"config"}}function p(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function v(){const e=d().__avatar||{};return{...p(),source:void 0===e.enabled?"default":"config"}}function b(e){const t=Number(e);if(!Number.isFinite(t))return 6e4;const n=Math.round(t);return n<15e3||n>18e5?6e4:n}function T(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:b(e.intervalMs)}}function R(){const e=d().__autoDrain||{};return{...T(),source:void 0===e.enabled?"default":"config"}}function C(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function h(){const e=d().__autoMint||{};return{...C(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,t){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:t},{dir:i}),c(e)},get:E,set:function(e,{baseURL:t,key:n}={}){f(e);let r=t;if("local"===e&&t){const e=localTransport.remoteRefusal(t);if(e)throw e;r=localTransport.normalizeBase(t)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==n&&(i.key=n?_(n):null),o[e]=i,A(o),E(e)},rawKey:function(e){return l((d()[e]||{}).key)},remove:function(e){f(e);const t=d();return delete t[e],A(t),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter((e=>!isReservedNamespace(e))).map((e=>E(e)))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return l((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const t=d();return t.__aegis={...t.__aegis||{},key:e?_(e):null,savedAt:e?(new Date).toISOString():null},A(t),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const t=e.aegis||{},n=e.__aegis||{},r={...e};return t.key&&!n.key&&(r.__aegis={...n,key:t.key}),delete r.aegis,A(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:m,setQuickLauncherConfig:function({enabled:e,shortcut:t}={}){const n=d();return n.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof t&&t.trim()?t.trim():"CmdOrCtrl+Shift+Space"},A(n),m()},vaultBackendConfig:M,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return M();const t=d();return t.__vaultBackend={backend:e},A(t),M()},getConfirmMode:function(){return g().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const t=d();return void 0!==t.__confirmMode&&(delete t.__confirmMode,A(t)),g().enabled},confirmModeState:g,getTelemetryOptIn:y,setTelemetryOptIn:function(e){const t=d();return t.__telemetry={enabled:Boolean(e)},A(t),y()},getMemoryPersist:function(){return N().enabled},memoryPersistState:N,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const t=d();return void 0!==t.__memoryPersist&&(delete t.__memoryPersist,A(t)),N()},getAvatar:p,avatarState:v,setAvatar:function(e={}){const t=p(),n=e&&"object"==typeof e?e:{},r={enabled:void 0===n.enabled?t.enabled:Boolean(n.enabled),showLevel:void 0===n.showLevel?t.showLevel:Boolean(n.showLevel),motion:AVATAR_MOTION_MODES.includes(n.motion)?n.motion:t.motion},o=d();return o.__avatar=r,A(o),v()},getAutoDrain:T,autoDrainState:R,setAutoDrain:function(e={}){const t=T(),n=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===n.enabled?t.enabled:Boolean(n.enabled),intervalMs:void 0===n.intervalMs?t.intervalMs:b(n.intervalMs)},A(r),R()},getAutoMint:C,autoMintState:h,setAutoMint:function(e={}){const t=C(),n=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===n.enabled?t.enabled:Boolean(n.enabled),publish:void 0===n.publish?t.publish:Boolean(n.publish)},A(r),h()},clampAutoDrainInterval:b}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const n=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!n)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${n}:(F)`],{stdio:"ignore"})}catch(n){console.error(`[settings] failed to restrict ACL on ${e}: ${n.message}`)}}else try{fs.chmodSync(e,384)}catch(n){console.error(`[settings] failed to chmod ${e} to 0600: ${n.message}`)}}function createSettingsStore({dir:e,safeStorage:n,prefsDir:t,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==t?"":String(t).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const n=a()[e];return void 0===n?null:n}const u=()=>Boolean(n&&"function"==typeof n.isEncryptionAvailable&&n.isEncryptionAvailable());function _(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function l(e){if(!e)return null;try{const t=Buffer.from(String(e),"base64");return u()?n.decryptString(t):t.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function f(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const n=`${o}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(n,o),restrictFile(o)}function A(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const n=d()[e]||{},t=l(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=l((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(){const e=d().__quickLauncher||{},n="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:n}}function M(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function p(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const n=d().__confirmMode||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function y(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function g(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function N(){return!0===(d().__telemetry||{}).enabled}function b(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const n=d().__memoryPersist||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function v(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function R(){const e=d().__avatar||{};return{...v(),source:void 0===e.enabled?"default":"config"}}function T(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function h(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:T(e.intervalMs)}}function C(){const e=d().__autoDrain||{};return{...h(),source:void 0===e.enabled?"default":"config"}}function I(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function L(){const e=d().__autoMint||{};return{...I(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,n){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:n},{dir:i}),c(e)},get:E,set:function(e,{baseURL:n,key:t}={}){A(e);let r=n;if("local"===e&&n){const e=localTransport.remoteRefusal(n);if(e)throw e;r=localTransport.normalizeBase(n)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==t&&(i.key=t?_(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return l((d()[e]||{}).key)},remove:function(e){A(e);const n=d();return delete n[e],f(n),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter((e=>!isReservedNamespace(e))).map((e=>E(e)))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return l((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?_(e):null,savedAt:e?(new Date).toISOString():null},f(n),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const n=e.aegis||{},t=e.__aegis||{},r={...e};return n.key&&!t.key&&(r.__aegis={...t,key:n.key}),delete r.aegis,f(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:m,setQuickLauncherConfig:function({enabled:e,shortcut:n}={}){const t=d();return t.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof n&&n.trim()?n.trim():"CmdOrCtrl+Shift+Space"},f(t),m()},vaultBackendConfig:M,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return M();const n=d();return n.__vaultBackend={backend:e},f(n),M()},getConfirmMode:function(){return p().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),p().enabled},confirmModeState:p,getPermissionMode:g,setPermissionMode:function(e){if(null==e||""===e||"off"===e||"none"===e)return prefs.remove("permissionMode",{dir:i}),null;const n=String(e),t=function(){const e=[path.join(__dirname,"..","..","one","src","permissions.js"),path.join(__dirname,"..","vendor","one","src","permissions.js")];for(const n of e)try{const e=require(n);if(e&&Array.isArray(e.PERMISSION_MODES)&&e.PERMISSION_MODES.length)return[...e.PERMISSION_MODES]}catch{}return["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]}();if(!t.includes(n))throw new Error(`"${n}" is not one of ${t.join("|")} (or 'off' to clear it)`);return prefs.set({permissionMode:n},{dir:i}),g()},getSandboxPolicy:y,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),y()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:N,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),N()},getMemoryPersist:function(){return b().enabled},memoryPersistState:b,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),b()},getAvatar:v,avatarState:R,setAvatar:function(e={}){const n=v(),t=e&&"object"==typeof e?e:{},r={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),showLevel:void 0===t.showLevel?n.showLevel:Boolean(t.showLevel),motion:AVATAR_MOTION_MODES.includes(t.motion)?t.motion:n.motion},o=d();return o.__avatar=r,f(o),R()},getAutoDrain:h,autoDrainState:C,setAutoDrain:function(e={}){const n=h(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),intervalMs:void 0===t.intervalMs?n.intervalMs:T(t.intervalMs)},f(r),C()},getAutoMint:I,autoMintState:L,setAutoMint:function(e={}){const n=I(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),publish:void 0===t.publish?n.publish:Boolean(t.publish)},f(r),L()},clampAutoDrainInterval:T}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
4
|
-
"use strict";const path=require("node:path"),fs=require("node:fs"),{execFile:execFile}=require("node:child_process"),{pathToFileURL:pathToFileURL}=require("node:url");let sharedClient;try{sharedClient=require("../client/aegis.js")}catch{sharedClient=require("./vendor/aegis.js")}const{createClient:createClient}=sharedClient;let credentials,autoProvision,sharedPresence,sharedTopup,googleSignIn,driveConnectLib,driveUploadLib,conversationExportLib;try{credentials=require("../client/credentials.js")}catch{credentials=require("./vendor/credentials.js")}try{autoProvision=require("../client/auto-provision.js")}catch{autoProvision=require("./vendor/auto-provision.js")}try{sharedPresence=require("../client/presence.js")}catch{sharedPresence=require("./vendor/presence.js")}try{sharedTopup=require("../client/topup.js")}catch{sharedTopup=require("./vendor/topup.js")}try{googleSignIn=require("../client/google-signin.js")}catch{googleSignIn=require("./vendor/google-signin.js")}try{driveConnectLib=require("../client/drive-connect.js")}catch{driveConnectLib=require("./vendor/drive-connect.js")}try{driveUploadLib=require("../client/drive-upload.js")}catch{driveUploadLib=require("./vendor/drive-upload.js")}try{conversationExportLib=require("../client/conversation-export.js")}catch{try{conversationExportLib=require("./vendor/conversation-export.js")}catch{conversationExportLib=null}}const{createGoogleConnect:createGoogleConnect}=require("./lib/google-connect.js");let sharedFingerprint;try{sharedFingerprint=require("../client/device-fingerprint.js")}catch{sharedFingerprint=require("./vendor/device-fingerprint.js")}const{createFingerprintService:createFingerprintService}=require("./lib/fingerprint.js"),{createAutoDrain:createAutoDrain,createAutoMint:createAutoMint}=require("./lib/auto.js");let envFile=null;try{envFile=require("../client/env-file.js")}catch{try{envFile=require("./vendor/env-file.js")}catch{}}let electron=null;try{electron=require("electron")}catch{}const os=require("node:os"),{createLocalEngine:createLocalEngine}=require("./lib/local/engine.js"),{createAccountKey:createAccountKey,startupKeyOverride:startupKeyOverride}=require("./lib/account-key.js"),{createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace}=require("./lib/settings.js"),sessionStore=require("./lib/sync/sessions.js"),memoryQueue=require("./lib/sync/memory-queue.js"),persistGate=require("./lib/sync/persist-gate.js"),avatarStore=require("./lib/avatar/store.js"),windowState=require("./lib/window-state.js"),deepLink=require("./lib/deep-link.js"),quickLauncherLib=require("./lib/quick-launcher.js");let foreignMemory;try{foreignMemory=require("../client/foreign-memory.js")}catch{foreignMemory=require("./vendor/foreign-memory.js")}const localTools=require("./lib/local/tools.js"),queueModule=require("./lib/local/queue.js"),autonomousModule=require("./lib/local/autonomous.js"),{autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault}=require("./lib/local/autonomous.js"),entitlementModule=require("./lib/local/entitlement.js"),telemetryModule=require("./lib/local/telemetry.js"),covenantModule=require("./lib/local/covenant.js"),{createTelemetry:createTelemetry,telemetryEnabled:telemetryEnabled}=telemetryModule,IPC_PREFIX="aegis:",MODEL_PREFIX="model:",SYNC_PREFIX="sync:",TOOLS_PREFIX="tools:",QUICK_PREFIX="quick:",QUEUE_PREFIX="queue:",AUTO_PREFIX="auto:",DESKTOP_CLASSES=Object.freeze(["aegis","byok","local"]),CHAT_DELTA_CHANNEL=`${IPC_PREFIX}chatDelta`,MENU_NEW_CHAT_CHANNEL=`${IPC_PREFIX}menuNewChat`,MENU_SEARCH_CHANNEL=`${IPC_PREFIX}menuSearch`,MENU_EXPORT_MARKDOWN_CHANNEL=`${IPC_PREFIX}menuExportMarkdown`,MENU_EXPORT_JSON_CHANNEL=`${IPC_PREFIX}menuExportJson`,MENU_FINGERPRINT_CHANNEL=`${IPC_PREFIX}menuFingerprint`,MENU_GOOGLE_DRIVE_CHANNEL=`${IPC_PREFIX}menuGoogleDrive`,DEEP_LINK_CHANNEL=`${IPC_PREFIX}deepLink`,QUICK_LAUNCHER_PUSH_CHANNEL=`${IPC_PREFIX}quickLauncherPush`,QUEUE_PROGRESS_CHANNEL=`${QUEUE_PREFIX}progress`,QUEUE_MAX_TASK_CHARS=8e3,QUEUE_MAX_ROUNDS=200,QUEUE_MAX_WORKERS=8,QUEUE_EFFORTS=new Set(["low","medium","high","max"]);function taggedChunk(e,t){return{...e&&"object"==typeof e?e:{delta:e},id:t}}const APP_VERSION=require("./package.json").version;function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}function upgradeInfo(e){const t=e&&e.status,n=e&&e.data||{},r="string"==typeof n.error?n.error:"";if(402!==t&&"free_session_limit_reached"!==r)return null;const o=null!=n.tokensUsed?n.tokensUsed:null!=n.sessionsUsed?n.sessionsUsed:null,s=null!=n.tokenLimit?n.tokenLimit:null!=n.freeSessionLimit?n.freeSessionLimit:null;return{url:n.upgradeUrl||"https://aegiscloud.org/go/upgrade?s=desktop&c=status_card",used:o,limit:s,code:r||"free_session_limit_reached"}}function errorText(e){return e&&e.message?e.message:String(e)}function isAbortShapedError(e){return!(!e||"object"!=typeof e||!0!==e.aegisCancelled&&"AbortError"!==e.name&&"ABORT_ERR"!==e.code)}function abortedTurnPayload(e){return{aborted:!0,status:0,code:"ABORT_ERR",message:errorText(e),choices:[{message:{content:""}}]}}function describeSyncError(e){const t=e&&(e.status||e.response&&e.response.status)||0,n=errorText(e);return upgradeInfo(e)?{kind:"quota",status:t||402,message:n,hint:"the plan's synced-token ceiling is reached — free space in the account dashboard or upgrade to keep syncing"}:401===t?{kind:"auth",status:t,message:n,hint:"the memory token was refused — re-enter your AEGIS API key to exchange a new one"}:{kind:"error",status:t||null,message:n,hint:null}}function syncErrorReason(e){return e?e.hint?`${e.message} — ${e.hint}`:e.message:"sync failed"}async function billingResult(e){try{const t=await e();return{ok:!0,url:t&&t.url||null,status:0,reason:null,setupRequired:!1,upgrade:null}}catch(e){const t=e&&e.data||{};return{ok:!1,url:null,status:e&&e.status||0,reason:errorText(e),setupRequired:Boolean(t.setup_required),upgrade:upgradeInfo(e)}}}const{bankAmount:bankAmount,parseTopupAmount:parseTopupAmount,startTopup:startTopup,createCreditWatch:createCreditWatch,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES}=sharedTopup;let topupWatch=null;function watchTopupCredit(e,t){const n=t||{},r=n.intervalMs||TOPUP_POLL_MS,o=n.log;topupWatch&&clearInterval(topupWatch);const s=createCreditWatch(e,n.maxTries?{maxTries:n.maxTries}:void 0),a=()=>{topupWatch&&clearInterval(topupWatch),topupWatch=null,s.stop()},i=async()=>{const e=await s.tick();"credited"===e.state?(a(),(e=>{if("function"!=typeof n.notify)try{const t=electron&&electron.Notification;t&&t.isSupported()&&new t({title:"AEGIS Desktop",body:`Bank credited — €${e.toFixed(2)} available`}).show()}catch{}else n.notify(e)})(e.amount)):"expired"===e.state&&(a(),o&&o("top-up: no credit observed within the watch window; stopping"))};return topupWatch=setInterval(i,r),topupWatch&&"function"==typeof topupWatch.unref&&topupWatch.unref(),{stop:a,tick:i,get baseline(){return s.baseline}}}async function saveMemoryWithQueue(e,t,n,r){const o=avatarStore.normalizeMemoryEntry(n);try{const t=await e.memorySave(o);return r&&o&&"object"==typeof o&&r.awardSave(o,{session:o.session}),t}catch(e){const s=upgradeInfo(e);if(s)return{ok:!1,queued:0,saved:0,upgrade:s,reason:errorText(e)};if(!t||!n)throw e;return memoryQueue.enqueue(t,o),r&&o&&"object"==typeof o&&r.awardQueued(o,{session:o.session}),{ok:!0,queued:!0,reason:errorText(e)}}}async function normalizeMemoryRead(e){try{const t=await e,n=quotaFromPayload(t);return n?Object.assign({},t,{upgrade:n}):t}catch(e){const t=upgradeInfo(e);if(!t)throw e;return{entries:[],upgrade:t}}}function quotaFromPayload(e){if(!e||"object"!=typeof e)return null;const t=null!=e.tokensUsed?e.tokensUsed:null,n=null!=e.tokenLimit?e.tokenLimit:null;return null==t||null==n||n<=0||t<n?null:{url:"https://aegiscloud.org/go/upgrade?s=desktop&c=memory_quota",used:t,limit:n,code:"sync_quota_reached"}}async function importForeignMemory(e,t,n,r){const o=n||{},s=foreignMemory.scan({sources:o.sources,limit:o.limit||1e3}),a=foreignMemory.describe(s),i=s.sources.map((e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,count:e.count,skipped:e.skipped,files:e.files}))),c={summary:a,totals:s.totals,sources:i};if(!o.confirm||!s.entries.length)return{...c,ok:!0,dryRun:!o.confirm,saved:0,queued:0};let u=0,l=0;const d=[];let p=null;for(const n of foreignMemory.chunk(s.entries,200))try{const t=await e.memorySaveBatch(n);if(u+=t&&t.saved||n.length,r&&n.length){const e=n[0]||{};r.awardImports(n,{source:e.session||e.source||"foreign-import"})}}catch(e){if(p=upgradeInfo(e),!p&&t)for(const e of n)memoryQueue.enqueue(t,e),l+=1,r&&r.awardQueued(e,{session:e&&e.session});d.push(errorText(e));break}return{...c,ok:0===d.length,dryRun:!1,saved:u,queued:l,upgrade:p,reason:d[0]||null}}function resolveIconsDir(e,t,n){return e?path.join(t,"icons"):path.join(n,"build")}function iconForPlatform(e,t){return"darwin"===t?path.join(e,"icon.icns"):"win32"===t?path.join(e,"icon.ico"):path.join(e,"icon.png")}function isSafeExternalUrl(e){if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function providerRouteConfigured(e){try{const t=e&&e.settings&&e.settings.list;return"function"==typeof t&&(t.call(e.settings)||[]).some((e=>{if(!e||!e.provider||isReservedNamespace(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)}))}catch{return!1}}function createIpcDispatch(e,t,n,r,o,s,a){let i=null;const c=new Proxy({},{get(e,n){i||(i=createFingerprintService({dir:t,getVaultBackend:a}));const r=i[n];return"function"==typeof r?r.bind(i):r},has:(e,n)=>(i||(i=createFingerprintService({dir:t,getVaultBackend:a})),n in i)}),u=()=>{try{return Boolean("function"==typeof o&&o())}catch{return!1}},l=r||(()=>Promise.reject(new Error("no opener configured")));return{status:()=>({appVersion:APP_VERSION,clientVersion:e.clientVersion,apiBase:e.apiBase,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey),providerConfigured:u()}),setApiKey:t=>{try{const r=t&&t.key;return e.setApiKey(r||""),n&&n(e.apiKey),{ok:!0,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey)}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},verifyApiKey:async()=>{try{return{ok:!0,...await e.verifyApiKey()}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},tokenBankBalance:()=>e.tokenBankBalance(),billingCheckout:()=>billingResult((()=>e.billingCheckout())),tokenBankTopup:async t=>{const n=parseTopupAmount(t&&t.amountEur);if(!n.ok)return{ok:!1,url:null,status:400,reason:n.message,setupRequired:!1,upgrade:null};const r=await startTopup(e,n.amount);return!0===r.ok&&r.url&&watchTopupCredit(e),{ok:!0===r.ok,url:r.url,status:r.status,reason:r.ok?null:r.hint?`${r.message} — ${r.hint}`:r.message,setupRequired:r.setupRequired,upgrade:null}},listModels:()=>e.listModels(),chatCompletion:t=>e.chatCompletion({prompt:t&&t.prompt,system:t&&t.system,model:t&&t.model,mode:t&&t.mode,maxTokens:t&&t.maxTokens,stream:t&&t.stream,onStream:t&&t.onStream}),fingerprintStatus:()=>c.status(),fingerprintKeygen:e=>c.keygen(e||{}),fingerprintMint:e=>c.mint(e||{}),fingerprintVerify:e=>c.verify(e||{}),fingerprintBackup:e=>c.backup(e||{})
|
|
4
|
+
"use strict";const path=require("node:path"),fs=require("node:fs"),{execFile:execFile}=require("node:child_process"),{pathToFileURL:pathToFileURL}=require("node:url");let sharedClient;try{sharedClient=require("../client/aegis.js")}catch{sharedClient=require("./vendor/aegis.js")}const{createClient:createClient}=sharedClient;let credentials,autoProvision,sharedPresence,sharedTopup,googleSignIn,driveConnectLib,driveUploadLib,conversationExportLib;try{credentials=require("../client/credentials.js")}catch{credentials=require("./vendor/credentials.js")}try{autoProvision=require("../client/auto-provision.js")}catch{autoProvision=require("./vendor/auto-provision.js")}try{sharedPresence=require("../client/presence.js")}catch{sharedPresence=require("./vendor/presence.js")}try{sharedTopup=require("../client/topup.js")}catch{sharedTopup=require("./vendor/topup.js")}try{googleSignIn=require("../client/google-signin.js")}catch{googleSignIn=require("./vendor/google-signin.js")}try{driveConnectLib=require("../client/drive-connect.js")}catch{driveConnectLib=require("./vendor/drive-connect.js")}try{driveUploadLib=require("../client/drive-upload.js")}catch{driveUploadLib=require("./vendor/drive-upload.js")}try{conversationExportLib=require("../client/conversation-export.js")}catch{try{conversationExportLib=require("./vendor/conversation-export.js")}catch{conversationExportLib=null}}const{createGoogleConnect:createGoogleConnect}=require("./lib/google-connect.js");let sharedFingerprint;try{sharedFingerprint=require("../client/device-fingerprint.js")}catch{sharedFingerprint=require("./vendor/device-fingerprint.js")}const{createFingerprintService:createFingerprintService}=require("./lib/fingerprint.js"),{createAutoDrain:createAutoDrain,createAutoMint:createAutoMint}=require("./lib/auto.js");let envFile=null;try{envFile=require("../client/env-file.js")}catch{try{envFile=require("./vendor/env-file.js")}catch{}}let electron=null;try{electron=require("electron")}catch{}const os=require("node:os"),{createLocalEngine:createLocalEngine}=require("./lib/local/engine.js"),{createAccountKey:createAccountKey,startupKeyOverride:startupKeyOverride}=require("./lib/account-key.js"),{createSettingsStore:createSettingsStore,isReservedNamespace:isReservedNamespace}=require("./lib/settings.js"),sessionStore=require("./lib/sync/sessions.js"),memoryQueue=require("./lib/sync/memory-queue.js"),sessionSearch=(()=>{try{return require("../client/session-search.js")}catch{return require("./vendor/session-search.js")}})(),creditsLib=(()=>{try{return require("../client/credits.js")}catch{return require("./vendor/credits.js")}})(),memoryStore=require("./lib/sync/memory-store.js"),persistGate=require("./lib/sync/persist-gate.js"),avatarStore=require("./lib/avatar/store.js"),windowState=require("./lib/window-state.js"),deepLink=require("./lib/deep-link.js"),quickLauncherLib=require("./lib/quick-launcher.js");let foreignMemory,foreignSessions;try{foreignMemory=require("../client/foreign-memory.js")}catch{foreignMemory=require("./vendor/foreign-memory.js")}try{foreignSessions=require("../client/foreign-sessions.js")}catch{foreignSessions=require("./vendor/foreign-sessions.js")}const localTools=require("./lib/local/tools.js"),queueModule=require("./lib/local/queue.js"),autonomousModule=require("./lib/local/autonomous.js"),{autoContinuePlan:autoContinuePlan,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault}=require("./lib/local/autonomous.js"),entitlementModule=require("./lib/local/entitlement.js"),telemetryModule=require("./lib/local/telemetry.js"),covenantModule=require("./lib/local/covenant.js"),{createTelemetry:createTelemetry,telemetryEnabled:telemetryEnabled}=telemetryModule,IPC_PREFIX="aegis:",MODEL_PREFIX="model:",SYNC_PREFIX="sync:",TOOLS_PREFIX="tools:",QUICK_PREFIX="quick:",QUEUE_PREFIX="queue:",AUTO_PREFIX="auto:",DESKTOP_CLASSES=Object.freeze(["aegis","byok","local"]),CHAT_DELTA_CHANNEL=`${IPC_PREFIX}chatDelta`,MENU_NEW_CHAT_CHANNEL=`${IPC_PREFIX}menuNewChat`,MENU_SEARCH_CHANNEL=`${IPC_PREFIX}menuSearch`,MENU_SEARCH_MEMORY_CHANNEL=`${IPC_PREFIX}menuSearchMemory`,MENU_CREDITS_CHANNEL=`${IPC_PREFIX}menuCredits`,MENU_EXPORT_MARKDOWN_CHANNEL=`${IPC_PREFIX}menuExportMarkdown`,MENU_EXPORT_JSON_CHANNEL=`${IPC_PREFIX}menuExportJson`,MENU_FINGERPRINT_CHANNEL=`${IPC_PREFIX}menuFingerprint`,MENU_GOOGLE_DRIVE_CHANNEL=`${IPC_PREFIX}menuGoogleDrive`,DEEP_LINK_CHANNEL=`${IPC_PREFIX}deepLink`,QUICK_LAUNCHER_PUSH_CHANNEL=`${IPC_PREFIX}quickLauncherPush`,QUEUE_PROGRESS_CHANNEL=`${QUEUE_PREFIX}progress`,QUEUE_MAX_TASK_CHARS=8e3,QUEUE_MAX_ROUNDS=200,QUEUE_MAX_WORKERS=8,QUEUE_EFFORTS=new Set(["low","medium","high","max"]);function taggedChunk(e,t){return{...e&&"object"==typeof e?e:{delta:e},id:t}}const APP_VERSION=require("./package.json").version;function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}function upgradeInfo(e){const t=e&&e.status,r=e&&e.data||{},n="string"==typeof r.error?r.error:"";if(402!==t&&"free_session_limit_reached"!==n)return null;const o=null!=r.tokensUsed?r.tokensUsed:null!=r.sessionsUsed?r.sessionsUsed:null,s=null!=r.tokenLimit?r.tokenLimit:null!=r.freeSessionLimit?r.freeSessionLimit:null;return{url:r.upgradeUrl||"https://aegiscloud.org/go/upgrade?s=desktop&c=status_card",used:o,limit:s,code:n||"free_session_limit_reached"}}function errorText(e){return e&&e.message?e.message:String(e)}function isAbortShapedError(e){return!(!e||"object"!=typeof e||!0!==e.aegisCancelled&&"AbortError"!==e.name&&"ABORT_ERR"!==e.code)}function abortedTurnPayload(e){return{aborted:!0,status:0,code:"ABORT_ERR",message:errorText(e),choices:[{message:{content:""}}]}}function describeSyncError(e){const t=e&&(e.status||e.response&&e.response.status)||0,r=errorText(e);return upgradeInfo(e)?{kind:"quota",status:t||402,message:r,hint:"the plan's synced-token ceiling is reached — free space in the account dashboard or upgrade to keep syncing"}:401===t?{kind:"auth",status:t,message:r,hint:"the memory token was refused — re-enter your AEGIS API key to exchange a new one"}:{kind:"error",status:t||null,message:r,hint:null}}function syncErrorReason(e){return e?e.hint?`${e.message} — ${e.hint}`:e.message:"sync failed"}async function billingResult(e){try{const t=await e();return{ok:!0,url:t&&t.url||null,status:0,reason:null,setupRequired:!1,upgrade:null}}catch(e){const t=e&&e.data||{};return{ok:!1,url:null,status:e&&e.status||0,reason:errorText(e),setupRequired:Boolean(t.setup_required),upgrade:upgradeInfo(e)}}}const{bankAmount:bankAmount,parseTopupAmount:parseTopupAmount,startTopup:startTopup,createCreditWatch:createCreditWatch,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES}=sharedTopup;let topupWatch=null;function watchTopupCredit(e,t){const r=t||{},n=r.intervalMs||TOPUP_POLL_MS,o=r.log;topupWatch&&clearInterval(topupWatch);const s=createCreditWatch(e,r.maxTries?{maxTries:r.maxTries}:void 0),i=()=>{topupWatch&&clearInterval(topupWatch),topupWatch=null,s.stop()},a=async()=>{const e=await s.tick();"credited"===e.state?(i(),(e=>{if("function"!=typeof r.notify)try{const t=electron&&electron.Notification;t&&t.isSupported()&&new t({title:"AEGIS Desktop",body:`Bank credited — €${e.toFixed(2)} available`}).show()}catch{}else r.notify(e)})(e.amount)):"expired"===e.state&&(i(),o&&o("top-up: no credit observed within the watch window; stopping"))};return topupWatch=setInterval(a,n),topupWatch&&"function"==typeof topupWatch.unref&&topupWatch.unref(),{stop:i,tick:a,get baseline(){return s.baseline}}}let memoryIndexHandle=null,memoryIndexOff=!1;function memoryIndex(e){if(memoryIndexHandle)return memoryIndexHandle;if(memoryIndexOff||!e)return null;try{const t=new memoryStore.MemoryStore({dir:e});return t.open().ok?(memoryIndexHandle=t,memoryIndexHandle):(memoryIndexOff=!0,null)}catch{return memoryIndexOff=!0,null}}function closeMemoryIndex(){if(memoryIndexHandle){try{memoryIndexHandle.close()}catch{}memoryIndexHandle=null}}async function saveMemoryWithQueue(e,t,r,n,o){const s=avatarStore.normalizeMemoryEntry(r);try{const t=await e.memorySave(s);if(n&&s&&"object"==typeof s&&n.awardSave(s,{session:s.session}),o&&s&&"object"==typeof s)try{o.upsert(s)}catch{}return t}catch(e){const o=upgradeInfo(e);if(o)return{ok:!1,queued:0,saved:0,upgrade:o,reason:errorText(e)};if(!t||!r)throw e;return memoryQueue.enqueue(t,s),n&&s&&"object"==typeof s&&n.awardQueued(s,{session:s.session}),{ok:!0,queued:!0,reason:errorText(e)}}}async function normalizeMemoryRead(e){try{const t=await e,r=quotaFromPayload(t);return r?Object.assign({},t,{upgrade:r}):t}catch(e){const t=upgradeInfo(e);if(!t)throw e;return{entries:[],upgrade:t}}}async function normalizeMemoryReadWithFallback(e,t,r,n){try{return await normalizeMemoryRead(e)}catch(e){const o=Number(e&&e.status),s=o>=400&&o<500||!t?null:searchMemoryLocally(t,r,n);if(!s||!s.entries.length)throw e;return s}}function searchMemoryLocally(e,t,r){let n;try{n=e.search(t,{limit:r})}catch{return null}return n&&n.ok&&Array.isArray(n.results)?{entries:n.results.map((e=>({id:e.id,content:e.body,source:"local-index",scope:e.scope,tags:Array.isArray(e.tags)?e.tags:[],createdAt:e.updated}))),local:!0,fts:!0===n.fts}:null}async function indexPulledMemory(e,t){const r=await e;if(t&&r&&Array.isArray(r.entries)&&r.entries.length)try{t.upsertMany(r.entries)}catch{}return r}function quotaFromPayload(e){if(!e||"object"!=typeof e)return null;const t=null!=e.tokensUsed?e.tokensUsed:null,r=null!=e.tokenLimit?e.tokenLimit:null;return null==t||null==r||r<=0||t<r?null:{url:"https://aegiscloud.org/go/upgrade?s=desktop&c=memory_quota",used:t,limit:r,code:"sync_quota_reached"}}async function importForeignSessions(e,t){const r=t||{},n=foreignSessions.scan({sources:r.sources,limit:r.limit||500}),o=foreignSessions.describe(n),s=n.sources.map((e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,unreadable:e.unreadable,count:e.count,messages:e.messages,files:e.files,skipped:e.skipped}))),i={summary:o,totals:n.totals,sources:s};if(!r.confirm||!n.sessions.length)return{...i,ok:!0,dryRun:!r.confirm,imported:0,skippedExisting:0,sessions:n.sessions.map((e=>({id:e.id,title:e.title,source:e.source,sourceLabel:e.sourceLabel,messages:e.messages.length,updatedAt:e.updatedAt})))};const a=new Set((sessions.listSessions(e)||[]).map((e=>e&&e.id)).filter(Boolean));let c=0,l=0;const u=[];for(const t of n.sessions)try{if(a.has(t.id)){l+=1;continue}sessions.upsertSession(e,foreignSessions.toRecord(t,{pending:!0===r.sync})),c+=1}catch(e){u.push(errorText(e))}return{...i,ok:0===u.length,dryRun:!1,imported:c,skippedExisting:l,reason:u[0]||null}}async function importForeignMemory(e,t,r,n,o){const s=r||{},i=foreignMemory.scan({sources:s.sources,limit:s.limit||1e3}),a=foreignMemory.describe(i),c=i.sources.map((e=>({id:e.id,label:e.label,verified:e.verified,present:e.present,count:e.count,skipped:e.skipped,files:e.files}))),l={summary:a,totals:i.totals,sources:c};if(!s.confirm||!i.entries.length)return{...l,ok:!0,dryRun:!s.confirm,saved:0,queued:0};let u=0,d=0;const p=[];let m=null;for(const r of foreignMemory.chunk(i.entries,200))try{const t=await e.memorySaveBatch(r);if(u+=t&&t.saved||r.length,n&&r.length){const e=r[0]||{};n.awardImports(r,{source:e.session||e.source||"foreign-import"})}if(o&&r.length)try{o.upsertMany(r)}catch{}}catch(e){if(m=upgradeInfo(e),!m&&t)for(const e of r)memoryQueue.enqueue(t,e),d+=1,n&&n.awardQueued(e,{session:e&&e.session});p.push(errorText(e));break}return{...l,ok:0===p.length,dryRun:!1,saved:u,queued:d,upgrade:m,reason:p[0]||null}}function resolveIconsDir(e,t,r){return e?path.join(t,"icons"):path.join(r,"build")}function iconForPlatform(e,t){return"darwin"===t?path.join(e,"icon.icns"):"win32"===t?path.join(e,"icon.ico"):path.join(e,"icon.png")}function isSafeExternalUrl(e){if("string"!=typeof e||!e)return!1;try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function providerRouteConfigured(e){try{const t=e&&e.settings&&e.settings.list;return"function"==typeof t&&(t.call(e.settings)||[]).some((e=>{if(!e||!e.provider||isReservedNamespace(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)}))}catch{return!1}}function createIpcDispatch(e,t,r,n,o,s,i){let a=null;const c=new Proxy({},{get(e,r){a||(a=createFingerprintService({dir:t,getVaultBackend:i}));const n=a[r];return"function"==typeof n?n.bind(a):n},has:(e,r)=>(a||(a=createFingerprintService({dir:t,getVaultBackend:i})),r in a)}),l=()=>{try{return Boolean("function"==typeof o&&o())}catch{return!1}},u=n||(()=>Promise.reject(new Error("no opener configured")));return{status:()=>({appVersion:APP_VERSION,clientVersion:e.clientVersion,apiBase:e.apiBase,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey),providerConfigured:l()}),setApiKey:t=>{try{const n=t&&t.key;return e.setApiKey(n||""),r&&r(e.apiKey),{ok:!0,keyConfigured:Boolean(e.apiKey),keyMask:maskKey(e.apiKey)}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},verifyApiKey:async()=>{try{return{ok:!0,...await e.verifyApiKey()}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},tokenBankBalance:()=>e.tokenBankBalance(),billingCheckout:()=>billingResult((()=>e.billingCheckout())),tokenBankTopup:async t=>{const r=parseTopupAmount(t&&t.amountEur);if(!r.ok)return{ok:!1,url:null,status:400,reason:r.message,setupRequired:!1,upgrade:null};const n=await startTopup(e,r.amount);return!0===n.ok&&n.url&&watchTopupCredit(e),{ok:!0===n.ok,url:n.url,status:n.status,reason:n.ok?null:n.hint?`${n.message} — ${n.hint}`:n.message,setupRequired:n.setupRequired,upgrade:null}},listModels:()=>e.listModels(),chatCompletion:t=>e.chatCompletion({prompt:t&&t.prompt,system:t&&t.system,model:t&&t.model,mode:t&&t.mode,maxTokens:t&&t.maxTokens,stream:t&&t.stream,onStream:t&&t.onStream}),fingerprintStatus:()=>c.status(),fingerprintKeygen:e=>c.keygen(e||{}),fingerprintMint:e=>c.mint(e||{}),fingerprintVerify:e=>c.verify(e||{}),fingerprintBackup:e=>c.backup(e||{})
|
|
5
5
|
// gdrive:AEGIS-AGPL/records and writes the `.anchor.json` link beside the
|
|
6
|
-
,fingerprintPublish:e=>c.publish(e||{}),fingerprintAnchor:e=>c.anchor(e||{}),fingerprintVault:()=>c.vaultList(),fingerprintVaultAudit:()=>c.vaultAudit(),byokStatus:()=>e.byokStatus(),byokSet:t=>e.byokSet(t&&t.provider,t&&t.apiKey),memorySearch:t=>normalizeMemoryRead(e.memorySearch(t&&t.query,t&&t.limit)),memorySave:n=>saveMemoryWithQueue(e,t,n&&n.entry,s),memoryList:t=>normalizeMemoryRead(e.memoryList(t&&t.limit)),verifyToken:t=>e.verifyToken(t&&t.token),memoryActivate:t=>e.memoryActivate(t&&t.token),memoryPull:t=>e.memoryPull(t&&t.since),memorySaveBatch:t=>e.memorySaveBatch(t&&t.entries),memoryImport:n=>importForeignMemory(e,t,n,s),importConversation:t=>e.importConversation(t||{}),openExternal:e=>{const t=e&&e.url;return isSafeExternalUrl(t)?Promise.resolve(l(t)).then((()=>({ok:!0})),(e=>({ok:!1,reason:errorText(e)}))):Promise.resolve({ok:!1,reason:"unsupported URL scheme"})}}}function withReplyNotify(e,t,n){return n?e.then((e=>(n(t,e),e))):e}function registerIpc(e,t,n,r,o,s,a,i){const c=createIpcDispatch(t,n,r,o,a,void 0,i);for(const[t,n]of Object.entries(c))"chatCompletion"!==t?e.handle(`${IPC_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${IPC_PREFIX}${t}`,((e,t)=>{const r={...t||{}};if(!r.stream)return withReplyNotify(n(r),e,s);const o=e&&e.sender;return withReplyNotify(n({...r,stream:!0,onStream:e=>{o&&"function"==typeof o.send&&!o.isDestroyed()&&o.send(CHAT_DELTA_CHANNEL,taggedChunk(e,r.sessionId))}}),e,s)}));return c}function createConfirmModeDispatch(e){if(!e)throw new Error("createConfirmModeDispatch requires a settings store");return{getConfirmMode:()=>({enabled:e.getConfirmMode()}),setConfirmMode:t=>{const n=t&&t.enabled;return"boolean"!=typeof n?{enabled:e.getConfirmMode()}:{enabled:e.setConfirmMode(n)}}}}function withAutoRoundsSwitch(e,t){const n=e.setConfirmMode;return{...e,setConfirmMode:e=>{const r=n(e);return e&&"boolean"==typeof e.enabled&&t&&"function"==typeof t.setAutoRounds&&t.setAutoRounds(!1===e.enabled),r}}}function registerConfirmModeIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function createVaultBackendDispatch(e){if(!e)throw new Error("createVaultBackendDispatch requires a settings store");return{getVaultBackend:()=>e.vaultBackendConfig(),setVaultBackend:t=>e.setVaultBackendConfig(t&&t.backend)}}function createTelemetryDispatch(e){const t=e||null;return{telemetryEvent:e=>{try{if(!t||"function"!=typeof t.record)return{ok:!1,reason:"telemetry off"};const n=e&&"object"==typeof e?e:{};return t.record(n.event,{campaign:n.campaign,surface:n.surface})?{ok:!0}:{ok:!1,reason:"not an allowlisted funnel event"}}catch(e){return{ok:!1,reason:errorText(e)}}},telemetryReport:()=>{try{return t&&"function"==typeof t.report?t.report():{enabled:!1,transport:"off"}}catch(e){return{enabled:!1,error:errorText(e)}}}}}function createCovenantDispatch(e){return{covenantStatus:()=>({ok:!0,covenant:e.snapshot(),gapReport:e.gapReport()}),covenantGapReport:()=>({ok:!0,gapReport:e.gapReport()})}}function registerCovenantIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function registerTelemetryIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${IPC_PREFIX}${n}`,((e,t)=>r(t)));return t}function safeExportBasename(e){return(e&&(e.title||e.id)||"session").replace(/[^\w.-]+/g,"_").slice(0,80)||"session"}function createExportDispatch(e,t,n,r){return{exportSession:async o=>{const s=o&&o.sessionId,a=o&&"json"===o.format?"json":"markdown",i=s?e.getSession(t,s):null;if(!i)return{ok:!1,reason:"session not found"};const c="json"===a?e.toJson(i):e.toMarkdown(i),u="json"===a?"json":"md",l="json"===a?[{name:"JSON",extensions:["json"]}]:[{name:"Markdown",extensions:["md"]}],d=await n({defaultPath:`${safeExportBasename(i)}.${u}`,filters:l});if(!d||d.canceled||!d.filePath)return{ok:!1,canceled:!0};try{await r(d.filePath,c)}catch(e){return{ok:!1,reason:errorText(e)}}return{ok:!0,filePath:d.filePath}}}}function registerExportIpc(e,t,n,r,o){const s=createExportDispatch(t,n,r,o);for(const[t,n]of Object.entries(s))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>n(t)));return s}function createQuickLauncherDispatch(e,t={}){const n=Boolean(t.isPackaged),r=t.applyConfig||(()=>({active:!1,reason:null})),o=t.pushToMain||(()=>({ok:!1,reason:"no main window"}));let s={active:!1,reason:null};return{status:function(){return{...e.quickLauncherConfig(),packaged:n,...s}},setConfig:function(t){const o=e.setQuickLauncherConfig({enabled:t&&t.enabled,shortcut:t&&t.shortcut});return s=r(o)||{active:!1,reason:null},{...o,packaged:n,...s}},pushToMain:(e,t)=>o(e,t)}}function registerQuickLauncherIpc(e,t){for(const[n,r]of Object.entries(t))"pushToMain"!==n?e.handle(`${QUICK_PREFIX}${n}`,((e,t)=>r(t))):e.handle(`${QUICK_PREFIX}${n}`,((e,t)=>r(t,e)));return t}function resolveUserDataDir(e){if(e&&"function"==typeof e.getPath)try{return e.getPath("userData")}catch{}try{const e=require("../one/src/iface/paths.js").plan({platform:process.platform,env:process.env});if(e&&e.ok)return e.state}catch{}return path.join(os.homedir(),".aegiscode")}function createEngine(e,{app:t,safeStorage:n,dir:r,sessionsDir:o}={}){const s=r||resolveUserDataDir(t),a=createSettingsStore({dir:s,safeStorage:n});return a.migrateLegacyAegisKey(),{engine:createLocalEngine({aegis:e,settings:a}),sessionsDir:o||sessionStore.resolveStoreDir(s),settingsDir:s,settings:a}}const PREVIEW_READ_MAX_BYTES=524288;function readTextFileForPreview(e){try{const t=e&&"string"==typeof e.file?e.file:"",n=e&&"string"==typeof e.cwd?e.cwd:"";if(!t||!n||!path.isAbsolute(n))return null;const r=fs.realpathSync(n),o=fs.realpathSync(path.resolve(r,t)),s=path.relative(r,o);if(""===s||s.startsWith("..")||path.isAbsolute(s))return null;const a=fs.statSync(o);if(!a.isFile())return null;if(a.size<=PREVIEW_READ_MAX_BYTES)return{text:fs.readFileSync(o,"utf8"),truncated:!1};const i=fs.openSync(o,"r");try{const e=Buffer.alloc(PREVIEW_READ_MAX_BYTES),t=fs.readSync(i,e,0,PREVIEW_READ_MAX_BYTES,0);let n=e.toString("utf8",0,t);const r=n.lastIndexOf("\n");return r>0&&(n=n.slice(0,r+1)),{text:n,truncated:!0}}finally{fs.closeSync(i)}}catch{return null}}const attachmentsModule=require("./lib/local/attachments.js");function nativeImageResizer(e,t){try{const{nativeImage:n}=require("electron");if(!n)return null;const r=n.createFromBuffer(e);if(!r||r.isEmpty())return null;const o=r.getSize(),s=Math.max(o.width,o.height),a=s>1568?r.resize({width:Math.round(1568*o.width/s)}):r,i="image/png"===t?a.toPNG():a.toJPEG(82);return i&&i.length?{buffer:i,mime:"image/png"===t?"image/png":"image/jpeg"}:null}catch{return null}}function ingestAttachment(e,{resize:t=nativeImageResizer}={}){const n=e&&"string"==typeof e.path?e.path.trim():"";if(!n)return{ok:!1,reason:"no path"};if(!path.isAbsolute(n))return{ok:!1,reason:"not an absolute path"};let r,o,s;try{r=fs.realpathSync(n),o=fs.statSync(r)}catch{return{ok:!1,reason:"not found"}}if(!o.isFile())return{ok:!1,reason:"not a regular file"};if(0===o.size)return{ok:!1,reason:"empty file"};if(o.size>attachmentsModule.MAX_FILE_BYTES)return{ok:!1,reason:`too large (${attachmentsModule.humanBytes(o.size)})`};try{s=fs.readFileSync(r)}catch{return{ok:!1,reason:"unreadable"}}const a=attachmentsModule.sniff(s),i={path:r,name:path.basename(r),size:o.size,mime:a.mime,kind:a.kind};if("image"===a.kind){let{mime:e}=a,n=s,r=!1;if(n.length>attachmentsModule.MAX_IMAGE_BYTES&&"function"==typeof t){const o=t(s,e);o&&o.buffer&&o.buffer.length<n.length&&(n=o.buffer,e=o.mime,r=!0)}const o=attachmentsModule.toDataUrl(n,e);return o?{ok:!0,attachment:{...i,kind:"image",mime:e,size:n.length,dataUrl:o,scaled:r,vision:attachmentsModule.isVisionMime(e)}}:{ok:!1,reason:"could not encode image"}}if("text"===a.kind){if(o.size>attachmentsModule.MAX_TEXT_BYTES){let e=s.subarray(0,attachmentsModule.MAX_TEXT_BYTES).toString("utf8");const t=e.lastIndexOf("\n");return t>0&&(e=e.slice(0,t+1)),{ok:!0,attachment:{...i,kind:"text",text:e,truncated:!0}}}return{ok:!0,attachment:{...i,kind:"text",text:s.toString("utf8"),truncated:!1}}}return"pdf"===a.kind?{ok:!0,attachment:{...i,kind:"pdf"}}:{ok:!0,attachment:{...i,kind:"binary"}}}function createModelDispatch(e,{env:t=process.env,settings:n}={}){const r=new Map;let o,s=autoRoundsDefault(t),a=!1;const i=()=>{const t=n||e&&e.settings||null,r=e=>"boolean"==typeof e?e:void 0;let i;try{if(t&&"function"==typeof t.confirmModeState){const e=t.confirmModeState();i=r(e&&e.enabled)}void 0===i&&t&&"function"==typeof t.getConfirmMode&&(i=r(t.getConfirmMode()))}catch{}return a||void 0===i||(void 0===o?o=i:i!==o&&(a=!0,s=!0)),!(!s||!t||void 0===i)&&!1===i},c={listClasses:async()=>(await e.listClasses()).filter((e=>DESKTOP_CLASSES.includes(e.class))),listModels:t=>e.listModels(t&&t.class),chat:n=>{const o=n&&n.onStream;if("function"!=typeof o)return e.chat(n,o);const s=n&&n.sessionId||"";return e.chat(n,(n=>{if(n&&n.rounds&&n.rounds.id&&i()){const a=autoContinuePlan({on:!0,used:r.get(s)||0,limit:autoContinueLimit(t)});if(r.set(s,a.used),a.auto){const t="function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(n.rounds.id,!0):{ok:!1};if(t&&t.ok){const e=Number(n.rounds.spent)||0;return void o({note:`auto mode: the ${e}-round limit was reached — continuing automatically (${a.used}/${a.cap}, then it asks).`})}}}o(n)}))},"settings.get":()=>e.settings.list().filter((e=>!(e&&isReservedNamespace(e.provider)))),"settings.set":t=>e.settings.set(t&&t.provider,{baseURL:t&&t.baseURL,key:t&&t.key}),"settings.remove":t=>e.settings.remove(t&&t.provider),"userModels.get":()=>e.userModels(),"userModels.add":t=>e.addUserModel(t&&t.provider,t&&t.model),"userModels.remove":t=>e.removeUserModel(t&&t.provider,t&&t.model),"userModels.discover":t=>e.discoverModels(t&&t.provider),"userModels.addAll":t=>e.addUserModels(t&&t.provider,t&&t.ids),"userModels.canDiscover":t=>Boolean(e.canDiscoverModels(t&&t.provider)),"userModels.discoverable":()=>e.discoverableProviders(),"memoryPersist.get":()=>e.settings.memoryPersistState(),"memoryPersist.set":t=>e.settings.setMemoryPersist(Boolean(t&&t.enabled)),cancel:t=>e.cancel(t&&t.sessionId),respondApproval:t=>e.respondApproval(t&&t.approvalId,t&&t.decision),respondRoundsAsk:t=>"function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(t&&t.roundsAskId,t&&t.decision):{ok:!1},clearApprovals:t=>e.clearSessionApprovals(t&&t.sessionId)};return Object.defineProperties(c,{autoRoundsOn:{value:i,enumerable:!1},setAutoRounds:{value:e=>{s=Boolean(e),a=!0},enumerable:!1}}),c}function createSyncDispatch(e,t,n,r,o){let s=null;function a(){return Boolean(n&&n.apiKey)}async function i(){const r=e.listPending(t);if(!a())return{ok:!1,queued:r.length,reason:"no AEGIS key configured"};const o=await async function(){const e=memoryQueue.listQueued(t);if(!e.length)return{flushed:0,remaining:0,upgrade:null};const r=[];let o=0,s=null;for(let t=0;t<e.length;t+=1)try{await n.memorySave(e[t]),o+=1}catch(n){const o=upgradeInfo(n);if(o){s=o,r.push(...e.slice(t));break}r.push(e[t])}return memoryQueue.save(t,r),{flushed:o,remaining:r.length,upgrade:s}}();if(!r.length)return{ok:!0,queued:0,pushed:0,memoryFlushed:o.flushed,upgrade:o.upgrade};let i=0,c=null,u=null;for(const o of r)try{const r=await n.conversationSyncPush({session_id:o.id,title:o.title,messages:o.messages}),s=r&&(r.session_id||r.id);e.markSynced(t,o.id,{remoteId:s}),i+=1}catch(e){if(c=e,u=describeSyncError(e),"quota"===u.kind||"auth"===u.kind)break}const l=e.listPending(t).length;i&&(s=Date.now());const d=(c?upgradeInfo(c):null)||o.upgrade;return 0===i&&c?{ok:!1,queued:l,reason:syncErrorReason(u),failed:u?[u]:[],kind:u?u.kind:"error",status:u?u.status:0,hint:u?u.hint:null,memoryFlushed:o.flushed,upgrade:d}:{ok:!0,queued:l,pushed:i,failed:u?[u]:[],memoryFlushed:o.flushed,upgrade:d}}const c=persistGate.createAutoPush({push:i,dir:r||t});return{auto:()=>c.auto(),memoryPersistState:()=>c.gate(),listSessions:()=>({sessions:e.listSessions(t)}),open:n=>e.getSession(t,n&&n.sessionId),save:n=>e.upsertSession(t,n||{}),append:n=>e.appendMessage(t,n&&n.sessionId,n&&n.message),delete:n=>e.deleteSession(t,n&&n.sessionId),nameSession:async n=>{const r=n&&n.sessionId,s=n&&n.prompt;if(!r||!String(null==s?"":s).trim())return null;let a;for(const e of["../client/naming.js","./vendor/naming.js","./vendor/client/naming.js"])try{a=require(e);break}catch{}if(!a)return null;const i=async(e,t={})=>{if(!o||"function"!=typeof o.chat)return null;try{const s=await o.chat({class:n&&n.class||"model",model:n&&n.model,prompt:e,system:t.system,maxTokens:64,sessionId:r,tools:!1}),a=s&&s.choices&&s.choices[0]||{};return a.message&&a.message.content||null}catch{return null}};try{return await a.nameSession(e,t,r,s,{callModel:i})}catch{return null}},push:i,pull:async function(){if(!a())return{ok:!1,merged:0,reason:"no AEGIS key configured"};try{const r=await n.conversationSyncPull(),o=e.mergeRemoteSessions(t,r&&r.sessions||[]);return s=Date.now(),{ok:!0,merged:o,failed:[],upgrade:null}}catch(e){const t=describeSyncError(e);return{ok:!1,merged:0,reason:syncErrorReason(t),failed:[t],kind:t.kind,status:t.status,hint:t.hint,upgrade:upgradeInfo(e)}}},status:()=>({count:e.listSessions(t).length,pending:e.listPending(t).length,cloud:a(),lastSyncAt:s})}}const HEARTBEAT_RETRY_BASE_MS=5e3,HEARTBEAT_RETRY_MAX_MS=3e4;function createHeartbeatRetry(e,t={}){const n="function"==typeof t.now?t.now:()=>Date.now(),r=Number(t.baseMs)>0?Number(t.baseMs):HEARTBEAT_RETRY_BASE_MS,o=Number(t.maxMs)>0?Number(t.maxMs):HEARTBEAT_RETRY_MAX_MS;let s=0,a=0,i=null,c=!1;function u(e){s+=1;const t=Math.min(o,r*2**Math.max(0,s-1));return i=e||"push failed",a=n()+t,{attempted:!0,ok:!1,error:i,failures:s,retryInMs:t}}return{run:async function(){const t=n();if(s>0&&t<a)return{attempted:!1,ok:!1,error:i,failures:s,retryInMs:a-t};if(c)return{attempted:!1,ok:!1,error:i,failures:s,retryInMs:0};c=!0;try{const t=await e();return t&&!1===t.ok?u(t.reason||t.kind||"push failed"):(s=0,a=0,i=null,{attempted:!0,ok:!0,error:null,failures:0,retryInMs:0,result:t})}catch(e){return u(errorText(e))}finally{c=!1}},state:function(){const e=n();return{failures:s,lastError:i,retryInMs:s>0&&a>e?a-e:0}},recordFailure:e=>u(errorText(e))}}function registerModelIpc(e,t,n,r,o,s,a){const i=createModelDispatch(t),c=createSyncDispatch(sessionStore,n,r,a,i),u=createHeartbeatRetry((()=>c.push()),s);function l(){const e=u.run();e&&"function"==typeof e.catch&&e.catch((e=>u.recordFailure(e)))}for(const[t,n]of Object.entries(i))"chat"!==t?"listModels"!==t?e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>(l(),n(t)))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>{const r={...t||{}},s=!0===r.bestEffort;delete r.bestEffort;const a="low"===r.effort||"medium"===r.effort||"max"===r.effort?r.effort:"high";r.effort=a;const i=e&&e.sender,c=r.class||"model",u=n({...r,onStream:e=>{i&&"function"==typeof i.send&&!i.isDestroyed()&&i.send(CHAT_DELTA_CHANNEL,taggedChunk(e,r.sessionId))}});return s?u.then((t=>(o&&o(e,t),t)),(e=>{const t=e&&"number"==typeof e.status?e.status:0,n=e&&e.code||"";return console.warn(`[model] background ${c} turn produced no answer: ${errorText(e)}${t?` (status ${t})`:""}${n?` [${n}]`:""}`),{bestEffortFailed:!0,status:t,code:n||void 0,message:errorText(e),choices:[{message:{content:""}}]}})):withReplyNotify(u,e,o).catch((e=>{if(!isAbortShapedError(e))throw e;return console.warn(`[model] ${c} turn stopped before it finished: ${errorText(e)} [ABORT_ERR]`),abortedTurnPayload(e)}))}));e.on(`${MODEL_PREFIX}readTextFile`,((e,t)=>{e.returnValue=readTextFileForPreview(t)})),e.handle(`${IPC_PREFIX}attachments:ingest`,(async(e,t)=>ingestAttachment(t)));for(const[t,n]of Object.entries(c))"status"!==t?e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>n(t))):e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>{l();const r=n(t);return r&&"object"==typeof r?{...r,retry:u.state()}:r}));return{modelDispatch:i,syncDispatch:c,heartbeat:u}}function createQueueEngine(e,t){return createLocalEngine({aegis:e,settings:t,getConfirmMode:()=>!1})}function queueEngineWithDeniedApprovals(e){return e&&"function"==typeof e.chat?{...e,chat:(t,n)=>e.chat(t,(t=>{(t=>{const n=t&&t.approval;if(n&&n.id&&"function"==typeof e.respondApproval)try{e.respondApproval(n.id,"deny")}catch{}})(t),(t=>{const n=t&&t.rounds;if(n&&n.id&&"function"==typeof e.respondRoundsAsk)try{e.respondRoundsAsk(n.id,!1)}catch{}})(t),"function"==typeof n&&n(t)}))}:e}function isExistingDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function clampInt(e,t,n){const r=Number(e);return!Number.isInteger(r)||r<t||r>n?null:r}function createQueueDispatch({engine:e,env:t=process.env,queue:n=queueModule,autonomous:r=autonomousModule,entitlement:o=entitlementModule.createEntitlement({}),log:s=(()=>{})}={}){if(!e||"function"!=typeof e.chat)throw new Error("createQueueDispatch: a local engine with chat() is required");let a=null,i=!1,c=!1;const u=r.createQueueWorker({engine:queueEngineWithDeniedApprovals(e),env:t,log:e=>{e&&"start"===e.type&&(a=e.taskId),e&&"finish"===e.type&&(a=null),s(e)},canFanOut:()=>o.current().entitled});function l(){const e=n.loadQueue(t);return{ok:!0,items:e,pending:n.pendingCount(e),running:e.find((e=>e&&"running"===e.status))||null,draining:c,stopping:i,defaultCwd:process.cwd(),defaultModel:r.resolveModel({env:t}),queueFile:n.queuePath(t),runs:n.readRuns(t,{limit:20}),entitlement:o.current()}}const d=e=>(e||[]).map((e=>({id:e.id,ok:Boolean(e.ok),error:e.error||null})));return{enqueue:async e=>{await o.refresh();const s=o.gateFanout({workers:clampInt(e&&e.workers,1,QUEUE_MAX_WORKERS),fanout:Boolean(e&&!0===e.fanout)});if(!s.ok)return{...s,...l()};const{opts:a,error:i}=function(e){const t=e||{},n=String(null==t.task?"":t.task).trim();if(!n)return{error:"a queued task needs text"};if(n.length>QUEUE_MAX_TASK_CHARS)return{error:`task text is too long (${n.length} > ${QUEUE_MAX_TASK_CHARS} chars)`};const o=String(null==t.cwd?"":t.cwd).trim()||process.cwd();if(!path.isAbsolute(o))return{error:"the working directory must be an absolute path"};if(!isExistingDir(o))return{error:`not a directory: ${o}`};const s=r.normalizeClass(t.class),a=String(null==t.model?"":t.model).trim().slice(0,120)||null,i=r.modelRefusal(a,s);if(i)return{error:i};const c=String(null==t.effort?"":t.effort).trim().toLowerCase();return{opts:{task:n,cwd:o,class:s,model:a,effort:QUEUE_EFFORTS.has(c)?c:null,workers:clampInt(t.workers,1,QUEUE_MAX_WORKERS),maxRounds:clampInt(t.maxRounds,1,QUEUE_MAX_ROUNDS),singlePass:!(!0===t.fanout||!0===t.autonomous),commit:Boolean(t.commit),source:"desktop"}}}(e);return i?{ok:!1,reason:i,...l()}:{ok:!0,item:n.addTask(t,a),...l()}},list:()=>l(),entitlement:async e=>(await o.refresh({force:Boolean(e&&!0===e.force)}),{ok:!0,...l()}),clear:e=>({...n.clearQueue(t,{all:Boolean(e&&e.all)}),ok:!0,...l()}),retry:e=>{const r=e&&e.id,o=n.retryTask(t,r);return o?{ok:!0,item:o,...l()}:{ok:!1,reason:`no task #${r}`,...l()}},remove:e=>{const r=e&&e.id,o=n.loadQueue(t),s=n.findTask(o,r);return s?"running"===s.status?{ok:!1,reason:`task #${s.id} is running — stop the drain first`,...l()}:(n.saveQueue(t,o.filter((e=>Number(e&&e.id)!==Number(s.id)))),{ok:!0,removed:s.id,...l()}):{ok:!1,reason:`no task #${r}`,...l()}},drain:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...l()};let e;c=!0,i=!1;try{const t=await u.proceed({max:1});e=t.locked?{ok:!1,locked:!0,holder:t.holder,ran:[]}:{ok:!0,ran:d(t.ran)}}catch(t){e={ok:!1,reason:errorText(t),ran:[]}}return c=!1,a=null,{...e,...l()}}(),proceed:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...l()};c=!0,i=!1;const e=[];let t;try{for(;;){const n=await u.proceed({max:1});if(n.locked){t={ok:!1,locked:!0,holder:n.holder,ran:d(e)};break}if(!n.ran.length){t={ok:!0,stopped:i,ran:d(e)};break}if(e.push(...n.ran),i){t={ok:!0,stopped:!0,ran:d(e)};break}}}catch(n){t={ok:!1,reason:errorText(n),ran:d(e)}}return c=!1,a=null,{...t,...l()}}(),stop:e=>{i=!0;const t=e&&null!=e.id?e.id:a,n=null==t?null:u.cancel(t);return{ok:!0,wasDraining:c,cancelled:n,...l()}}}}function createAutoDispatch({autoDrain:e,autoMint:t}={}){if(!e||"function"!=typeof e.state)throw new Error("createAutoDispatch: the auto-drain automation is required");if(!t||"function"!=typeof t.state)throw new Error("createAutoDispatch: the auto-mint automation is required");return{autoStatus:()=>({ok:!0,drain:e.state(),mint:t.state()}),autoSetDrain:t=>{const n=t||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.intervalMs&&(r.intervalMs=Number(n.intervalMs));try{return{ok:!0,drain:e.set(r)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSetMint:e=>{const n=e||{},r={};null!=n.enabled&&(r.enabled=Boolean(n.enabled)),null!=n.publish&&(r.publish=Boolean(n.publish));try{return{ok:!0,mint:t.set(r)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSealNow:async e=>{const n=e||{};null!=n.publish&&t.set({publish:Boolean(n.publish)});try{const e=await t.flush();return t.reset(),{ok:!0,...e}}catch(e){return t.reset(),{ok:!1,error:errorText(e)}}}}}function registerQueueIpc(e,{engine:t,env:n,queue:r,autonomous:o,entitlement:s,aegis:a}={}){let i=null;const c=createQueueDispatch({engine:t,env:n,queue:r,autonomous:o,entitlement:s||entitlementModule.createEntitlement({probe:a&&"function"==typeof a.verifyApiKey?async()=>{const e=await a.verifyApiKey(),t=e&&"object"==typeof e?{...e}:{};if("function"==typeof a.tokenBankBalance)try{const e=await a.tokenBankBalance();e&&"object"==typeof e&&(null!=e.balance_micros?t.balance_micros=e.balance_micros:null!=e.balance_eur&&(t.balance_eur=e.balance_eur))}catch{}return t}:void 0}),log:e=>{i&&"function"==typeof i.send&&("function"==typeof i.isDestroyed&&i.isDestroyed()||i.send(QUEUE_PROGRESS_CHANNEL,e))}});for(const[t,n]of Object.entries(c))e.handle(`${QUEUE_PREFIX}${t}`,((e,t)=>(i=e&&e.sender||null,n(t))));return c}function registerAutoIpc(e,t){for(const[n,r]of Object.entries(t))e.handle(`${AUTO_PREFIX}${n}`,((e,t)=>r(t)));return t}const UPDATE_STATUS_CHANNEL=`${IPC_PREFIX}updateStatus`,ACCOUNT_STATUS_CHANNEL=`${IPC_PREFIX}accountStatusChanged`,UPDATE_CHECK_INTERVAL_MS=144e5,UPDATE_RETRY_BACKOFF_MS=[6e4,3e5,9e5,36e5];function describeRegistryFailure(e,t,n){switch(e){case"not-found":return`${n} is not published on the npm registry (404)`;case"forbidden":return`the npm registry refused the request (${t||"auth"})`;case"malformed":return"the npm registry sent a response this app could not read";case"too-large":return"the npm registry response was too large to read";case"timeout":return"the npm registry did not respond in time";case"network":return"the npm registry could not be reached";default:return"the update check did not complete"}}function createNpmUpdateManager({onStatus:e,packaged:t=!1,now:n=(()=>Date.now()),fetchImpl:r,setTimeoutImpl:o=setTimeout,clearTimeoutImpl:s=clearTimeout,runUpgrade:a,relaunch:i}={}){const c="aegis-desktop";let u="unknown";try{u=require("./package.json").version}catch{}let l={status:"idle",version:null,error:null,channel:"npm",reason:null,transient:!1,attempts:0,retryInMs:0,command:null,plan:null,method:null,canDownload:!1};const d=t=>(l={...l,...t},e&&e(l),l);let p=null;try{p=require("../client/update.js")}catch{try{p=require("./vendor/update.js")}catch{p=null}}let f=0,m=0,h=null,g=null,y=null,E=null;function k(){h&&s(h),h=null}async function _({announce:e=!1}={}){if(!p)return d({status:"disabled",error:"update checker unavailable"});if(g)return g;g=(async()=>{const s=l.status,a=l.version;let i;d({status:"checking",error:null,reason:null,transient:!1});try{i=await async function(){if(r)return r({pkg:c});if(p&&"function"==typeof p.checkPublished){const e=await p.checkPublished({current:u,pkg:c,now:n(),intervalMs:0});return e?{ok:e.ok,latest:e.latest,reason:e.reason,status:e.status}:{ok:!1,latest:null,reason:"unknown",status:null}}return{ok:!1,latest:null,reason:"unavailable",status:null}}()}catch(e){i={ok:!1,latest:null,reason:"unknown",status:null,error:errorText(e)}}if(i.ok){if(f=0,m=0,k(),!p.isNewer(i.latest,u))return d({status:"up-to-date",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0});const e=function(){if(E)return E;const e=p&&p.detectInstallMethod;if("function"!=typeof e)return E="npm",E;try{E=e({env:process.env,argv:process.argv,pkg:c,entry:__dirname,fileExists:e=>fs.existsSync(path.resolve(__dirname,"..",e))})}catch{E="npm"}return E}(),n="function"==typeof p.updatePlan?p.updatePlan({current:u,latest:i.latest,behind:!0,channel:"npm",pkg:c,method:e}):null;return d({status:"available",version:i.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,plan:n,method:e,command:t?`${i.latest} is published — reinstall AEGIS Desktop from the installer to pick it up`:n&&n.instruction||`npm i -g ${c}@latest`,commandIsSentence:t||Boolean(n&&!n.apply),canDownload:Boolean(n&&n.apply)&&!t})}f+=1;const g=i.error||describeRegistryFailure(i.reason,i.status,c);return y=i.reason,v=i.status,("function"==typeof p.isTransientReason?p.isTransientReason(y,v):"unknown"===y)?(function(){k();const e=UPDATE_RETRY_BACKOFF_MS[Math.min(Math.max(f-1,0),UPDATE_RETRY_BACKOFF_MS.length-1)];m=n()+e,h=o((()=>{h=null,_().catch((()=>{}))}),e),h&&h.unref&&h.unref(),d({retryInMs:e})}(),d(e?{status:"error",error:g,reason:i.reason,transient:!0,attempts:f}:{status:"available"===s?"available":"unavailable",version:a,error:g,reason:i.reason,transient:!0,attempts:f})):(k(),m=0,d({status:"error",error:g,reason:i.reason,transient:!1,attempts:f,retryInMs:0}));var y,v})();try{return await g}finally{g=null}}return{status:()=>l,check:_,download:async()=>{const e=!t&&l.plan&&l.plan.apply;if(!e)return d({status:"available"===l.status?"available":l.status,command:l.plan&&l.plan.instruction||l.command,canDownload:!1});d({status:"downloading",error:null,progress:0});const n=await function(e){const t=a||((e,t)=>new Promise((n=>{execFile(e,t,{timeout:18e4,windowsHide:!0},((e,t,r)=>{if(e)return n({ok:!1,output:String(r||t||e.message||e)});n({ok:!0,output:String(t||"")})}))}))),n=!a&&p&&"function"==typeof p.installSpawn?p.installSpawn(e,{env:process.env}):null,r=n?n.command:e.command,o=n?n.args:e.args;return Promise.resolve(t(r,o)).then((e=>({ok:Boolean(e&&e.ok),output:String(e&&e.output||"")})),(e=>({ok:!1,output:errorText(e)})))}(e);return n.ok?d({status:"downloaded",version:l.version,error:null,progress:100,command:`npm i -g ${c}@latest`,canDownload:!1}):d({status:"error",transient:!1,error:n.output.trim().split("\n").slice(-3).join(" ").trim()||"the installer failed",command:`${e.command} ${e.args.join(" ")}`})},quitAndInstall:()=>{"downloaded"===l.status&&(i||(()=>{try{const{app:e}=require("electron");e.relaunch(),e.exit(0)}catch{}}))()},start:()=>{_().catch((()=>{})),y=setInterval((()=>_().catch((()=>{}))),UPDATE_CHECK_INTERVAL_MS),y.unref&&y.unref()},stop:()=>{k(),y&&clearInterval(y),y=null},retryState:()=>({attempts:f,retryAt:m,inFlight:!!g,hasTimer:!!h})}}function createUpdateManager({isPackaged:e,onStatus:t}){let n={status:"idle",version:null,error:null,canDownload:!1};return createNpmUpdateManager({onStatus:function(e){n={...n,...e},t&&t(n)},packaged:Boolean(e)})}function createUpdateDispatch(e){return{checkForUpdates:()=>e.check({announce:!0}),downloadUpdate:()=>e.download(),quitAndInstallUpdate:()=>(e.quitAndInstall(),{ok:!0}),updateStatus:()=>Promise.resolve(e.status())}}function registerUpdateIpc(e,t){const n=createUpdateDispatch(t);for(const[t,r]of Object.entries(n))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>r(t)));return n}let resolveTargetWindow=null;function sendToAppWindow(e,t){const n="function"==typeof resolveTargetWindow?resolveTargetWindow():null,r=n&&!n.isDestroyed()?n:e.getFocusedWindow()||e.getAllWindows()[0];r&&!r.isDestroyed()&&r.webContents.send(t)}function sendDeepLinkToWindow(e,t){if(!e||e.isDestroyed()||!t)return;const n=()=>{e.isDestroyed()||e.webContents.send(DEEP_LINK_CHANNEL,t)};e.webContents.isLoadingMainFrame()?e.webContents.once("did-finish-load",n):n()}function buildAppMenu({app:e,Menu:t,BrowserWindow:n,updateManager:r,loggedIn:o}){const s="darwin"===process.platform;e.setAboutPanelOptions({applicationName:e.getName(),applicationVersion:e.getVersion(),version:e.getVersion()});const a={label:"Check for Updates…",click:()=>r.check({announce:!0})},i={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>sendToAppWindow(n,MENU_NEW_CHAT_CHANNEL)},c={label:"Search…",accelerator:"CmdOrCtrl+K",click:()=>sendToAppWindow(n,MENU_SEARCH_CHANNEL)},u={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToAppWindow(n,MENU_EXPORT_MARKDOWN_CHANNEL)},l={label:"Export Session…",click:()=>sendToAppWindow(n,MENU_EXPORT_JSON_CHANNEL)},d={label:"Authorship Panel…",click:()=>sendToAppWindow(n,MENU_FINGERPRINT_CHANNEL)},p={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToAppWindow(n,MENU_GOOGLE_DRIVE_CHANNEL)},f=[...s?[{label:e.getName(),submenu:[{role:"about"},a,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[i,{type:"separator"},u,l,{type:"separator"},...s?[]:[a,{type:"separator"}],s?{role:"close"}:{role:"quit"}]},{label:"Edit",submenu:[{role:"undo"},{role:"redo"},{type:"separator"},{role:"cut"},{role:"copy"},{role:"paste"},{role:"selectAll"}]},{label:"View",submenu:[c,{type:"separator"},d,p,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},...s?[]:[{label:"Help",submenu:[{role:"about"}]}]];return t.buildFromTemplate(f)}function bootstrap(){let e=!1;try{e=require("./lib/local/integrity.js").armed()}catch{e=!0,process.env.AEGIS_REDUCED_MODE="1",process.stderr.write("aegis-desktop: reduced mode (d1) — this build is not the one that was published.\n")}if(e){try{const{app:e}=electron;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:t,BrowserWindow:n,ipcMain:r,safeStorage:o,shell:s,Menu:a,Notification:i,screen:c,dialog:u,globalShortcut:l}=electron;try{let e;try{e=require("./vendor/selfhost.js")}catch{e=require("../one/src/selfhost.js")}const n=e.plan({packaged:t.isPackaged,execPath:process.execPath,resourcesPath:process.resourcesPath,argv:process.argv.slice(1),invokedAs:path.basename(process.argv[1]||process.execPath)});if(n){const r=e.spawnOptions(n,process.env),o=require("node:child_process").spawnSync(r.exec,r.args,{stdio:"inherit",env:r.env}),s="number"==typeof o.status?o.status:1;return void t.exit(s)}}catch(e){t.isPackaged&&!/MODULE_NOT_FOUND/.test(String(e&&e.message))&&process.stderr.write(`aegis: terminal face hand-off failed: ${e&&e.message||e}\n`)}if(t.disableHardwareAcceleration(),t.commandLine.appendSwitch("disable-gpu"),t.commandLine.appendSwitch("disable-software-rasterizer"),t.commandLine.appendSwitch("disable-gpu-compositing"),t.commandLine.appendSwitch("disable-features","UsePortalAccentColor"),process.argv.some((e=>/^--(log-level|enable-logging)/.test(e)))||process.env.ELECTRON_ENABLE_LOGGING||t.commandLine.appendSwitch("log-level","3"),!t.requestSingleInstanceLock())return void t.quit();if(t.setName("AEGIS Desktop"),envFile&&"function"==typeof envFile.loadEnvFile)try{const e=envFile.loadEnvFile();e.loose&&console.warn(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.`)}catch(e){console.warn(`aegis: could not read ${envFile.envFileFor()}: ${e&&e.message}`)}t.setAsDefaultProtocolClient(deepLink.PROTOCOL);let d=deepLink.parseDeepLinkArgv(process.argv);t.on("open-url",((e,t)=>{e.preventDefault();const n=deepLink.parseDeepLinkUrl(t);if(!n)return;const r="function"==typeof resolveTargetWindow?resolveTargetWindow():null;r&&!r.isDestroyed()?sendDeepLinkToWindow(r,n):d=n}));const p=createClient(credentials.clientOptions()),f=resolveUserDataDir(t),{engine:m,sessionsDir:h,settingsDir:g,settings:y}=createEngine(p,{app:t,safeStorage:o,dir:f}),E=createAccountKey({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>q(e)});let k=null;const _=createGoogleConnect({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),openUrl:e=>!!isSafeExternalUrl(e)&&(s.openExternal(e),!0),googleSignIn:googleSignIn,driveConnect:driveConnectLib,driveUpload:driveUploadLib,conversationExport:conversationExportLib?{...conversationExportLib,toTranscript:e=>sessionStore.toMarkdown(e)}:null,getSession:e=>sessionStore.getSession(h,e),getAuthor:()=>{try{k||(k=createFingerprintService({dir:f,getVaultBackend:()=>y.vaultBackendConfig().backend}));const e=k.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>q(E.status())}),v=Boolean(p.apiKey),A=autoProvision.autoProvisionApiKey(p,credentials,{app:"desktop"}).then((e=>{if(E.recordStartup(e),!e.key&&!p.apiKey){const t=e.error&&(e.error.status||e.error.message||String(e.error))||"no key returned";console.warn(`auto-provision: no account key from register-device (${t})`)}return e}));try{const{wrapProviderKeyMirror:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`);e(y,envFile,{onWarn:t}),m&&m.settings&&m.settings!==y&&e(m.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let b=null;const S=(e,t)=>{if(function(e){const t=e&&e.sender,r=t&&n.fromWebContents(t);if(!r||r.isDestroyed())return;if(r.isFocused()&&r.isVisible())return;if(!i||!i.isSupported())return;const o=new i({title:"AEGIS Desktop",body:"Reply ready"});o.on("click",(()=>{r.isDestroyed()||(r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus())})),o.show()}(e),b&&"function"==typeof b.note){const e=t&&(t.model||t.modelId)||void 0;b.note({sessionId:t&&t.sessionId||null,model:e})}};registerIpc(r,p,f,(e=>{const t=y.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t}),(e=>s.openExternal(e)),S,(()=>providerRouteConfigured(m)),(()=>y.vaultBackendConfig().backend));const w=registerModelIpc(r,m,h,p,S,void 0,g);registerConfirmModeIpc(r,withAutoRoundsSwitch(createConfirmModeDispatch(y),w.modelDispatch)),registerConfirmModeIpc(r,createVaultBackendDispatch(y)),registerTelemetryIpc(r,createTelemetryDispatch(createTelemetry({dir:g,enabled:telemetryEnabled(process.env,y),appVersion:(()=>{try{return"function"==typeof t.getVersion?t.getVersion():""}catch{return""}})()}))),registerCovenantIpc(r,createCovenantDispatch(covenantModule));const I=registerQueueIpc(r,{engine:createQueueEngine(p,y),aegis:p}),C=createAutoDrain({proceed:()=>I.proceed(),settings:y,queue:queueModule,env:process.env,log:e=>{e&&"skip"!==e.type&&console.log("[auto-drain]",e.type,e.reason||e.error||"")}});let R=null;b=createAutoMint({mint:e=>(R||(R=createFingerprintService({dir:f,getVaultBackend:()=>y.vaultBackendConfig().backend})),R.mint(e||{})),settings:y}),registerAutoIpc(r,createAutoDispatch({autoDrain:C,autoMint:b})),C.start(),b.start();let P=null,M=null;function T(){return M&&!M.isDestroyed()||(M=new n({width:560,height:320,show:!1,frame:!1,alwaysOnTop:!0,skipTaskbar:!0,resizable:!1,movable:!0,fullscreenable:!1,minimizable:!1,maximizable:!1,backgroundColor:"#0d1117",icon:iconForPlatform(resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),M.setMenuBarVisibility(!1),M.loadFile(path.join(__dirname,"renderer","quick.html")),M.webContents.on("before-input-event",((e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||M.isDestroyed()||M.hide()})),M.on("blur",(()=>{!M.isDestroyed()&&M.isVisible()&&M.hide()})),M.on("closed",(()=>{M=null}))),M}function D(){const e=T();e.isVisible()?e.hide():function(){const e=T(),t=c.getCursorScreenPoint(),n=c.getAllDisplays(),r=e.getBounds(),o=quickLauncherLib.computeQuickLauncherBounds({cursor:t,displays:n,size:{width:r.width,height:r.height}});e.setBounds(o),e.show(),e.focus()}()}resolveTargetWindow=()=>{if(P&&!P.isDestroyed())return P;const e=n.getFocusedWindow();return e&&!e.isDestroyed()&&e!==M?e:n.getAllWindows().find((e=>e!==M))||null};const N=createQuickLauncherDispatch(y,{isPackaged:t.isPackaged,applyConfig:function(e){if(l.unregisterAll(),!quickLauncherLib.shouldEnableGlobalShortcut({isPackaged:t.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!l.register(e.shortcut,D)){const t=`"${e.shortcut}" could not be registered — it may already be in use by another application.`;return console.warn(`[quick-launcher] ${t}`),{active:!1,reason:t}}return{active:!0,reason:null}}catch(t){const n=errorText(t);return console.warn(`[quick-launcher] failed to register shortcut "${e.shortcut}": ${n}`),{active:!1,reason:n}}},pushToMain:function(e,t){const r=t&&t.sender&&n.fromWebContents(t.sender);r&&!r.isDestroyed()&&r.hide();const o=P&&!P.isDestroyed()?P:n.getAllWindows().find((e=>e!==r))||null;return o?(o.webContents.send(QUICK_LAUNCHER_PUSH_CHANNEL,e||{}),o.isMinimized()&&o.restore(),o.isVisible()||o.show(),o.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(r,N);let U=null;t.on("will-quit",(()=>{U&&"function"==typeof U.stop&&U.stop(),l.unregisterAll(),O&&"function"==typeof O.stop&&O.stop()}));let L=!1;t.on("before-quit",(e=>{!L&&m&&"function"==typeof m.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then((()=>m.unloadLocalModels())).catch((()=>{})).finally((()=>{L=!0,t.quit()})))}));const F=new Set;function q(e){for(const t of F)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);x()}function x(){a.setApplicationMenu(buildAppMenu({app:t,Menu:a,BrowserWindow:n,updateManager:O,loggedIn:Boolean(p.apiKey)}))}const O=createUpdateManager({isPackaged:t.isPackaged,onStatus:function(e){for(const t of F)t.isDestroyed()||t.webContents.send(UPDATE_STATUS_CHANNEL,e)}});registerUpdateIpc(r,O),r.handle(`${IPC_PREFIX}accountStatus`,(()=>E.status())),r.handle(`${IPC_PREFIX}registerAccount`,(()=>E.registerAccount())),r.handle(`${IPC_PREFIX}driveSignIn`,(()=>_.signInWithGoogle())),r.handle(`${IPC_PREFIX}driveConnect`,(()=>_.connectDrive())),r.handle(`${IPC_PREFIX}driveStatus`,(()=>_.status())),r.handle(`${IPC_PREFIX}driveSyncMemory`,(()=>_.syncMemoryNow())),r.handle(`${IPC_PREFIX}driveBackupConversation`,((e,t)=>_.backupConversation({sessionId:t&&t.sessionId}))),registerExportIpc(r,sessionStore,h,(e=>u.showSaveDialog(n.getFocusedWindow(),e)),((e,t)=>fs.promises.writeFile(e,t,"utf8"))),x();const B=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function j(){const e=windowState.load(f),r=windowState.clampToDisplay(e,c.getAllDisplays(),{width:1080,height:720}),o=resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),a=new n({...r,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"AEGIS Desktop",icon:iconForPlatform(o,process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0}});e&&e.isMaximized&&a.maximize(),a.webContents.setWindowOpenHandler((({url:e})=>(isSafeExternalUrl(e)&&s.openExternal(e),{action:"deny"}))),a.webContents.on("will-navigate",((e,t)=>{t!==B&&(e.preventDefault(),isSafeExternalUrl(t)&&s.openExternal(t))}));let i=null;function u(){if(a.isDestroyed())return;const e=a.isMaximized(),t=e?a.getNormalBounds():a.getBounds();windowState.save(f,{...t,isMaximized:e})}function l(){i&&clearTimeout(i),i=setTimeout(u,500)}return a.on("resize",l),a.on("move",l),a.on("close",(()=>{i&&clearTimeout(i),u()})),a.loadFile(path.join(__dirname,"renderer","index.html")),F.add(a),P=a,a.on("closed",(()=>{F.delete(a),P===a&&(P=null)})),a}t.whenReady().then((async()=>{if(!credentials.normalizeApiKey(process.env[credentials.KEY_ENV])){const e=await A,t=startupKeyOverride({mintedKey:v?"":e.key,hostKey:credentials.normalizeApiKey(y.aegisRawKey())});if(t)credentials.saveApiKey(t),p.setApiKey(t);else{const e=credentials.preferNewest(y.aegisRawKey(),y.aegisKeySavedAt());e.key&&(p.setApiKey(e.key),"shared"===e.source&&y.setAegisKey(e.key))}}try{U&&"function"==typeof U.stop&&U.stop(),U=sharedPresence.createPresence({apiKey:p.apiKey,app:"desktop",version:t.getVersion(),platform:process.platform,install:sharedFingerprint.machineFingerprint(),queueDepth:()=>{try{return queueModule.readQueue(queueModule.queuePath()).filter((e=>e&&"pending"===e.status)).length}catch{return 0}},autonomous:!1,log:(e,t)=>{"debug"!==e&&console.warn(t)}}),U.start()}catch(e){console.warn("presence: beacon not started",e&&e.message)}try{const{backfillProviderKeys:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`),n=e(y,envFile,{onWarn:t});n.mirrored.length&&console.warn(`aegis: shared ${n.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),m&&m.settings&&m.settings!==y&&e(m.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}N.setConfig(y.quickLauncherConfig());const e=j();O.start(),d&&sendDeepLinkToWindow(e,d)})),t.on("window-all-closed",(()=>{"darwin"!==process.platform&&t.quit()})),t.on("activate",(()=>{const e=n.getAllWindows();if(0===e.length)return void j();const t=resolveTargetWindow()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()})),t.on("second-instance",((e,t)=>{const n=resolveTargetWindow(),r=deepLink.parseDeepLinkArgv(t);if(n)n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus(),r&&sendDeepLinkToWindow(n,r);else{const e=j();r&&sendDeepLinkToWindow(e,r)}}))}electron&&electron.app&&bootstrap(),module.exports={createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:IPC_PREFIX,MODEL_PREFIX:MODEL_PREFIX,SYNC_PREFIX:SYNC_PREFIX,watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:CHAT_DELTA_CHANNEL,MENU_NEW_CHAT_CHANNEL:MENU_NEW_CHAT_CHANNEL,MENU_SEARCH_CHANNEL:MENU_SEARCH_CHANNEL,MENU_EXPORT_MARKDOWN_CHANNEL:MENU_EXPORT_MARKDOWN_CHANNEL,MENU_EXPORT_JSON_CHANNEL:MENU_EXPORT_JSON_CHANNEL,MENU_FINGERPRINT_CHANNEL:MENU_FINGERPRINT_CHANNEL,MENU_GOOGLE_DRIVE_CHANNEL:MENU_GOOGLE_DRIVE_CHANNEL,DEEP_LINK_CHANNEL:DEEP_LINK_CHANNEL,UPDATE_STATUS_CHANNEL:UPDATE_STATUS_CHANNEL,UPDATE_CHECK_INTERVAL_MS:UPDATE_CHECK_INTERVAL_MS,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:PREVIEW_READ_MAX_BYTES,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:HEARTBEAT_RETRY_BASE_MS,HEARTBEAT_RETRY_MAX_MS:HEARTBEAT_RETRY_MAX_MS,createEngine:createEngine,resolveUserDataDir:resolveUserDataDir,importForeignMemory:importForeignMemory,isSafeExternalUrl:isSafeExternalUrl,createUpdateManager:createUpdateManager,createNpmUpdateManager:createNpmUpdateManager,createUpdateDispatch:createUpdateDispatch,describeRegistryFailure:describeRegistryFailure,UPDATE_RETRY_BACKOFF_MS:UPDATE_RETRY_BACKOFF_MS,registerUpdateIpc:registerUpdateIpc,buildAppMenu:buildAppMenu,createExportDispatch:createExportDispatch,registerExportIpc:registerExportIpc,safeExportBasename:safeExportBasename,sendDeepLinkToWindow:sendDeepLinkToWindow,QUICK_PREFIX:QUICK_PREFIX,QUICK_LAUNCHER_PUSH_CHANNEL:QUICK_LAUNCHER_PUSH_CHANNEL,createQuickLauncherDispatch:createQuickLauncherDispatch,registerQuickLauncherIpc:registerQuickLauncherIpc,createConfirmModeDispatch:createConfirmModeDispatch,createVaultBackendDispatch:createVaultBackendDispatch,withAutoRoundsSwitch:withAutoRoundsSwitch,createTelemetryDispatch:createTelemetryDispatch,registerTelemetryIpc:registerTelemetryIpc,createCovenantDispatch:createCovenantDispatch,registerCovenantIpc:registerCovenantIpc,registerConfirmModeIpc:registerConfirmModeIpc,QUEUE_PREFIX:QUEUE_PREFIX,QUEUE_PROGRESS_CHANNEL:QUEUE_PROGRESS_CHANNEL,QUEUE_MAX_TASK_CHARS:QUEUE_MAX_TASK_CHARS,QUEUE_MAX_ROUNDS:QUEUE_MAX_ROUNDS,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:AUTO_PREFIX,createAutoDispatch:createAutoDispatch,registerAutoIpc:registerAutoIpc};
|
|
6
|
+
,fingerprintPublish:e=>c.publish(e||{}),fingerprintAnchor:e=>c.anchor(e||{}),fingerprintVault:()=>c.vaultList(),fingerprintVaultAudit:()=>c.vaultAudit(),byokStatus:()=>e.byokStatus(),byokSet:t=>e.byokSet(t&&t.provider,t&&t.apiKey),memorySearch:r=>normalizeMemoryReadWithFallback(e.memorySearch(r&&r.query,r&&r.limit),memoryIndex(t),r&&r.query,r&&r.limit),memorySave:r=>saveMemoryWithQueue(e,t,r&&r.entry,s,memoryIndex(t)),memoryList:r=>normalizeMemoryReadWithFallback(e.memoryList(r&&r.limit),memoryIndex(t),"",r&&r.limit),verifyToken:t=>e.verifyToken(t&&t.token),memoryActivate:t=>e.memoryActivate(t&&t.token),memoryPull:r=>indexPulledMemory(e.memoryPull(r&&r.since),memoryIndex(t)),memorySaveBatch:t=>e.memorySaveBatch(t&&t.entries),memoryImport:r=>importForeignMemory(e,t,r,s,memoryIndex(t)),sessionsImportScan:()=>importForeignSessions(t,{confirm:!1}),sessionsImport:e=>importForeignSessions(t,e),importConversation:t=>e.importConversation(t||{}),openExternal:e=>{const t=e&&e.url;return isSafeExternalUrl(t)?Promise.resolve(u(t)).then((()=>({ok:!0})),(e=>({ok:!1,reason:errorText(e)}))):Promise.resolve({ok:!1,reason:"unsupported URL scheme"})}}}function withReplyNotify(e,t,r){return r?e.then((e=>(r(t,e),e))):e}function registerIpc(e,t,r,n,o,s,i,a){const c=createIpcDispatch(t,r,n,o,i,void 0,a);for(const[t,r]of Object.entries(c))"chatCompletion"!==t?e.handle(`${IPC_PREFIX}${t}`,((e,t)=>r(t))):e.handle(`${IPC_PREFIX}${t}`,((e,t)=>{const n={...t||{}};if(!n.stream)return withReplyNotify(r(n),e,s);const o=e&&e.sender;return withReplyNotify(r({...n,stream:!0,onStream:e=>{o&&"function"==typeof o.send&&!o.isDestroyed()&&o.send(CHAT_DELTA_CHANNEL,taggedChunk(e,n.sessionId))}}),e,s)}));return c}function createConfirmModeDispatch(e){if(!e)throw new Error("createConfirmModeDispatch requires a settings store");return{getConfirmMode:()=>({enabled:e.getConfirmMode()}),setConfirmMode:t=>{const r=t&&t.enabled;return"boolean"!=typeof r?{enabled:e.getConfirmMode()}:{enabled:e.setConfirmMode(r)}}}}function createPermissionModeDispatch(e){if(!e)throw new Error("createPermissionModeDispatch requires a settings store");return{getPermissionMode:()=>({mode:e.getPermissionMode()}),setPermissionMode:t=>{const r=t&&t.mode;return"plan"!==r&&null!=r?{mode:e.getPermissionMode()}:{mode:e.setPermissionMode("plan"===r?"plan":null)}}}}function withAutoRoundsSwitch(e,t){const r=e.setConfirmMode;return{...e,setConfirmMode:e=>{const n=r(e);return e&&"boolean"==typeof e.enabled&&t&&"function"==typeof t.setAutoRounds&&t.setAutoRounds(!1===e.enabled),n}}}function createPermRulesDispatch(e){if(!e)throw new Error("createPermRulesDispatch requires a rule store");const t=(e,t)=>{try{return e()}catch(e){return{...t,ok:!1,reason:e&&e.message||String(e)}}};return{permRulesList:()=>t((()=>e.listRules()),{}),permRulesAdd:r=>{const n=r&&r.list,o=r&&r.rule;return"string"!=typeof n||"string"!=typeof o?t((()=>e.listRules()),{reason:"a rule needs a list and a pattern"}):t((()=>e.addRule(n,o)),{})},permRulesRemove:r=>{const n=r&&r.list,o=r&&r.rule;return"string"!=typeof n||"string"!=typeof o?t((()=>e.listRules()),{reason:"a rule needs a list and a pattern"}):t((()=>e.removeRule(n,o)),{})}}}function createSandboxPolicyDispatch(e,t,r){if(!e)throw new Error("createSandboxPolicyDispatch requires a settings store");const n=t||{},o=(Array.isArray(n.MODES)?n.MODES:["off","read-only","workspace-write","managed"]).filter((e=>"managed"!==e)),s=r&&r.appDir,i=()=>{const t=e.getSandboxPolicy(),r=t&&o.includes(t.mode)?t.mode:"workspace-write",i=t&&"open"===t.network?"open":"restricted";let a=null,c=null,l=null;try{const e=(e=>{const t=n.detectCached||n.detect;if("function"!=typeof t||"function"!=typeof n.describe)return null;try{const r=t({appDir:s}),o=n.describe(r,e);return{mechanism:r&&(r.mechanism||(r.path?"bwrap":null))||null,enforced:Boolean(r&&r.available)&&"off"!==e.mode,sentence:"string"==typeof o?o:null}}catch{return{mechanism:null,enforced:null,sentence:null}}})("function"==typeof n.normalize?n.normalize(t,void 0):{mode:r,network:i});e&&({sentence:a,enforced:c,mechanism:l}=e)}catch{}return{ok:!0,mode:r,network:i,modes:o,stored:!!t,sentence:a,enforced:c,mechanism:l}};return{getSandboxPolicy:()=>i(),setSandboxPolicy:t=>{const r=t&&t.mode,a=t&&t.network;if("string"!=typeof r||!o.includes(r))return i();if(void 0!==a&&"open"!==a&&"restricted"!==a)return i();const c=e.getSandboxPolicy(),l=c&&c.fileSystem&&Array.isArray(c.fileSystem.entries)?{entries:c.fileSystem.entries}:{entries:[]},u=void 0===a?c&&"open"===c.network?"open":"restricted":a;try{e.setSandboxPolicy({mode:r,fileSystem:l,network:u})}catch{return i()}if("function"==typeof n.invalidateProbe)try{n.invalidateProbe(s)}catch{}return i()}}}function registerConfirmModeIpc(e,t){for(const[r,n]of Object.entries(t))e.handle(`${IPC_PREFIX}${r}`,((e,t)=>n(t)));return t}function createVaultBackendDispatch(e){if(!e)throw new Error("createVaultBackendDispatch requires a settings store");return{getVaultBackend:()=>e.vaultBackendConfig(),setVaultBackend:t=>e.setVaultBackendConfig(t&&t.backend)}}function createTelemetryDispatch(e){const t=e||null;return{telemetryEvent:e=>{try{if(!t||"function"!=typeof t.record)return{ok:!1,reason:"telemetry off"};const r=e&&"object"==typeof e?e:{};return t.record(r.event,{campaign:r.campaign,surface:r.surface})?{ok:!0}:{ok:!1,reason:"not an allowlisted funnel event"}}catch(e){return{ok:!1,reason:errorText(e)}}},telemetryReport:()=>{try{return t&&"function"==typeof t.report?t.report():{enabled:!1,transport:"off"}}catch(e){return{enabled:!1,error:errorText(e)}}}}}function createCovenantDispatch(e){return{covenantStatus:()=>({ok:!0,covenant:e.snapshot(),gapReport:e.gapReport()}),covenantGapReport:()=>({ok:!0,gapReport:e.gapReport()})}}function registerCovenantIpc(e,t){for(const[r,n]of Object.entries(t))e.handle(`${IPC_PREFIX}${r}`,((e,t)=>n(t)));return t}function registerTelemetryIpc(e,t){for(const[r,n]of Object.entries(t))e.handle(`${IPC_PREFIX}${r}`,((e,t)=>n(t)));return t}function safeExportBasename(e){return(e&&(e.title||e.id)||"session").replace(/[^\w.-]+/g,"_").slice(0,80)||"session"}function createExportDispatch(e,t,r,n){return{exportSession:async o=>{const s=o&&o.sessionId,i=o&&"json"===o.format?"json":"markdown",a=s?e.getSession(t,s):null;if(!a)return{ok:!1,reason:"session not found"};const c="json"===i?e.toJson(a):e.toMarkdown(a),l="json"===i?"json":"md",u="json"===i?[{name:"JSON",extensions:["json"]}]:[{name:"Markdown",extensions:["md"]}],d=await r({defaultPath:`${safeExportBasename(a)}.${l}`,filters:u});if(!d||d.canceled||!d.filePath)return{ok:!1,canceled:!0};try{await n(d.filePath,c)}catch(e){return{ok:!1,reason:errorText(e)}}return{ok:!0,filePath:d.filePath}}}}function registerExportIpc(e,t,r,n,o){const s=createExportDispatch(t,r,n,o);for(const[t,r]of Object.entries(s))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>r(t)));return s}function createQuickLauncherDispatch(e,t={}){const r=Boolean(t.isPackaged),n=t.applyConfig||(()=>({active:!1,reason:null})),o=t.pushToMain||(()=>({ok:!1,reason:"no main window"}));let s={active:!1,reason:null};return{status:function(){return{...e.quickLauncherConfig(),packaged:r,...s}},setConfig:function(t){const o=e.setQuickLauncherConfig({enabled:t&&t.enabled,shortcut:t&&t.shortcut});return s=n(o)||{active:!1,reason:null},{...o,packaged:r,...s}},pushToMain:(e,t)=>o(e,t)}}function registerQuickLauncherIpc(e,t){for(const[r,n]of Object.entries(t))"pushToMain"!==r?e.handle(`${QUICK_PREFIX}${r}`,((e,t)=>n(t))):e.handle(`${QUICK_PREFIX}${r}`,((e,t)=>n(t,e)));return t}function resolveUserDataDir(e){if(e&&"function"==typeof e.getPath)try{return e.getPath("userData")}catch{}try{const e=require("../one/src/iface/paths.js").plan({platform:process.platform,env:process.env});if(e&&e.ok)return e.state}catch{}return path.join(os.homedir(),".aegiscode")}function createEngine(e,{app:t,safeStorage:r,dir:n,sessionsDir:o}={}){const s=n||resolveUserDataDir(t),i=createSettingsStore({dir:s,safeStorage:r});return i.migrateLegacyAegisKey(),{engine:createLocalEngine({aegis:e,settings:i,sandbox:{policy:i.getSandboxPolicy(),strict:!1,appDir:__dirname},permissionRules:{rulesVerdict:require("./lib/local/perm-rules.js").rulesVerdict,subjectFor:require("./lib/local/perm-rules.js").subjectFor,alwaysAllow:require("./lib/local/perm-write.js").alwaysAllow}}),sessionsDir:o||sessionStore.resolveStoreDir(s),settingsDir:s,settings:i}}const PREVIEW_READ_MAX_BYTES=524288;function readTextFileForPreview(e){try{const t=e&&"string"==typeof e.file?e.file:"",r=e&&"string"==typeof e.cwd?e.cwd:"";if(!t||!r||!path.isAbsolute(r))return null;const n=fs.realpathSync(r),o=fs.realpathSync(path.resolve(n,t)),s=path.relative(n,o);if(""===s||s.startsWith("..")||path.isAbsolute(s))return null;const i=fs.statSync(o);if(!i.isFile())return null;if(i.size<=PREVIEW_READ_MAX_BYTES)return{text:fs.readFileSync(o,"utf8"),truncated:!1};const a=fs.openSync(o,"r");try{const e=Buffer.alloc(PREVIEW_READ_MAX_BYTES),t=fs.readSync(a,e,0,PREVIEW_READ_MAX_BYTES,0);let r=e.toString("utf8",0,t);const n=r.lastIndexOf("\n");return n>0&&(r=r.slice(0,n+1)),{text:r,truncated:!0}}finally{fs.closeSync(a)}}catch{return null}}const attachmentsModule=require("./lib/local/attachments.js");function nativeImageResizer(e,t){try{const{nativeImage:r}=require("electron");if(!r)return null;const n=r.createFromBuffer(e);if(!n||n.isEmpty())return null;const o=n.getSize(),s=Math.max(o.width,o.height),i=s>1568?n.resize({width:Math.round(1568*o.width/s)}):n,a="image/png"===t?i.toPNG():i.toJPEG(82);return a&&a.length?{buffer:a,mime:"image/png"===t?"image/png":"image/jpeg"}:null}catch{return null}}function ingestAttachment(e,{resize:t=nativeImageResizer}={}){const r=e&&"string"==typeof e.path?e.path.trim():"";if(!r)return{ok:!1,reason:"no path"};if(!path.isAbsolute(r))return{ok:!1,reason:"not an absolute path"};let n,o,s;try{n=fs.realpathSync(r),o=fs.statSync(n)}catch{return{ok:!1,reason:"not found"}}if(!o.isFile())return{ok:!1,reason:"not a regular file"};if(0===o.size)return{ok:!1,reason:"empty file"};if(o.size>attachmentsModule.MAX_FILE_BYTES)return{ok:!1,reason:`too large (${attachmentsModule.humanBytes(o.size)})`};try{s=fs.readFileSync(n)}catch{return{ok:!1,reason:"unreadable"}}const i=attachmentsModule.sniff(s),a={path:n,name:path.basename(n),size:o.size,mime:i.mime,kind:i.kind};if("image"===i.kind){let{mime:e}=i,r=s,n=!1;if(r.length>attachmentsModule.MAX_IMAGE_BYTES&&"function"==typeof t){const o=t(s,e);o&&o.buffer&&o.buffer.length<r.length&&(r=o.buffer,e=o.mime,n=!0)}const o=attachmentsModule.toDataUrl(r,e);return o?{ok:!0,attachment:{...a,kind:"image",mime:e,size:r.length,dataUrl:o,scaled:n,vision:attachmentsModule.isVisionMime(e)}}:{ok:!1,reason:"could not encode image"}}if("text"===i.kind){if(o.size>attachmentsModule.MAX_TEXT_BYTES){let e=s.subarray(0,attachmentsModule.MAX_TEXT_BYTES).toString("utf8");const t=e.lastIndexOf("\n");return t>0&&(e=e.slice(0,t+1)),{ok:!0,attachment:{...a,kind:"text",text:e,truncated:!0}}}return{ok:!0,attachment:{...a,kind:"text",text:s.toString("utf8"),truncated:!1}}}return"pdf"===i.kind?{ok:!0,attachment:{...a,kind:"pdf"}}:{ok:!0,attachment:{...a,kind:"binary"}}}function createModelDispatch(e,{env:t=process.env,settings:r}={}){const n=new Map;let o,s=autoRoundsDefault(t),i=!1;const a=()=>{const t=r||e&&e.settings||null,n=e=>"boolean"==typeof e?e:void 0;let a;try{if(t&&"function"==typeof t.confirmModeState){const e=t.confirmModeState();a=n(e&&e.enabled)}void 0===a&&t&&"function"==typeof t.getConfirmMode&&(a=n(t.getConfirmMode()))}catch{}return i||void 0===a||(void 0===o?o=a:a!==o&&(i=!0,s=!0)),!(!s||!t||void 0===a)&&!1===a},c={listClasses:async()=>(await e.listClasses()).filter((e=>DESKTOP_CLASSES.includes(e.class))),listModels:t=>e.listModels(t&&t.class),chat:r=>{const o=r&&r.onStream;if("function"!=typeof o)return e.chat(r,o);const s=r&&r.sessionId||"";return e.chat(r,(r=>{if(r&&r.rounds&&r.rounds.id&&a()){const i=autoContinuePlan({on:!0,used:n.get(s)||0,limit:autoContinueLimit(t)});if(n.set(s,i.used),i.auto){const t="function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(r.rounds.id,!0):{ok:!1};if(t&&t.ok){const e=Number(r.rounds.spent)||0;return void o({note:`auto mode: the ${e}-round limit was reached — continuing automatically (${i.used}/${i.cap}, then it asks).`})}}}o(r)}))},"settings.get":()=>e.settings.list().filter((e=>!(e&&isReservedNamespace(e.provider)))),"settings.set":t=>e.settings.set(t&&t.provider,{baseURL:t&&t.baseURL,key:t&&t.key}),"settings.remove":t=>e.settings.remove(t&&t.provider),"userModels.get":()=>e.userModels(),"userModels.add":t=>e.addUserModel(t&&t.provider,t&&t.model),"userModels.remove":t=>e.removeUserModel(t&&t.provider,t&&t.model),"userModels.discover":t=>e.discoverModels(t&&t.provider),"userModels.addAll":t=>e.addUserModels(t&&t.provider,t&&t.ids),"userModels.canDiscover":t=>Boolean(e.canDiscoverModels(t&&t.provider)),"userModels.discoverable":()=>e.discoverableProviders(),"memoryPersist.get":()=>e.settings.memoryPersistState(),"memoryPersist.set":t=>e.settings.setMemoryPersist(Boolean(t&&t.enabled)),cancel:t=>e.cancel(t&&t.sessionId),respondApproval:t=>e.respondApproval(t&&t.approvalId,t&&t.decision),respondRoundsAsk:t=>"function"==typeof e.respondRoundsAsk?e.respondRoundsAsk(t&&t.roundsAskId,t&&t.decision):{ok:!1},clearApprovals:t=>e.clearSessionApprovals(t&&t.sessionId),listUndoable:t=>"function"==typeof e.listUndoable?e.listUndoable(t&&t.sessionId):[],undoMutation:t=>"function"==typeof e.undoMutation?e.undoMutation(t&&t.sessionId,t&&t.id):{ok:!1,error:"undo is not available on this engine"}};return Object.defineProperties(c,{autoRoundsOn:{value:a,enumerable:!1},setAutoRounds:{value:e=>{s=Boolean(e),i=!0},enumerable:!1}}),c}function createSyncDispatch(e,t,r,n,o){let s=null;function i(){return Boolean(r&&r.apiKey)}async function a(){const n=e.listPending(t);if(!i())return{ok:!1,queued:n.length,reason:"no AEGIS key configured"};const o=await async function(){const e=memoryQueue.listQueued(t);if(!e.length)return{flushed:0,remaining:0,upgrade:null};const n=[];let o=0,s=null;for(let i=0;i<e.length;i+=1)try{await r.memorySave(e[i]),o+=1;const n=memoryIndex(t);if(n)try{n.upsert(e[i])}catch{}}catch(t){const r=upgradeInfo(t);if(r){s=r,n.push(...e.slice(i));break}n.push(e[i])}return memoryQueue.save(t,n),{flushed:o,remaining:n.length,upgrade:s}}();if(!n.length)return{ok:!0,queued:0,pushed:0,memoryFlushed:o.flushed,upgrade:o.upgrade};let a=0,c=null,l=null;for(const o of n)try{const n=await r.conversationSyncPush({session_id:o.id,title:o.title,messages:o.messages}),s=n&&(n.session_id||n.id);e.markSynced(t,o.id,{remoteId:s}),a+=1}catch(e){if(c=e,l=describeSyncError(e),"quota"===l.kind||"auth"===l.kind)break}const u=e.listPending(t).length;a&&(s=Date.now());const d=(c?upgradeInfo(c):null)||o.upgrade;return 0===a&&c?{ok:!1,queued:u,reason:syncErrorReason(l),failed:l?[l]:[],kind:l?l.kind:"error",status:l?l.status:0,hint:l?l.hint:null,memoryFlushed:o.flushed,upgrade:d}:{ok:!0,queued:u,pushed:a,failed:l?[l]:[],memoryFlushed:o.flushed,upgrade:d}}const c=persistGate.createAutoPush({push:a,dir:n||t});return{auto:()=>c.auto(),memoryPersistState:()=>c.gate(),listSessions:()=>({sessions:e.listSessions(t)}),searchSessions:r=>{const n=r&&"string"==typeof r.query?r.query:"",o=Number.isInteger(r&&r.limit)?r.limit:50,s=e.listSessions(t)||[],i=sessionSearch.rankSessions(n,s).slice(0,Math.max(1,o));return{query:n,total:s.length,sessions:i.map((e=>({id:e&&e.id,title:e&&e.title||e&&e.id||"untitled",updatedAt:e&&e.updatedAt||null,messages:e&&Array.isArray(e.messages)?e.messages.map((e=>({role:e&&e.role,content:"string"==typeof(e&&e.content)?e.content.slice(0,400):""}))):[],reason:sessionSearch.matchReason(n,e)})))}},open:r=>e.getSession(t,r&&r.sessionId),save:r=>e.upsertSession(t,r||{}),append:r=>e.appendMessage(t,r&&r.sessionId,r&&r.message),delete:r=>e.deleteSession(t,r&&r.sessionId),nameSession:async r=>{const n=r&&r.sessionId,s=r&&r.prompt;if(!n||!String(null==s?"":s).trim())return null;let i;for(const e of["../client/naming.js","./vendor/naming.js","./vendor/client/naming.js"])try{i=require(e);break}catch{}if(!i)return null;const a=async(e,t={})=>{if(!o||"function"!=typeof o.chat)return null;try{const s=await o.chat({class:r&&r.class||"model",model:r&&r.model,prompt:e,system:t.system,maxTokens:64,sessionId:n,tools:!1}),i=s&&s.choices&&s.choices[0]||{};return i.message&&i.message.content||null}catch{return null}};try{return await i.nameSession(e,t,n,s,{callModel:a})}catch{return null}},push:a,pull:async function(){if(!i())return{ok:!1,merged:0,reason:"no AEGIS key configured"};try{const n=await r.conversationSyncPull(),o=e.mergeRemoteSessions(t,n&&n.sessions||[]);return s=Date.now(),{ok:!0,merged:o,failed:[],upgrade:null}}catch(e){const t=describeSyncError(e);return{ok:!1,merged:0,reason:syncErrorReason(t),failed:[t],kind:t.kind,status:t.status,hint:t.hint,upgrade:upgradeInfo(e)}}},status:()=>({count:e.listSessions(t).length,pending:e.listPending(t).length,cloud:i(),lastSyncAt:s})}}const HEARTBEAT_RETRY_BASE_MS=5e3,HEARTBEAT_RETRY_MAX_MS=3e4;function createHeartbeatRetry(e,t={}){const r="function"==typeof t.now?t.now:()=>Date.now(),n=Number(t.baseMs)>0?Number(t.baseMs):HEARTBEAT_RETRY_BASE_MS,o=Number(t.maxMs)>0?Number(t.maxMs):HEARTBEAT_RETRY_MAX_MS;let s=0,i=0,a=null,c=!1;function l(e){s+=1;const t=Math.min(o,n*2**Math.max(0,s-1));return a=e||"push failed",i=r()+t,{attempted:!0,ok:!1,error:a,failures:s,retryInMs:t}}return{run:async function(){const t=r();if(s>0&&t<i)return{attempted:!1,ok:!1,error:a,failures:s,retryInMs:i-t};if(c)return{attempted:!1,ok:!1,error:a,failures:s,retryInMs:0};c=!0;try{const t=await e();return t&&!1===t.ok?l(t.reason||t.kind||"push failed"):(s=0,i=0,a=null,{attempted:!0,ok:!0,error:null,failures:0,retryInMs:0,result:t})}catch(e){return l(errorText(e))}finally{c=!1}},state:function(){const e=r();return{failures:s,lastError:a,retryInMs:s>0&&i>e?i-e:0}},recordFailure:e=>l(errorText(e))}}function registerModelIpc(e,t,r,n,o,s,i){const a=createModelDispatch(t),c=createSyncDispatch(sessionStore,r,n,i,a),l=createHeartbeatRetry((()=>c.push()),s);function u(){const e=l.run();e&&"function"==typeof e.catch&&e.catch((e=>l.recordFailure(e)))}for(const[t,r]of Object.entries(a))"chat"!==t?"listModels"!==t?e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>r(t))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>(u(),r(t)))):e.handle(`${MODEL_PREFIX}${t}`,((e,t)=>{const n={...t||{}},s=!0===n.bestEffort;delete n.bestEffort;const i="low"===n.effort||"medium"===n.effort||"max"===n.effort?n.effort:"high";n.effort=i;const a=e&&e.sender,c=n.class||"model",l=r({...n,onStream:e=>{a&&"function"==typeof a.send&&!a.isDestroyed()&&a.send(CHAT_DELTA_CHANNEL,taggedChunk(e,n.sessionId))}});return s?l.then((t=>(o&&o(e,t),t)),(e=>{const t=e&&"number"==typeof e.status?e.status:0,r=e&&e.code||"";return console.warn(`[model] background ${c} turn produced no answer: ${errorText(e)}${t?` (status ${t})`:""}${r?` [${r}]`:""}`),{bestEffortFailed:!0,status:t,code:r||void 0,message:errorText(e),choices:[{message:{content:""}}]}})):withReplyNotify(l,e,o).catch((e=>{if(!isAbortShapedError(e))throw e;return console.warn(`[model] ${c} turn stopped before it finished: ${errorText(e)} [ABORT_ERR]`),abortedTurnPayload(e)}))}));e.on(`${MODEL_PREFIX}readTextFile`,((e,t)=>{e.returnValue=readTextFileForPreview(t)})),e.handle(`${IPC_PREFIX}attachments:ingest`,(async(e,t)=>ingestAttachment(t)));for(const[t,r]of Object.entries(c))"status"!==t?e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>r(t))):e.handle(`${SYNC_PREFIX}${t}`,((e,t)=>{u();const n=r(t);return n&&"object"==typeof n?{...n,retry:l.state()}:n}));return{modelDispatch:a,syncDispatch:c,heartbeat:l}}function createQueueEngine(e,t){return createLocalEngine({aegis:e,settings:t,getConfirmMode:()=>!1})}function queueEngineWithDeniedApprovals(e){return e&&"function"==typeof e.chat?{...e,chat:(t,r)=>e.chat(t,(t=>{(t=>{const r=t&&t.approval;if(r&&r.id&&"function"==typeof e.respondApproval)try{e.respondApproval(r.id,"deny")}catch{}})(t),(t=>{const r=t&&t.rounds;if(r&&r.id&&"function"==typeof e.respondRoundsAsk)try{e.respondRoundsAsk(r.id,!1)}catch{}})(t),"function"==typeof r&&r(t)}))}:e}function isExistingDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function clampInt(e,t,r){const n=Number(e);return!Number.isInteger(n)||n<t||n>r?null:n}function createQueueDispatch({engine:e,env:t=process.env,queue:r=queueModule,autonomous:n=autonomousModule,entitlement:o=entitlementModule.createEntitlement({}),log:s=(()=>{})}={}){if(!e||"function"!=typeof e.chat)throw new Error("createQueueDispatch: a local engine with chat() is required");let i=null,a=!1,c=!1;const l=n.createQueueWorker({engine:queueEngineWithDeniedApprovals(e),env:t,log:e=>{e&&"start"===e.type&&(i=e.taskId),e&&"finish"===e.type&&(i=null),s(e)},canFanOut:()=>o.current().entitled});function u(){const e=r.loadQueue(t);return{ok:!0,items:e,pending:r.pendingCount(e),running:e.find((e=>e&&"running"===e.status))||null,draining:c,stopping:a,defaultCwd:process.cwd(),defaultModel:n.resolveModel({env:t}),queueFile:r.queuePath(t),runs:r.readRuns(t,{limit:20}),entitlement:o.current()}}const d=e=>(e||[]).map((e=>({id:e.id,ok:Boolean(e.ok),error:e.error||null})));return{enqueue:async e=>{await o.refresh();const s=o.gateFanout({workers:clampInt(e&&e.workers,1,QUEUE_MAX_WORKERS),fanout:Boolean(e&&!0===e.fanout)});if(!s.ok)return{...s,...u()};const{opts:i,error:a}=function(e){const t=e||{},r=String(null==t.task?"":t.task).trim();if(!r)return{error:"a queued task needs text"};if(r.length>QUEUE_MAX_TASK_CHARS)return{error:`task text is too long (${r.length} > ${QUEUE_MAX_TASK_CHARS} chars)`};const o=String(null==t.cwd?"":t.cwd).trim()||process.cwd();if(!path.isAbsolute(o))return{error:"the working directory must be an absolute path"};if(!isExistingDir(o))return{error:`not a directory: ${o}`};const s=n.normalizeClass(t.class),i=String(null==t.model?"":t.model).trim().slice(0,120)||null,a=n.modelRefusal(i,s);if(a)return{error:a};const c=String(null==t.effort?"":t.effort).trim().toLowerCase();return{opts:{task:r,cwd:o,class:s,model:i,effort:QUEUE_EFFORTS.has(c)?c:null,workers:clampInt(t.workers,1,QUEUE_MAX_WORKERS),maxRounds:clampInt(t.maxRounds,1,QUEUE_MAX_ROUNDS),singlePass:!(!0===t.fanout||!0===t.autonomous),commit:Boolean(t.commit),source:"desktop"}}}(e);return a?{ok:!1,reason:a,...u()}:{ok:!0,item:r.addTask(t,i),...u()}},list:()=>u(),entitlement:async e=>(await o.refresh({force:Boolean(e&&!0===e.force)}),{ok:!0,...u()}),clear:e=>({...r.clearQueue(t,{all:Boolean(e&&e.all)}),ok:!0,...u()}),retry:e=>{const n=e&&e.id,o=r.retryTask(t,n);return o?{ok:!0,item:o,...u()}:{ok:!1,reason:`no task #${n}`,...u()}},remove:e=>{const n=e&&e.id,o=r.loadQueue(t),s=r.findTask(o,n);return s?"running"===s.status?{ok:!1,reason:`task #${s.id} is running — stop the drain first`,...u()}:(r.saveQueue(t,o.filter((e=>Number(e&&e.id)!==Number(s.id)))),{ok:!0,removed:s.id,...u()}):{ok:!1,reason:`no task #${n}`,...u()}},drain:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...u()};let e;c=!0,a=!1;try{const t=await l.proceed({max:1});e=t.locked?{ok:!1,locked:!0,holder:t.holder,ran:[]}:{ok:!0,ran:d(t.ran)}}catch(t){e={ok:!1,reason:errorText(t),ran:[]}}return c=!1,i=null,{...e,...u()}}(),proceed:()=>async function(){if(c)return{ok:!1,reason:"a drain is already running in this window",...u()};c=!0,a=!1;const e=[];let t;try{for(;;){const r=await l.proceed({max:1});if(r.locked){t={ok:!1,locked:!0,holder:r.holder,ran:d(e)};break}if(!r.ran.length){t={ok:!0,stopped:a,ran:d(e)};break}if(e.push(...r.ran),a){t={ok:!0,stopped:!0,ran:d(e)};break}}}catch(r){t={ok:!1,reason:errorText(r),ran:d(e)}}return c=!1,i=null,{...t,...u()}}(),stop:e=>{a=!0;const t=e&&null!=e.id?e.id:i,r=null==t?null:l.cancel(t);return{ok:!0,wasDraining:c,cancelled:r,...u()}}}}function createAutoDispatch({autoDrain:e,autoMint:t}={}){if(!e||"function"!=typeof e.state)throw new Error("createAutoDispatch: the auto-drain automation is required");if(!t||"function"!=typeof t.state)throw new Error("createAutoDispatch: the auto-mint automation is required");return{autoStatus:()=>({ok:!0,drain:e.state(),mint:t.state()}),autoSetDrain:t=>{const r=t||{},n={};null!=r.enabled&&(n.enabled=Boolean(r.enabled)),null!=r.intervalMs&&(n.intervalMs=Number(r.intervalMs));try{return{ok:!0,drain:e.set(n)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSetMint:e=>{const r=e||{},n={};null!=r.enabled&&(n.enabled=Boolean(r.enabled)),null!=r.publish&&(n.publish=Boolean(r.publish));try{return{ok:!0,mint:t.set(n)}}catch(e){return{ok:!1,error:errorText(e)}}},autoSealNow:async e=>{const r=e||{};null!=r.publish&&t.set({publish:Boolean(r.publish)});try{const e=await t.flush();return t.reset(),{ok:!0,...e}}catch(e){return t.reset(),{ok:!1,error:errorText(e)}}}}}function registerQueueIpc(e,{engine:t,env:r,queue:n,autonomous:o,entitlement:s,aegis:i}={}){let a=null;const c=createQueueDispatch({engine:t,env:r,queue:n,autonomous:o,entitlement:s||entitlementModule.createEntitlement({probe:i&&"function"==typeof i.verifyApiKey?async()=>{const e=await i.verifyApiKey(),t=e&&"object"==typeof e?{...e}:{};if("function"==typeof i.tokenBankBalance)try{const e=await i.tokenBankBalance();e&&"object"==typeof e&&(null!=e.balance_micros?t.balance_micros=e.balance_micros:null!=e.balance_eur&&(t.balance_eur=e.balance_eur))}catch{}return t}:void 0}),log:e=>{a&&"function"==typeof a.send&&("function"==typeof a.isDestroyed&&a.isDestroyed()||a.send(QUEUE_PROGRESS_CHANNEL,e))}});for(const[t,r]of Object.entries(c))e.handle(`${QUEUE_PREFIX}${t}`,((e,t)=>(a=e&&e.sender||null,r(t))));return c}function registerAutoIpc(e,t){for(const[r,n]of Object.entries(t))e.handle(`${AUTO_PREFIX}${r}`,((e,t)=>n(t)));return t}const UPDATE_STATUS_CHANNEL=`${IPC_PREFIX}updateStatus`,ACCOUNT_STATUS_CHANNEL=`${IPC_PREFIX}accountStatusChanged`,UPDATE_CHECK_INTERVAL_MS=144e5,UPDATE_RETRY_BACKOFF_MS=[6e4,3e5,9e5,36e5];function describeRegistryFailure(e,t,r){switch(e){case"not-found":return`${r} is not published on the npm registry (404)`;case"forbidden":return`the npm registry refused the request (${t||"auth"})`;case"malformed":return"the npm registry sent a response this app could not read";case"too-large":return"the npm registry response was too large to read";case"timeout":return"the npm registry did not respond in time";case"network":return"the npm registry could not be reached";default:return"the update check did not complete"}}function createNpmUpdateManager({onStatus:e,packaged:t=!1,now:r=(()=>Date.now()),fetchImpl:n,setTimeoutImpl:o=setTimeout,clearTimeoutImpl:s=clearTimeout,runUpgrade:i,relaunch:a}={}){const c="aegis-desktop";let l="unknown";try{l=require("./package.json").version}catch{}let u={status:"idle",version:null,error:null,channel:"npm",reason:null,transient:!1,attempts:0,retryInMs:0,command:null,plan:null,method:null,canDownload:!1};const d=t=>(u={...u,...t},e&&e(u),u);let p=null;try{p=require("../client/update.js")}catch{try{p=require("./vendor/update.js")}catch{p=null}}let m=0,f=0,h=null,g=null,y=null,E=null;function k(){h&&s(h),h=null}async function _({announce:e=!1}={}){if(!p)return d({status:"disabled",error:"update checker unavailable"});if(g)return g;g=(async()=>{const s=u.status,i=u.version;let a;d({status:"checking",error:null,reason:null,transient:!1});try{a=await async function(){if(n)return n({pkg:c});if(p&&"function"==typeof p.checkPublished){const e=await p.checkPublished({current:l,pkg:c,now:r(),intervalMs:0});return e?{ok:e.ok,latest:e.latest,reason:e.reason,status:e.status}:{ok:!1,latest:null,reason:"unknown",status:null}}return{ok:!1,latest:null,reason:"unavailable",status:null}}()}catch(e){a={ok:!1,latest:null,reason:"unknown",status:null,error:errorText(e)}}if(a.ok){if(m=0,f=0,k(),!p.isNewer(a.latest,l))return d({status:"up-to-date",version:a.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0});const e=function(){if(E)return E;const e=p&&p.detectInstallMethod;if("function"!=typeof e)return E="npm",E;try{E=e({env:process.env,argv:process.argv,pkg:c,entry:__dirname,fileExists:e=>fs.existsSync(path.resolve(__dirname,"..",e))})}catch{E="npm"}return E}(),r="function"==typeof p.updatePlan?p.updatePlan({current:l,latest:a.latest,behind:!0,channel:"npm",pkg:c,method:e}):null;return d({status:"available",version:a.latest,error:null,reason:null,transient:!1,attempts:0,retryInMs:0,plan:r,method:e,command:t?`${a.latest} is published — reinstall AEGIS Desktop from the installer to pick it up`:r&&r.instruction||`npm i -g ${c}@latest`,commandIsSentence:t||Boolean(r&&!r.apply),canDownload:Boolean(r&&r.apply)&&!t})}m+=1;const g=a.error||describeRegistryFailure(a.reason,a.status,c);return y=a.reason,b=a.status,("function"==typeof p.isTransientReason?p.isTransientReason(y,b):"unknown"===y)?(function(){k();const e=UPDATE_RETRY_BACKOFF_MS[Math.min(Math.max(m-1,0),UPDATE_RETRY_BACKOFF_MS.length-1)];f=r()+e,h=o((()=>{h=null,_().catch((()=>{}))}),e),h&&h.unref&&h.unref(),d({retryInMs:e})}(),d(e?{status:"error",error:g,reason:a.reason,transient:!0,attempts:m}:{status:"available"===s?"available":"unavailable",version:i,error:g,reason:a.reason,transient:!0,attempts:m})):(k(),f=0,d({status:"error",error:g,reason:a.reason,transient:!1,attempts:m,retryInMs:0}));var y,b})();try{return await g}finally{g=null}}return{status:()=>u,check:_,download:async()=>{const e=!t&&u.plan&&u.plan.apply;if(!e)return d({status:"available"===u.status?"available":u.status,command:u.plan&&u.plan.instruction||u.command,canDownload:!1});d({status:"downloading",error:null,progress:0});const r=await function(e){const t=i||((e,t)=>new Promise((r=>{execFile(e,t,{timeout:18e4,windowsHide:!0},((e,t,n)=>{if(e)return r({ok:!1,output:String(n||t||e.message||e)});r({ok:!0,output:String(t||"")})}))}))),r=!i&&p&&"function"==typeof p.installSpawn?p.installSpawn(e,{env:process.env}):null,n=r?r.command:e.command,o=r?r.args:e.args;return Promise.resolve(t(n,o)).then((e=>({ok:Boolean(e&&e.ok),output:String(e&&e.output||"")})),(e=>({ok:!1,output:errorText(e)})))}(e);return r.ok?d({status:"downloaded",version:u.version,error:null,progress:100,command:`npm i -g ${c}@latest`,canDownload:!1}):d({status:"error",transient:!1,error:r.output.trim().split("\n").slice(-3).join(" ").trim()||"the installer failed",command:`${e.command} ${e.args.join(" ")}`})},quitAndInstall:()=>{"downloaded"===u.status&&(a||(()=>{try{const{app:e}=require("electron");e.relaunch(),e.exit(0)}catch{}}))()},start:()=>{_().catch((()=>{})),y=setInterval((()=>_().catch((()=>{}))),UPDATE_CHECK_INTERVAL_MS),y.unref&&y.unref()},stop:()=>{k(),y&&clearInterval(y),y=null},retryState:()=>({attempts:m,retryAt:f,inFlight:!!g,hasTimer:!!h})}}function createUpdateManager({isPackaged:e,onStatus:t}){let r={status:"idle",version:null,error:null,canDownload:!1};return createNpmUpdateManager({onStatus:function(e){r={...r,...e},t&&t(r)},packaged:Boolean(e)})}function createUpdateDispatch(e){return{checkForUpdates:()=>e.check({announce:!0}),downloadUpdate:()=>e.download(),quitAndInstallUpdate:()=>(e.quitAndInstall(),{ok:!0}),updateStatus:()=>Promise.resolve(e.status())}}function registerUpdateIpc(e,t){const r=createUpdateDispatch(t);for(const[t,n]of Object.entries(r))e.handle(`${IPC_PREFIX}${t}`,((e,t)=>n(t)));return r}let resolveTargetWindow=null;function sendToAppWindow(e,t){const r="function"==typeof resolveTargetWindow?resolveTargetWindow():null,n=r&&!r.isDestroyed()?r:e.getFocusedWindow()||e.getAllWindows()[0];n&&!n.isDestroyed()&&n.webContents.send(t)}function sendDeepLinkToWindow(e,t){if(!e||e.isDestroyed()||!t)return;const r=()=>{e.isDestroyed()||e.webContents.send(DEEP_LINK_CHANNEL,t)};e.webContents.isLoadingMainFrame()?e.webContents.once("did-finish-load",r):r()}function buildAppMenu({app:e,Menu:t,BrowserWindow:r,updateManager:n,loggedIn:o}){const s="darwin"===process.platform;e.setAboutPanelOptions({applicationName:e.getName(),applicationVersion:e.getVersion(),version:e.getVersion(),
|
|
7
|
+
// The licence and the copyright, where the OS shows them. macOS draws
|
|
8
|
+
copyright:creditsLib.COPYRIGHT,credits:`${creditsLib.LICENCE_NAME}\n${creditsLib.COPYRIGHT}\nSource: ${creditsLib.SOURCE_URL}\nHelp > Credits & licence lists the vendored third-party code and fonts.`});const i={label:"Check for Updates…",click:()=>n.check({announce:!0})},a={label:"New Chat",accelerator:"CmdOrCtrl+N",click:()=>sendToAppWindow(r,MENU_NEW_CHAT_CHANNEL)},c={label:"Search sessions…",accelerator:"CmdOrCtrl+K",click:()=>sendToAppWindow(r,MENU_SEARCH_CHANNEL)},l={label:"Search memory…",accelerator:"CmdOrCtrl+Shift+K",click:()=>sendToAppWindow(r,MENU_SEARCH_MEMORY_CHANNEL)},u={label:"Credits & Licence…",click:()=>sendToAppWindow(r,MENU_CREDITS_CHANNEL)},d={label:"Source Code",click:()=>{try{require("electron").shell.openExternal(creditsLib.SOURCE_URL)}catch{}}},p={label:"Save as…",accelerator:"CmdOrCtrl+S",click:()=>sendToAppWindow(r,MENU_EXPORT_MARKDOWN_CHANNEL)},m={label:"Export Session…",click:()=>sendToAppWindow(r,MENU_EXPORT_JSON_CHANNEL)},f={label:"Authorship Panel…",click:()=>sendToAppWindow(r,MENU_FINGERPRINT_CHANNEL)},h={label:"Google Drive Backup…",enabled:Boolean(o),click:()=>sendToAppWindow(r,MENU_GOOGLE_DRIVE_CHANNEL)},g=[...s?[{label:e.getName(),submenu:[{role:"about"},i,{type:"separator"},u,d,{type:"separator"},{role:"services"},{type:"separator"},{role:"hide"},{role:"hideOthers"},{role:"unhide"},{type:"separator"},{role:"quit"}]}]:[],{label:"File",submenu:[a,{type:"separator"},p,m,{type:"separator"},...s?[]:[i,{type:"separator"}],s?{role:"close"}:{role:"quit"}]},{label:"Edit",submenu:[{role:"undo"},{role:"redo"},{type:"separator"},{role:"cut"},{role:"copy"},{role:"paste"},{role:"selectAll"}]},{label:"View",submenu:[c,l,{type:"separator"},f,h,{type:"separator"},{role:"reload",accelerator:"CmdOrCtrl+R"},{role:"forceReload"},{type:"separator"},{role:"toggleDevTools",accelerator:"CmdOrCtrl+Shift+I"}]},{label:"Help",submenu:[u,d,{type:"separator"},...s?[]:[{role:"about"}]]}];return t.buildFromTemplate(g)}function bootstrap(){let e=!1;try{e=require("./lib/local/integrity.js").armed()}catch{e=!0,process.env.AEGIS_REDUCED_MODE="1",process.stderr.write("aegis-desktop: reduced mode (d1) — this build is not the one that was published.\n")}if(e){try{const{app:e}=electron;e&&"function"==typeof e.quit&&e.quit()}catch{}return}const{app:t,BrowserWindow:r,ipcMain:n,safeStorage:o,shell:s,Menu:i,Notification:a,screen:c,dialog:l,globalShortcut:u}=electron;try{let e;try{e=require("./vendor/selfhost.js")}catch{e=require("../one/src/selfhost.js")}const r=e.plan({packaged:t.isPackaged,execPath:process.execPath,resourcesPath:process.resourcesPath,argv:process.argv.slice(1),invokedAs:path.basename(process.argv[1]||process.execPath)});if(r){const n=e.spawnOptions(r,process.env),o=require("node:child_process").spawnSync(n.exec,n.args,{stdio:"inherit",env:n.env}),s="number"==typeof o.status?o.status:1;return void t.exit(s)}}catch(e){t.isPackaged&&!/MODULE_NOT_FOUND/.test(String(e&&e.message))&&process.stderr.write(`aegis: terminal face hand-off failed: ${e&&e.message||e}\n`)}if(t.disableHardwareAcceleration(),t.commandLine.appendSwitch("disable-gpu"),t.commandLine.appendSwitch("disable-software-rasterizer"),t.commandLine.appendSwitch("disable-gpu-compositing"),t.commandLine.appendSwitch("disable-features","UsePortalAccentColor"),process.argv.some((e=>/^--(log-level|enable-logging)/.test(e)))||process.env.ELECTRON_ENABLE_LOGGING||t.commandLine.appendSwitch("log-level","3"),!t.requestSingleInstanceLock())return void t.quit();if(t.setName("AEGIS Desktop"),envFile&&"function"==typeof envFile.loadEnvFile)try{const e=envFile.loadEnvFile();e.loose&&console.warn(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.`)}catch(e){console.warn(`aegis: could not read ${envFile.envFileFor()}: ${e&&e.message}`)}t.setAsDefaultProtocolClient(deepLink.PROTOCOL);let d=deepLink.parseDeepLinkArgv(process.argv);t.on("open-url",((e,t)=>{e.preventDefault();const r=deepLink.parseDeepLinkUrl(t);if(!r)return;const n="function"==typeof resolveTargetWindow?resolveTargetWindow():null;n&&!n.isDestroyed()?sendDeepLinkToWindow(n,r):d=r}));const p=createClient(credentials.clientOptions()),m=resolveUserDataDir(t),{engine:f,sessionsDir:h,settingsDir:g,settings:y}=createEngine(p,{app:t,safeStorage:o,dir:m}),E=createAccountKey({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),provision:(e,t)=>autoProvision.autoProvisionApiKey(e,t,{app:"desktop"}),describeFailure:autoProvision.provisionFailureText,onChange:e=>x(e)});let k=null;const _=createGoogleConnect({aegis:p,credentials:credentials,persistKey:e=>y.setAegisKey(e),openUrl:e=>!!isSafeExternalUrl(e)&&(s.openExternal(e),!0),googleSignIn:googleSignIn,driveConnect:driveConnectLib,driveUpload:driveUploadLib,conversationExport:conversationExportLib?{...conversationExportLib,toTranscript:e=>sessionStore.toMarkdown(e)}:null,getSession:e=>sessionStore.getSession(h,e),getAuthor:()=>{try{k||(k=createFingerprintService({dir:m,getVaultBackend:()=>y.vaultBackendConfig().backend}));const e=k.status();return e&&e.ok?e:null}catch{return null}},onAccountChange:()=>x(E.status())}),b=Boolean(p.apiKey),v=autoProvision.autoProvisionApiKey(p,credentials,{app:"desktop"}).then((e=>{if(E.recordStartup(e),!e.key&&!p.apiKey){const t=e.error&&(e.error.status||e.error.message||String(e.error))||"no key returned";console.warn(`auto-provision: no account key from register-device (${t})`)}return e}));try{const{wrapProviderKeyMirror:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`);e(y,envFile,{onWarn:t}),f&&f.settings&&f.settings!==y&&e(f.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not wire the shared env-file key mirror: ${e&&e.message}`)}let S=null;const A=(e,t)=>{if(function(e){const t=e&&e.sender,n=t&&r.fromWebContents(t);if(!n||n.isDestroyed())return;if(n.isFocused()&&n.isVisible())return;if(!a||!a.isSupported())return;const o=new a({title:"AEGIS Desktop",body:"Reply ready"});o.on("click",(()=>{n.isDestroyed()||(n.isMinimized()&&n.restore(),n.isVisible()||n.show(),n.focus())})),o.show()}(e),S&&"function"==typeof S.note){const e=t&&(t.model||t.modelId)||void 0;S.note({sessionId:t&&t.sessionId||null,model:e})}};registerIpc(n,p,m,(e=>{const t=y.setAegisKey(e);return e?credentials.saveApiKey(e):credentials.clearApiKey(),t}),(e=>s.openExternal(e)),A,(()=>providerRouteConfigured(f)),(()=>y.vaultBackendConfig().backend));const I=registerModelIpc(n,f,h,p,A,void 0,g);registerConfirmModeIpc(n,withAutoRoundsSwitch(createConfirmModeDispatch(y),I.modelDispatch)),registerConfirmModeIpc(n,createPermissionModeDispatch(y)),registerConfirmModeIpc(n,createVaultBackendDispatch(y)),registerConfirmModeIpc(n,createPermRulesDispatch(require("./lib/local/perm-store.js"))),registerConfirmModeIpc(n,createSandboxPolicyDispatch(y,require("./lib/local/sandbox.js"),{appDir:__dirname})),registerTelemetryIpc(n,createTelemetryDispatch(createTelemetry({dir:g,enabled:telemetryEnabled(process.env,y),appVersion:(()=>{try{return"function"==typeof t.getVersion?t.getVersion():""}catch{return""}})()}))),registerCovenantIpc(n,createCovenantDispatch(covenantModule));const R=registerQueueIpc(n,{engine:createQueueEngine(p,y),aegis:p}),C=createAutoDrain({proceed:()=>R.proceed(),settings:y,queue:queueModule,env:process.env,log:e=>{e&&"skip"!==e.type&&console.log("[auto-drain]",e.type,e.reason||e.error||"")}});let M=null;S=createAutoMint({mint:e=>(M||(M=createFingerprintService({dir:m,getVaultBackend:()=>y.vaultBackendConfig().backend})),M.mint(e||{})),settings:y}),registerAutoIpc(n,createAutoDispatch({autoDrain:C,autoMint:S})),C.start(),S.start();let w=null,P=null;function T(){return P&&!P.isDestroyed()||(P=new r({width:560,height:320,show:!1,frame:!1,alwaysOnTop:!0,skipTaskbar:!0,resizable:!1,movable:!0,fullscreenable:!1,minimizable:!1,maximizable:!1,backgroundColor:"#0d1117",icon:iconForPlatform(resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0}}),P.setMenuBarVisibility(!1),P.loadFile(path.join(__dirname,"renderer","quick.html")),P.webContents.on("before-input-event",((e,t)=>{"keyDown"!==t.type||"Escape"!==t.key||P.isDestroyed()||P.hide()})),P.on("blur",(()=>{!P.isDestroyed()&&P.isVisible()&&P.hide()})),P.on("closed",(()=>{P=null}))),P}function N(){const e=T();e.isVisible()?e.hide():function(){const e=T(),t=c.getCursorScreenPoint(),r=c.getAllDisplays(),n=e.getBounds(),o=quickLauncherLib.computeQuickLauncherBounds({cursor:t,displays:r,size:{width:n.width,height:n.height}});e.setBounds(o),e.show(),e.focus()}()}resolveTargetWindow=()=>{if(w&&!w.isDestroyed())return w;const e=r.getFocusedWindow();return e&&!e.isDestroyed()&&e!==P?e:r.getAllWindows().find((e=>e!==P))||null};const D=createQuickLauncherDispatch(y,{isPackaged:t.isPackaged,applyConfig:function(e){if(u.unregisterAll(),!quickLauncherLib.shouldEnableGlobalShortcut({isPackaged:t.isPackaged,enabled:e.enabled}))return{active:!1,reason:null};try{if(!u.register(e.shortcut,N)){const t=`"${e.shortcut}" could not be registered — it may already be in use by another application.`;return console.warn(`[quick-launcher] ${t}`),{active:!1,reason:t}}return{active:!0,reason:null}}catch(t){const r=errorText(t);return console.warn(`[quick-launcher] failed to register shortcut "${e.shortcut}": ${r}`),{active:!1,reason:r}}},pushToMain:function(e,t){const n=t&&t.sender&&r.fromWebContents(t.sender);n&&!n.isDestroyed()&&n.hide();const o=w&&!w.isDestroyed()?w:r.getAllWindows().find((e=>e!==n))||null;return o?(o.webContents.send(QUICK_LAUNCHER_PUSH_CHANNEL,e||{}),o.isMinimized()&&o.restore(),o.isVisible()||o.show(),o.focus(),{ok:!0}):{ok:!1,reason:"no main window is open"}}});registerQuickLauncherIpc(n,D);let L=null;t.on("will-quit",(()=>{L&&"function"==typeof L.stop&&L.stop(),closeMemoryIndex(),u.unregisterAll(),O&&"function"==typeof O.stop&&O.stop()}));let U=!1;t.on("before-quit",(e=>{!U&&f&&"function"==typeof f.unloadLocalModels&&(e.preventDefault(),Promise.resolve().then((()=>f.unloadLocalModels())).catch((()=>{})).finally((()=>{U=!0,t.quit()})))}));const F=new Set;function x(e){for(const t of F)t.isDestroyed()||t.webContents.send(ACCOUNT_STATUS_CHANNEL,e);q()}function q(){i.setApplicationMenu(buildAppMenu({app:t,Menu:i,BrowserWindow:r,updateManager:O,loggedIn:Boolean(p.apiKey)}))}const O=createUpdateManager({isPackaged:t.isPackaged,onStatus:function(e){for(const t of F)t.isDestroyed()||t.webContents.send(UPDATE_STATUS_CHANNEL,e)}});registerUpdateIpc(n,O),n.handle(`${IPC_PREFIX}accountStatus`,(()=>E.status())),n.handle(`${IPC_PREFIX}registerAccount`,(()=>E.registerAccount())),n.handle(`${IPC_PREFIX}driveSignIn`,(()=>_.signInWithGoogle())),n.handle(`${IPC_PREFIX}driveConnect`,(()=>_.connectDrive())),n.handle(`${IPC_PREFIX}driveStatus`,(()=>_.status())),n.handle(`${IPC_PREFIX}driveSyncMemory`,(()=>_.syncMemoryNow())),n.handle(`${IPC_PREFIX}driveBackupConversation`,((e,t)=>_.backupConversation({sessionId:t&&t.sessionId}))),registerExportIpc(n,sessionStore,h,(e=>l.showSaveDialog(r.getFocusedWindow(),e)),((e,t)=>fs.promises.writeFile(e,t,"utf8"))),n.handle(`${IPC_PREFIX}credits`,(()=>{try{return creditsLib.creditsFromDisk({readText:e=>{const t=[path.join(__dirname,"..",e),path.join(__dirname,e),path.join(process.resourcesPath||"","app",e)];for(const e of t)try{return{path:e,text:fs.readFileSync(e,"utf8")}}catch{}return null}})}catch(e){return{program:{licence:creditsLib.LICENCE_ID,name:creditsLib.LICENCE_NAME,url:creditsLib.LICENCE_URL,source:creditsLib.SOURCE_URL,copyright:creditsLib.COPYRIGHT,notice:creditsLib.COPYRIGHT},documents:[],code:[],fonts:[],missing:["licensing","vendor","fonts"],error:String(e&&e.message||e)}}})),q();const j=pathToFileURL(path.join(__dirname,"renderer","index.html")).href;function H(){const e=windowState.load(m),n=windowState.clampToDisplay(e,c.getAllDisplays(),{width:1080,height:720}),o=resolveIconsDir(t.isPackaged,process.resourcesPath,__dirname),i=new r({...n,minWidth:720,minHeight:480,show:!0,backgroundColor:"#0d1117",title:"AEGIS Desktop",icon:iconForPlatform(o,process.platform),webPreferences:{preload:path.join(__dirname,"preload.js"),contextIsolation:!0,nodeIntegration:!1,sandbox:!0,spellcheck:!0}});e&&e.isMaximized&&i.maximize(),i.webContents.setWindowOpenHandler((({url:e})=>(isSafeExternalUrl(e)&&s.openExternal(e),{action:"deny"}))),i.webContents.on("will-navigate",((e,t)=>{t!==j&&(e.preventDefault(),isSafeExternalUrl(t)&&s.openExternal(t))}));let a=null;function l(){if(i.isDestroyed())return;const e=i.isMaximized(),t=e?i.getNormalBounds():i.getBounds();windowState.save(m,{...t,isMaximized:e})}function u(){a&&clearTimeout(a),a=setTimeout(l,500)}return i.on("resize",u),i.on("move",u),i.on("close",(()=>{a&&clearTimeout(a),l()})),i.loadFile(path.join(__dirname,"renderer","index.html")),F.add(i),w=i,i.on("closed",(()=>{F.delete(i),w===i&&(w=null)})),i}t.whenReady().then((async()=>{if(!credentials.normalizeApiKey(process.env[credentials.KEY_ENV])){const e=await v,t=startupKeyOverride({mintedKey:b?"":e.key,hostKey:credentials.normalizeApiKey(y.aegisRawKey())});if(t)credentials.saveApiKey(t),p.setApiKey(t);else{const e=credentials.preferNewest(y.aegisRawKey(),y.aegisKeySavedAt());e.key&&(p.setApiKey(e.key),"shared"===e.source&&y.setAegisKey(e.key))}}try{L&&"function"==typeof L.stop&&L.stop(),L=sharedPresence.createPresence({apiKey:p.apiKey,app:"desktop",version:t.getVersion(),platform:process.platform,install:sharedFingerprint.machineFingerprint(),queueDepth:()=>{try{return queueModule.readQueue(queueModule.queuePath()).filter((e=>e&&"pending"===e.status)).length}catch{return 0}},autonomous:!1,log:(e,t)=>{"debug"!==e&&console.warn(t)}}),L.start()}catch(e){console.warn("presence: beacon not started",e&&e.message)}try{const{backfillProviderKeys:e}=require("./lib/provider-key-mirror.js"),t=e=>console.warn(`aegis: ${e}`),r=e(y,envFile,{onWarn:t});r.mirrored.length&&console.warn(`aegis: shared ${r.mirrored.join(", ")} key(s) with the other hosts (${envFile.envFileFor()})`),f&&f.settings&&f.settings!==y&&e(f.settings,envFile,{onWarn:t})}catch(e){console.warn(`aegis: could not backfill the shared env-file key mirror: ${e&&e.message}`)}D.setConfig(y.quickLauncherConfig());const e=H();O.start(),d&&sendDeepLinkToWindow(e,d)})),t.on("window-all-closed",(()=>{"darwin"!==process.platform&&t.quit()})),t.on("activate",(()=>{const e=r.getAllWindows();if(0===e.length)return void H();const t=resolveTargetWindow()||e[0];t.isMinimized()&&t.restore(),t.isVisible()||t.show(),t.focus()})),t.on("second-instance",((e,t)=>{const r=resolveTargetWindow(),n=deepLink.parseDeepLinkArgv(t);if(r)r.isMinimized()&&r.restore(),r.isVisible()||r.show(),r.focus(),n&&sendDeepLinkToWindow(r,n);else{const e=H();n&&sendDeepLinkToWindow(e,n)}}))}electron&&electron.app&&bootstrap(),module.exports={memoryIndex:memoryIndex,closeMemoryIndex:closeMemoryIndex,createIpcDispatch:createIpcDispatch,registerIpc:registerIpc,providerRouteConfigured:providerRouteConfigured,IPC_PREFIX:IPC_PREFIX,MODEL_PREFIX:MODEL_PREFIX,SYNC_PREFIX:SYNC_PREFIX,watchTopupCredit:watchTopupCredit,bankAmount:bankAmount,TOPUP_POLL_MS:TOPUP_POLL_MS,TOPUP_POLL_TRIES:TOPUP_POLL_TRIES,CHAT_DELTA_CHANNEL:CHAT_DELTA_CHANNEL,MENU_NEW_CHAT_CHANNEL:MENU_NEW_CHAT_CHANNEL,MENU_SEARCH_CHANNEL:MENU_SEARCH_CHANNEL,MENU_SEARCH_MEMORY_CHANNEL:MENU_SEARCH_MEMORY_CHANNEL,MENU_CREDITS_CHANNEL:MENU_CREDITS_CHANNEL,MENU_EXPORT_MARKDOWN_CHANNEL:MENU_EXPORT_MARKDOWN_CHANNEL,MENU_EXPORT_JSON_CHANNEL:MENU_EXPORT_JSON_CHANNEL,MENU_FINGERPRINT_CHANNEL:MENU_FINGERPRINT_CHANNEL,MENU_GOOGLE_DRIVE_CHANNEL:MENU_GOOGLE_DRIVE_CHANNEL,DEEP_LINK_CHANNEL:DEEP_LINK_CHANNEL,UPDATE_STATUS_CHANNEL:UPDATE_STATUS_CHANNEL,UPDATE_CHECK_INTERVAL_MS:UPDATE_CHECK_INTERVAL_MS,taggedChunk:taggedChunk,maskKey:maskKey,createModelDispatch:createModelDispatch,DESKTOP_CLASSES:DESKTOP_CLASSES,readTextFileForPreview:readTextFileForPreview,PREVIEW_READ_MAX_BYTES:PREVIEW_READ_MAX_BYTES,ingestAttachment:ingestAttachment,nativeImageResizer:nativeImageResizer,createSyncDispatch:createSyncDispatch,registerModelIpc:registerModelIpc,createHeartbeatRetry:createHeartbeatRetry,describeSyncError:describeSyncError,HEARTBEAT_RETRY_BASE_MS:HEARTBEAT_RETRY_BASE_MS,HEARTBEAT_RETRY_MAX_MS:HEARTBEAT_RETRY_MAX_MS,createEngine:createEngine,resolveUserDataDir:resolveUserDataDir,importForeignMemory:importForeignMemory,importForeignSessions:importForeignSessions,isSafeExternalUrl:isSafeExternalUrl,createUpdateManager:createUpdateManager,createNpmUpdateManager:createNpmUpdateManager,createUpdateDispatch:createUpdateDispatch,describeRegistryFailure:describeRegistryFailure,UPDATE_RETRY_BACKOFF_MS:UPDATE_RETRY_BACKOFF_MS,registerUpdateIpc:registerUpdateIpc,buildAppMenu:buildAppMenu,createExportDispatch:createExportDispatch,registerExportIpc:registerExportIpc,safeExportBasename:safeExportBasename,sendDeepLinkToWindow:sendDeepLinkToWindow,QUICK_PREFIX:QUICK_PREFIX,QUICK_LAUNCHER_PUSH_CHANNEL:QUICK_LAUNCHER_PUSH_CHANNEL,createQuickLauncherDispatch:createQuickLauncherDispatch,registerQuickLauncherIpc:registerQuickLauncherIpc,createConfirmModeDispatch:createConfirmModeDispatch,createVaultBackendDispatch:createVaultBackendDispatch,createPermRulesDispatch:createPermRulesDispatch,createSandboxPolicyDispatch:createSandboxPolicyDispatch,withAutoRoundsSwitch:withAutoRoundsSwitch,createTelemetryDispatch:createTelemetryDispatch,registerTelemetryIpc:registerTelemetryIpc,createCovenantDispatch:createCovenantDispatch,registerCovenantIpc:registerCovenantIpc,registerConfirmModeIpc:registerConfirmModeIpc,QUEUE_PREFIX:QUEUE_PREFIX,QUEUE_PROGRESS_CHANNEL:QUEUE_PROGRESS_CHANNEL,QUEUE_MAX_TASK_CHARS:QUEUE_MAX_TASK_CHARS,QUEUE_MAX_ROUNDS:QUEUE_MAX_ROUNDS,createQueueEngine:createQueueEngine,queueEngineWithDeniedApprovals:queueEngineWithDeniedApprovals,createQueueDispatch:createQueueDispatch,registerQueueIpc:registerQueueIpc,AUTO_PREFIX:AUTO_PREFIX,createAutoDispatch:createAutoDispatch,registerAutoIpc:registerAutoIpc};
|
|
@@ -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";function usageTokens(e){if(!e||"object"!=typeof e)return null;if("number"==typeof e.total_tokens)return e.total_tokens;const t=e.input_tokens??e.prompt_tokens??e.input,o=e.output_tokens??e.completion_tokens??e.output;return"number"!=typeof t&&"number"!=typeof o?null:(t||0)+(o||0)}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimatedBuckets(e,t,o){const n=("string"==typeof t?t:"")+("string"==typeof o?o:"");return"string"==typeof e&&e.length>0||n.length>0?{input:estimateTokens(e),output:estimateTokens(n),cacheRead:0,cacheWrite:0,real:!1}:null}const RATES={sonnet:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},default:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},fable:{input:10,output:50,cacheRead:1,cacheWrite:12.5},opus:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},haiku:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheWrite:6.25},"claude-opus-5-5":{input:4,output:20,cacheRead:.2,cacheWrite:5},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheWrite:2.5},"claude-sonnet-5-5":{input:2,output:10,cacheRead:.1,cacheWrite:2.5},"claude-haiku-5-5":{input:.1,output:.5,cacheRead:.01,cacheWrite:.125},"claude-fable-5":{input:10,output:50,cacheRead:1,cacheWrite:12.5},"claude-fable-5-1":{input:10,output:50,cacheRead:.25,cacheWrite:12.5},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},"claude-sonnet-4-5":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},deepseek:{input:.3,output:1.2,cacheRead:.006,cacheWrite:.3,offPeak:{input:.15,output:.6,cacheRead:.003,cacheWrite:.15}},"deepseek-v4-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"deepseek-v4.1-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"grok-4.7":{input:2,output:6,cacheRead:.5,cacheWrite:2},"gemini-3.8-flash":{input:.75,output:3.75,cacheRead:.075,cacheWrite:.75},"gpt-5.5":{input:5,output:30,cacheRead:.5,cacheWrite:5}};function isPeak(e,t=new Date){if(0!==String(e||"").toLowerCase().indexOf("deepseek"))return!0;const o=t.getUTCDay();if(0===o||6===o)return!1;const n=t.getUTCHours();return n>=1&&n<4||n>=6&&n<10}const RATE_BASIS=Object.freeze({EXACT:"exact",PREFIX:"prefix",FAMILY:"family",DEFAULT:"default"}),RATE_FAMILIES=Object.keys(RATES).filter((e=>"default"!==e)),UNPRICED_BY_DESIGN=Object.freeze({"nexus-brain":"pooled: multi-call fan-out, aegis1 settles the charge","aegis-brain":"pooled alias of nexus-brain","nexus-brain-smart":"pooled alias of nexus-brain","nexus-brain-neo":"pooled alias of nexus-brain","aegis-brain-smart":"pooled alias of nexus-brain","aegis-brain-neo":"pooled alias of nexus-brain","openai-gpt4o-mini":"pooled seat, aegis1 settles the charge",anthropic:"provider name, not a model id",openai:"provider name, not a model id",groq:"provider name, not a model id",google:"provider name, not a model id",xai:"provider name, not a model id"});function ratesFor(e,{at:t}={}){const o=String(e||"").toLowerCase(),n=(e,n)=>{const s=isPeak(0===o.indexOf("deepseek")||o.indexOf(":deepseek")>-1?"deepseek":o,t||new Date);return{...!s&&e.offPeak?{...e,...e.offPeak}:e,basis:n,peak:s,model:o}};if(!o)return n(RATES.default,RATE_BASIS.DEFAULT);const s=[o],a=Math.max(o.lastIndexOf(":"),o.lastIndexOf("/")),u=o.slice(a+1);u&&u!==o&&s.push(u);for(const e of s)if(RATES[e])return n(RATES[e],RATE_BASIS.EXACT);let c=null,i=0;for(const e of s)for(const[t,o]of Object.entries(RATES))"default"!==t&&e.startsWith(t)&&t.length>i&&(c=o,i=t.length);if(c)return n(c,RATE_BASIS.PREFIX);let r=null,p=0;for(const e of RATE_FAMILIES)o.includes(e)&&e.length>p&&(r=RATES[e],p=e.length);return n(r||RATES.default,r?RATE_BASIS.FAMILY:RATE_BASIS.DEFAULT)}function usageBuckets(e){const t=e&&"object"==typeof e?e:{},o=(...e)=>{for(const t of e)if("number"==typeof t)return t;return 0},n=e=>"number"==typeof e?e:void 0,s=n(t.input_tokens),a=n(t.prompt_tokens),u=t.prompt_tokens_details,c=u&&"object"==typeof u?n(u.cached_tokens):void 0,i=o(t.prompt_cache_hit_tokens,c,t.cached_tokens),r=void 0===s&&void 0!==a,p=r?a:o(s,a,t.input),l=o(t.cache_read_input_tokens,t.cacheRead,i),d=r?Math.min(Math.max(0,p),l):l,f=o(t.cache_creation_input_tokens,t.cacheWrite),m=o(t.output_tokens,t.completion_tokens,t.output),h=r?Math.max(0,p-d):p,k=o(t.total_tokens),R=h+m+d+f;return{input:k>R?h+(k-R):h,output:m,cacheRead:d,cacheWrite:f,cacheReported:"number"==typeof t.cache_read_input_tokens||"number"==typeof t.cacheRead||"number"==typeof t.cache_creation_input_tokens||"number"==typeof t.cacheWrite||"number"==typeof t.prompt_cache_hit_tokens||"number"==typeof t.cached_tokens||"number"==typeof c}}function cacheHitRate(e){const t=usageBuckets(e),o=Math.max(0,t.cacheRead||0),n=Math.max(0,t.input||0),s=o+n;return{read:o,miss:n,prompt:s,pct:t.cacheReported&&s>0?o/s*100:null,reported:t.cacheReported}}function costBreakdown(e,t,o={}){const n=ratesFor(t,o),s=usageBuckets(e),a=(e,t)=>Math.max(0,Number(e)||0)/1e6*t;return{cost:a(s.input,n.input)+a(s.output,n.output)+a(s.cacheRead,n.cacheRead)+a(s.cacheWrite,n.cacheWrite),basis:n.basis,peak:n.peak,model:n.model,priced:n.basis!==RATE_BASIS.DEFAULT}}function usageCost(e,t,o={}){return costBreakdown(e,t,o).cost}function turnAccounting(e,t,o={}){const n=usageTokens(e),s=e&&"object"==typeof e?e:{},a=e&&"object"==typeof e?usageBuckets(e).output:null,u="number"==typeof o.costUsd?o.costUsd:"number"==typeof s.costUsd?s.costUsd:void 0;if("number"==typeof u)return{tokens:n,output:a,cost:u,real:!0,estimated:!1,basis:"settled",priced:!0};if(null==n)return{tokens:n,output:a,cost:null,real:!1,estimated:!1,basis:null,priced:!1};const c=costBreakdown(s,t,o);return{tokens:n,output:a,cost:c.cost,real:!1,estimated:!0,basis:c.basis,priced:c.priced}}function emptyRoll(){return{turns:0,calls:0,tokens:0,input:0,output:0,cacheRead:0,cacheWrite:0,unknown:0,estimated:0,cost:0,estimate:0}}function rollTurn(e,t,o={}){const n=Object.assign(emptyRoll(),e||{});n.turns+=void 0===o.turns?1:Number(o.turns)||0,n.calls+=void 0===o.calls?1:Number(o.calls)||0;const s=turnAccounting(t,o.model,{costUsd:o.costUsd}),a=!0===o.estimated||t&&!1===t.real;if(null==s.tokens){const e=estimatedBuckets(o.prompt,o.reply,o.reasoning),t="number"==typeof o.measuredReasoningTokens&&o.measuredReasoningTokens>0?o.measuredReasoningTokens:0;return e?(n.tokens+=e.input+e.output+t,n.input+=e.input,n.output+=e.output+t,n.estimated+=1,n):t?(n.tokens+=t,n.output+=t,n.estimated+=1,n):(n.unknown+=1,n)}const u=usageBuckets(t);return n.tokens+=s.tokens,n.input+=u.input,n.output+=u.output,n.cacheRead+=u.cacheRead,n.cacheWrite+=u.cacheWrite,a?(n.estimated+=1,n):(s.real?n.cost+=s.cost:null!=s.cost&&(n.estimate+=s.cost),n)}function rollMessages(e){let t=emptyRoll();for(const o of Array.isArray(e)?e:[])o&&"assistant"===o.role&&(t=rollTurn(t,o.tokens,{model:o.model,costUsd:"number"==typeof o.costUsd?o.costUsd:void 0,calls:o.calls}));return t}function ledgerRow(e,t,o={}){const n=t||turnAccounting(e,o.model,{costUsd:o.costUsd}),s=Number.isFinite(o.calls)&&o.calls>0?o.calls:void 0;if(null!=n.tokens){const t={tokens:usageBuckets(e)};return n.real&&null!=n.cost&&(t.costUsd=n.cost),void 0!==s&&(t.calls=s),t}const a=estimatedBuckets(o.prompt,o.reply,o.reasoning);if(!a)return null;const u={tokens:a};return void 0!==s&&(u.calls=s),u}function fmtTokens(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"0":Math.round(t).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function displayTokens(e){if(!e||"object"!=typeof e)return null;const t=e.tokens,o=[e.output];t&&"object"==typeof t?o.push(t.output,t.output_tokens,t.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const e of o)if("number"==typeof e&&isFinite(e)&&e>0)return e;return null}function fmtRoll(e,t={}){const o=e||emptyRoll();if(!o.turns&&!o.calls)return"";const n=[],s=displayTokens(o);if(null!=s&&n.push(`${fmtTokens(s)} tokens`),n.push(`${o.calls} call${1===o.calls?"":"s"}`),!t.omitMoney&&(o.cost>0||o.estimate>0)){const e=[];o.cost>0&&e.push(fmtCost(o.cost,!0)),o.estimate>0&&e.push(fmtCost(o.estimate,!1)),n.push(e.join(" + "))}return o.unknown&&n.push(`${o.unknown} unrpt`),o.estimated&&n.push(`${o.estimated} est`),n.join(" · ")}function fmtCost(e,t){return"number"==typeof e&&isFinite(e)?`${t?"":"~"}$${e.toFixed(4)}`:""}function feeWaived(e){if(!e||"object"!=typeof e)return!1;const t=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter((e=>"string"==typeof e)).map((e=>e.trim().toLowerCase()));return!0===e.unlimited||!!t.some((e=>"unlimited"===e||"trial"===e))||t.some((e=>/(^|[^a-z])unlimited([^a-z]|$)/.test(e)))}function feeBillable(e){return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}"undefined"!=typeof module&&module.exports&&(module.exports={feeWaived:feeWaived,feeBillable:feeBillable,RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,usageTokens:usageTokens,ratesFor:ratesFor,usageBuckets:usageBuckets,cacheHitRate:cacheHitRate,usageCost:usageCost,costBreakdown:costBreakdown,turnAccounting:turnAccounting,displayTokens:displayTokens,estimateTokens:estimateTokens,estimatedBuckets:estimatedBuckets,emptyRoll:emptyRoll,rollTurn:rollTurn,rollMessages:rollMessages,ledgerRow:ledgerRow,fmtTokens:fmtTokens,fmtRoll:fmtRoll,fmtCost:fmtCost});
|
|
3
|
+
"use strict";function usageTokens(e){if(!e||"object"!=typeof e)return null;if("number"==typeof e.total_tokens)return e.total_tokens;const t=e.input_tokens??e.prompt_tokens??e.input,o=e.output_tokens??e.completion_tokens??e.output;return"number"!=typeof t&&"number"!=typeof o?null:(t||0)+(o||0)}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimatedBuckets(e,t,o){const n=("string"==typeof t?t:"")+("string"==typeof o?o:"");return"string"==typeof e&&e.length>0||n.length>0?{input:estimateTokens(e),output:estimateTokens(n),cacheRead:0,cacheWrite:0,real:!1}:null}const RATES={sonnet:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},default:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},fable:{input:10,output:50,cacheRead:1,cacheWrite:12.5},opus:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},haiku:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheWrite:6.25},"claude-opus-5-5":{input:4,output:20,cacheRead:.2,cacheWrite:5},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheWrite:2.5},"claude-sonnet-5-5":{input:2,output:10,cacheRead:.1,cacheWrite:2.5},"claude-haiku-5-5":{input:.1,output:.5,cacheRead:.01,cacheWrite:.125},"claude-fable-5":{input:10,output:50,cacheRead:1,cacheWrite:12.5},"claude-fable-5-1":{input:10,output:50,cacheRead:.25,cacheWrite:12.5},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},"claude-sonnet-4-5":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},deepseek:{input:.3,output:1.2,cacheRead:.006,cacheWrite:.3,offPeak:{input:.15,output:.6,cacheRead:.003,cacheWrite:.15}},"deepseek-v4-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"deepseek-v4.1-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"grok-4.7":{input:2,output:6,cacheRead:.5,cacheWrite:2},"gemini-3.8-flash":{input:.75,output:3.75,cacheRead:.075,cacheWrite:.75},"gpt-5.5":{input:5,output:30,cacheRead:.5,cacheWrite:5}};function isPeak(e,t=new Date){if(0!==String(e||"").toLowerCase().indexOf("deepseek"))return!0;const o=t.getUTCDay();if(0===o||6===o)return!1;const n=t.getUTCHours();return n>=1&&n<4||n>=6&&n<10}const RATE_BASIS=Object.freeze({EXACT:"exact",PREFIX:"prefix",FAMILY:"family",DEFAULT:"default"}),RATE_FAMILIES=Object.keys(RATES).filter((e=>"default"!==e)),UNPRICED_BY_DESIGN=Object.freeze({nexus:"auto-routing id: aegis1 picks the tier and settles the charge","nexus-brain":"pooled: multi-call fan-out, aegis1 settles the charge","aegis-brain":"pooled alias of nexus-brain","nexus-brain-smart":"pooled alias of nexus-brain","nexus-brain-neo":"pooled alias of nexus-brain","aegis-brain-smart":"pooled alias of nexus-brain","aegis-brain-neo":"pooled alias of nexus-brain","openai-gpt4o-mini":"pooled seat, aegis1 settles the charge",anthropic:"provider name, not a model id",openai:"provider name, not a model id",groq:"provider name, not a model id",google:"provider name, not a model id",xai:"provider name, not a model id"});function ratesFor(e,{at:t}={}){const o=String(e||"").toLowerCase(),n=(e,n)=>{const s=isPeak(0===o.indexOf("deepseek")||o.indexOf(":deepseek")>-1?"deepseek":o,t||new Date);return{...!s&&e.offPeak?{...e,...e.offPeak}:e,basis:n,peak:s,model:o}};if(!o)return n(RATES.default,RATE_BASIS.DEFAULT);const s=[o],a=Math.max(o.lastIndexOf(":"),o.lastIndexOf("/")),u=o.slice(a+1);u&&u!==o&&s.push(u);for(const e of s)if(RATES[e])return n(RATES[e],RATE_BASIS.EXACT);let c=null,i=0;for(const e of s)for(const[t,o]of Object.entries(RATES))"default"!==t&&e.startsWith(t)&&t.length>i&&(c=o,i=t.length);if(c)return n(c,RATE_BASIS.PREFIX);let r=null,p=0;for(const e of RATE_FAMILIES)o.includes(e)&&e.length>p&&(r=RATES[e],p=e.length);return n(r||RATES.default,r?RATE_BASIS.FAMILY:RATE_BASIS.DEFAULT)}function usageBuckets(e){const t=e&&"object"==typeof e?e:{},o=(...e)=>{for(const t of e)if("number"==typeof t)return t;return 0},n=e=>"number"==typeof e?e:void 0,s=n(t.input_tokens),a=n(t.prompt_tokens),u=t.prompt_tokens_details,c=u&&"object"==typeof u?n(u.cached_tokens):void 0,i=o(t.prompt_cache_hit_tokens,c,t.cached_tokens),r=void 0===s&&void 0!==a,p=r?a:o(s,a,t.input),l=o(t.cache_read_input_tokens,t.cacheRead,i),d=r?Math.min(Math.max(0,p),l):l,f=o(t.cache_creation_input_tokens,t.cacheWrite),m=o(t.output_tokens,t.completion_tokens,t.output),h=r?Math.max(0,p-d):p,k=o(t.total_tokens),R=h+m+d+f;return{input:k>R?h+(k-R):h,output:m,cacheRead:d,cacheWrite:f,cacheReported:"number"==typeof t.cache_read_input_tokens||"number"==typeof t.cacheRead||"number"==typeof t.cache_creation_input_tokens||"number"==typeof t.cacheWrite||"number"==typeof t.prompt_cache_hit_tokens||"number"==typeof t.cached_tokens||"number"==typeof c}}function cacheHitRate(e){const t=usageBuckets(e),o=Math.max(0,t.cacheRead||0),n=Math.max(0,t.input||0),s=o+n;return{read:o,miss:n,prompt:s,pct:t.cacheReported&&s>0?o/s*100:null,reported:t.cacheReported}}function costBreakdown(e,t,o={}){const n=ratesFor(t,o),s=usageBuckets(e),a=(e,t)=>Math.max(0,Number(e)||0)/1e6*t;return{cost:a(s.input,n.input)+a(s.output,n.output)+a(s.cacheRead,n.cacheRead)+a(s.cacheWrite,n.cacheWrite),basis:n.basis,peak:n.peak,model:n.model,priced:n.basis!==RATE_BASIS.DEFAULT}}function usageCost(e,t,o={}){return costBreakdown(e,t,o).cost}function turnAccounting(e,t,o={}){const n=usageTokens(e),s=e&&"object"==typeof e?e:{},a=e&&"object"==typeof e?usageBuckets(e).output:null,u="number"==typeof o.costUsd?o.costUsd:"number"==typeof s.costUsd?s.costUsd:void 0;if("number"==typeof u)return{tokens:n,output:a,cost:u,real:!0,estimated:!1,basis:"settled",priced:!0};if(null==n)return{tokens:n,output:a,cost:null,real:!1,estimated:!1,basis:null,priced:!1};const c=costBreakdown(s,t,o);return{tokens:n,output:a,cost:c.cost,real:!1,estimated:!0,basis:c.basis,priced:c.priced}}function emptyRoll(){return{turns:0,calls:0,tokens:0,input:0,output:0,cacheRead:0,cacheWrite:0,unknown:0,estimated:0,cost:0,estimate:0}}function rollTurn(e,t,o={}){const n=Object.assign(emptyRoll(),e||{});n.turns+=void 0===o.turns?1:Number(o.turns)||0,n.calls+=void 0===o.calls?1:Number(o.calls)||0;const s=turnAccounting(t,o.model,{costUsd:o.costUsd}),a=!0===o.estimated||t&&!1===t.real;if(null==s.tokens){const e=estimatedBuckets(o.prompt,o.reply,o.reasoning),t="number"==typeof o.measuredReasoningTokens&&o.measuredReasoningTokens>0?o.measuredReasoningTokens:0;return e?(n.tokens+=e.input+e.output+t,n.input+=e.input,n.output+=e.output+t,n.estimated+=1,n):t?(n.tokens+=t,n.output+=t,n.estimated+=1,n):(n.unknown+=1,n)}const u=usageBuckets(t);return n.tokens+=s.tokens,n.input+=u.input,n.output+=u.output,n.cacheRead+=u.cacheRead,n.cacheWrite+=u.cacheWrite,a?(n.estimated+=1,n):(s.real?n.cost+=s.cost:null!=s.cost&&(n.estimate+=s.cost),n)}function rollMessages(e){let t=emptyRoll();for(const o of Array.isArray(e)?e:[])o&&"assistant"===o.role&&(t=rollTurn(t,o.tokens,{model:o.model,costUsd:"number"==typeof o.costUsd?o.costUsd:void 0,calls:o.calls}));return t}function ledgerRow(e,t,o={}){const n=t||turnAccounting(e,o.model,{costUsd:o.costUsd}),s=Number.isFinite(o.calls)&&o.calls>0?o.calls:void 0;if(null!=n.tokens){const t={tokens:usageBuckets(e)};return n.real&&null!=n.cost&&(t.costUsd=n.cost),void 0!==s&&(t.calls=s),t}const a=estimatedBuckets(o.prompt,o.reply,o.reasoning);if(!a)return null;const u={tokens:a};return void 0!==s&&(u.calls=s),u}function fmtTokens(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"0":Math.round(t).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function displayTokens(e){if(!e||"object"!=typeof e)return null;const t=e.tokens,o=[e.output];t&&"object"==typeof t?o.push(t.output,t.output_tokens,t.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const e of o)if("number"==typeof e&&isFinite(e)&&e>0)return e;return null}function fmtRoll(e,t={}){const o=e||emptyRoll();if(!o.turns&&!o.calls)return"";const n=[],s=displayTokens(o);if(null!=s&&n.push(`${fmtTokens(s)} tokens`),n.push(`${o.calls} call${1===o.calls?"":"s"}`),!t.omitMoney&&(o.cost>0||o.estimate>0)){const e=[];o.cost>0&&e.push(fmtCost(o.cost,!0)),o.estimate>0&&e.push(fmtCost(o.estimate,!1)),n.push(e.join(" + "))}return o.unknown&&n.push(`${o.unknown} unrpt`),o.estimated&&n.push(`${o.estimated} est`),n.join(" · ")}function fmtCost(e,t){return"number"==typeof e&&isFinite(e)?`${t?"":"~"}$${e.toFixed(4)}`:""}function feeWaived(e){if(!e||"object"!=typeof e)return!1;const t=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter((e=>"string"==typeof e)).map((e=>e.trim().toLowerCase()));return!0===e.unlimited||!!t.some((e=>"unlimited"===e||"trial"===e))||t.some((e=>/(^|[^a-z])unlimited([^a-z]|$)/.test(e)))}function feeBillable(e){return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}"undefined"!=typeof module&&module.exports&&(module.exports={feeWaived:feeWaived,feeBillable:feeBillable,RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,usageTokens:usageTokens,ratesFor:ratesFor,usageBuckets:usageBuckets,cacheHitRate:cacheHitRate,usageCost:usageCost,costBreakdown:costBreakdown,turnAccounting:turnAccounting,displayTokens:displayTokens,estimateTokens:estimateTokens,estimatedBuckets:estimatedBuckets,emptyRoll:emptyRoll,rollTurn:rollTurn,rollMessages:rollMessages,ledgerRow:ledgerRow,fmtTokens:fmtTokens,fmtRoll:fmtRoll,fmtCost:fmtCost});
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");function dataDir(e={}){if(e.dir)return e.dir;const r=e.env||process.env;if(r.AEGISCODE_HOME)return r.AEGISCODE_HOME;const n=e.home||(()=>{try{return os.homedir()}catch{return r.HOME||r.USERPROFILE||""}})();return path.join(n,".aegiscode")}function registryPath(e={}){return path.join(dataDir(e),"harnesses.json")}function harnessName(e){const r=e&&(e.name||e.title);return String(null==r?"":r).trim().toLowerCase().replace(/\s+/g,"-").replace(/_/g,"-").replace(/[^a-z0-9.-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function deniedHarnesses(e={}){const r=e.env||process.env;return String(r.AEGISCODE_HARNESS_DENY||"").split(/[\s,]+/).map((e=>e.trim().toLowerCase())).filter(Boolean)}function admit(e,r={}){const n=harnessName(e),s=deniedHarnesses(r);return s.includes(n)||s.includes("*")?{ok:!1,name:n,reason:`AEGIS: harness "${n}" is denied by AEGISCODE_HARNESS_DENY. Unset that variable (or remove this name from it) to admit it.`}:{ok:!0,name:n,reason:""}}function read(e={}){const r=registryPath(e);try{const e=JSON.parse(fs.readFileSync(r,"utf8"));return e&&"object"==typeof e&&e&&"object"==typeof e.harnesses&&e.harnesses?e.harnesses:{}}catch{return{}}}function record(e,r={}){const n=harnessName(e),s=(new Date).toISOString();try{const t=read(r),a=t[n]||{},i=e&&e.version?String(e.version):a.version||null;t[n]={firstSeen:a.firstSeen||s,lastSeen:s,calls:(Number(a.calls)||0)+1,version:i};const o=registryPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0,mode:448});const c=`${o}.${process.pid}.tmp`;return fs.writeFileSync(c,JSON.stringify({harnesses:t},null,2),{mode:384}),fs.renameSync(c,o),{ok:!0,name:n}}catch{return{ok:!1,name:n}}}module.exports={dataDir:dataDir,registryPath:registryPath,harnessName:harnessName,deniedHarnesses:deniedHarnesses,admit:admit,read:read,record:record};
|