aegisone 1.0.65 → 1.0.67
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/aegis.js +1 -1
- package/package.json +1 -1
- package/vendor/cli/bin/aegiscode.js +47 -5
- package/vendor/cli/package.json +1 -1
- package/vendor/cli/src/app.js +1 -1
- package/vendor/cli/src/autonomous.js +574 -10
- package/vendor/cli/src/commands.js +1 -1
- package/vendor/cli/src/dream-cmd.js +3 -0
- package/vendor/cli/src/limits.js +1 -1
- package/vendor/cli/src/provenance.lock.json +3 -3
- package/vendor/cli/src/screen.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/cli/vendor/desktop/main.js +82 -1
- package/vendor/cli/vendor/mcp/tools.js +1 -1
- package/vendor/desktop/lib/local/autonomous.js +1 -1
- package/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/lib/local/queue.js +1 -1
- package/vendor/desktop/main.js +82 -1
- package/vendor/desktop/package.json +1 -1
- package/vendor/desktop/preload.js +1 -1
- package/vendor/desktop/renderer/app.js +3 -3
- package/vendor/desktop/renderer/pty-panel.js +1 -1
- package/vendor/desktop/renderer/pty-window.html +72 -0
- package/vendor/desktop/renderer/pty-window.js +3 -0
- package/vendor/desktop/renderer/stream-policy.js +1 -1
- package/vendor/desktop/renderer/style.css +55 -3
- package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
- package/vendor/desktop/vendor/faces/cli/package.json +1 -1
- package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/autonomous.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/commands.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/dream-cmd.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +3 -3
- package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.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/queue.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
|
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
|
|
|
134
134
|
* (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
|
|
135
135
|
* after obfuscation), never by hand.
|
|
136
136
|
*/
|
|
137
|
-
const SEALED = '
|
|
137
|
+
const SEALED = 'fb7b17fcebd59e8eeea8107198b7259c11c5c280e34a97d2a82fddaf599b1838';
|
|
138
138
|
|
|
139
139
|
/**
|
|
140
140
|
* Ask the question. Never throws — a check that can break the program it is
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),STATUSES=Object.freeze(["pending","running","done","error"]);function dataDir(e=process.env){const t=e||{},n=t.AEGISCODE_HOME||t.AEGIS_HOME;return n?path.resolve(n):path.join(os.homedir(),".aegiscode")}function queuePath(e=process.env){return e&&e.AEGIS_QUEUE_FILE||path.join(dataDir(e),"queue.jsonl")}function runsPath(e=process.env){return e&&e.AEGIS_RUNS_FILE||path.join(dataDir(e),"runs.jsonl")}function lockPath(e=process.env){return e&&e.AEGIS_QUEUE_LOCK||path.join(dataDir(e),"queue.lock")}function ensureDir(e){return fs.mkdirSync(e,{recursive:!0}),e}function readQueue(e){let t="";try{t=fs.readFileSync(e,"utf8")}catch{return[]}const n=[];for(const e of t.split("\n")){const t=e.trim();if(t)try{const e=JSON.parse(t);e&&"object"==typeof e&&null!=e.id&&n.push(e)}catch{}}return n}function writeQueue(e,t){ensureDir(path.dirname(e));const n=t.map(e=>JSON.stringify(e)).join("\n")+(t.length?"\n":""),r=`${e}.${process.pid}.tmp`;return fs.writeFileSync(r,n,{mode:384}),fs.renameSync(r,e),t}function loadQueue(e=process.env){return readQueue(queuePath(e))}function saveQueue(e,t){return writeQueue(queuePath(e),t)}function nextId(e){let t=0;for(const n of e){const e=Number(n&&n.id);Number.isFinite(e)&&e>t&&(t=e)}return t+1}function upsert(e,t){const n=Array.isArray(e)?e:[],r=n.findIndex(e=>e&&e.id===t.id);return-1===r?n.push(t):n[r]={...n[r],...t},n}function addTask(e,t={}){const n=String(null==t.task?"":t.task).trim();if(!n)throw new Error("queue: a task needs text");const r=require("./autonomous.js"),s=r.normalizeClass(t.class),
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),STATUSES=Object.freeze(["pending","running","done","error"]);function dataDir(e=process.env){const t=e||{},n=t.AEGISCODE_HOME||t.AEGIS_HOME;return n?path.resolve(n):path.join(os.homedir(),".aegiscode")}function queuePath(e=process.env){return e&&e.AEGIS_QUEUE_FILE||path.join(dataDir(e),"queue.jsonl")}function runsPath(e=process.env){return e&&e.AEGIS_RUNS_FILE||path.join(dataDir(e),"runs.jsonl")}function lockPath(e=process.env){return e&&e.AEGIS_QUEUE_LOCK||path.join(dataDir(e),"queue.lock")}function ensureDir(e){return fs.mkdirSync(e,{recursive:!0}),e}function readQueue(e){let t="";try{t=fs.readFileSync(e,"utf8")}catch{return[]}const n=[];for(const e of t.split("\n")){const t=e.trim();if(t)try{const e=JSON.parse(t);e&&"object"==typeof e&&null!=e.id&&n.push(e)}catch{}}return n}function writeQueue(e,t){ensureDir(path.dirname(e));const n=t.map(e=>JSON.stringify(e)).join("\n")+(t.length?"\n":""),r=`${e}.${process.pid}.tmp`;return fs.writeFileSync(r,n,{mode:384}),fs.renameSync(r,e),t}function loadQueue(e=process.env){return readQueue(queuePath(e))}function saveQueue(e,t){return writeQueue(queuePath(e),t)}function nextId(e){let t=0;for(const n of e){const e=Number(n&&n.id);Number.isFinite(e)&&e>t&&(t=e)}return t+1}function upsert(e,t){const n=Array.isArray(e)?e:[],r=n.findIndex(e=>e&&e.id===t.id);return-1===r?n.push(t):n[r]={...n[r],...t},n}function addTask(e,t={}){const n=String(null==t.task?"":t.task).trim();if(!n)throw new Error("queue: a task needs text");const r=require("./autonomous.js"),s=r.normalizeClass(t.class),a=String(null==t.model?"":t.model).trim(),o=r.modelRefusal(a,s);if(o)throw new Error(`queue: ${o}`);const u=loadQueue(e),i=t.now||Date.now(),c={id:nextId(u),task:n,cwd:t.cwd||process.cwd(),class:s,model:a||null,effort:t.effort||null,workers:Number.isInteger(t.workers)?t.workers:null,singlePass:Boolean(t.singlePass),commit:Boolean(t.commit),maxRounds:Number.isInteger(t.maxRounds)?t.maxRounds:null,source:t.source||"manual",status:"pending",attempts:0,created:i,updated:i};return upsert(u,c),saveQueue(e,u),c}function findTask(e,t){const n=Number(t);return(e||[]).find(e=>Number(e&&e.id)===n)||null}function markRunning(e,t,n={}){const r=findTask(e,t);if(!r)return null;const s=n.now||Date.now();return r.status="running",r.pid=n.pid||process.pid,r.startedAt=s,r.updated=s,r.attempts=(Number(r.attempts)||0)+1,r}function settle(e,t,{status:n,result:r,error:s,now:a=Date.now()}={}){const o=findTask(e,t);return o?(o.status=STATUSES.includes(n)?n:"error",o.updated=a,o.finishedAt=a,delete o.pid,void 0!==r&&(o.result=r),s?o.error=String(s):delete o.error,o):null}function retryTask(e,t,n={}){const r=loadQueue(e),s=findTask(r,t);return s?(s.status="pending",s.updated=n.now||Date.now(),delete s.error,delete s.pid,delete s.roundStops,saveQueue(e,r),s):null}function clearQueue(e,{all:t=!1}={}){const n=loadQueue(e),r=t?[]:n.filter(e=>"pending"===e.status||"running"===e.status),s=n.length-r.length;return saveQueue(e,r),{removed:s,kept:r.length}}function isAlive(e){const t=Number(e);if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return Boolean(e&&"EPERM"===e.code)}}function recoverStale(e,{isAliveFn:t=isAlive,now:n=Date.now()}={}){const r=[];for(const s of e||[])s&&"running"===s.status&&(s.pid&&t(s.pid)||(s.status="pending",s.updated=n,s.recoveredAt=n,delete s.pid,r.push(s.id)));return r}function pendingCount(e){return(e||[]).filter(e=>e&&"pending"===e.status).length}const LOCK_STALE_MS=9e4,LOCK_BEAT_MS=Math.floor(3e4);function pending(e){return(e||[]).filter(e=>e&&"pending"===e.status)}function lockHolder(e=process.env){try{return JSON.parse(fs.readFileSync(lockPath(e),"utf8"))}catch{return null}}function acquireLock(e=process.env,{pid:t=process.pid,now:n=Date.now(),isAliveFn:r=isAlive,staleMs:s=9e4}={}){const a=lockPath(e),o=lockHolder(e);if(o&&o.pid&&o.pid!==t&&r(o.pid)){const e=Number(o.beatAt||o.startedAt||0);if(!(s>0&&e>0&&n-e>s))return{ok:!1,holder:o,stale:!1}}ensureDir(path.dirname(a));const u={pid:t,host:os.hostname(),startedAt:n,beatAt:n};return fs.writeFileSync(a,JSON.stringify(u),{mode:384}),{ok:!0,holder:u,stoleFrom:o&&o.pid!==t?o:null}}function heartbeatLock(e=process.env,{pid:t=process.pid,now:n=Date.now()}={}){const r=lockHolder(e);if(!r||r.pid!==t)return{ok:!1,holder:r};const s={...r,beatAt:n};try{return ensureDir(path.dirname(lockPath(e))),fs.writeFileSync(lockPath(e),JSON.stringify(s),{mode:384}),{ok:!0,holder:s}}catch(e){return{ok:!1,holder:r,error:e.message}}}function releaseLock(e=process.env,{pid:t=process.pid}={}){const n=lockHolder(e);if(n&&n.pid&&n.pid!==t)return{ok:!1,holder:n};try{return fs.unlinkSync(lockPath(e)),{ok:!0}}catch{return{ok:!0,already:!0}}}function appendRun(e,t){const n=runsPath(e);return ensureDir(path.dirname(n)),fs.appendFileSync(n,JSON.stringify(t)+"\n",{mode:384}),t}function readRuns(e=process.env,{limit:t=20}={}){let n="";try{n=fs.readFileSync(runsPath(e),"utf8")}catch{return[]}const r=n.split("\n").filter(e=>e.trim()),s=t>0?r.slice(-t):r,a=[];for(const e of s)try{a.push(JSON.parse(e))}catch{}return a}function planPath(e){return path.join(e,"PLAN.md")}function parsePlanStatus(e){const t=new Map,n=new Set,r=new Set;let s=!1;for(const a of String(e||"").split("\n")){if(/^Status:/.test(a)){s=!0;continue}if(s){const e=a.match(/^- \[([ x])\] Phase (\d+)/);if(e){t.set(Number(e[2]),"x"===e[1]);continue}if(""===a.trim()||/^\s+\S/.test(a))continue;s=!1}const e=a.match(/^##\s*Phase\s+(\d+)\b/);if(e){const t=Number(e[1]);r.add(t),/✅/.test(a.slice(e[0].length))&&n.add(t)}}return{statusDone:t,headerDone:n,headerNums:r}}function extractPhaseTitle(e,t){const n=String(e||"").match(new RegExp(`^## Phase ${t}\\b(.*)$`,"m"));return n&&n[1].trim().replace(/^(✅|⚠️)\s*/,"").replace(/\s*(✅|⚠️)$/,"").replace(/^[—-]\s*/,"").trim()||`Phase ${t}`}function healPlanStatus(e,t){const n=[...t.headerDone].filter(e=>!t.statusDone.has(e)).sort((e,t)=>e-t);if(!n.length)return{text:e,changed:!1,added:[]};const r=String(e||"").split("\n"),s=r.findIndex(e=>/^Status:/.test(e));if(-1===s)return{text:e,changed:!1,added:[]};let a=-1;for(let e=s+1;e<r.length;e++)if(/^- \[[ x]\] Phase \d+/.test(r[e]))a=e;else if(""!==r[e].trim()&&!/^\s+\S/.test(r[e]))break;if(-1===a)return{text:e,changed:!1,added:[]};const o=n.map(t=>`- [x] Phase ${t} — ${extractPhaseTitle(e,t)}`);return r.splice(a+1,0,...o),{text:r.join("\n"),changed:!0,added:n}}function reconcilePlan(e,{write:t=!1}={}){let n;try{n=fs.readFileSync(planPath(e),"utf8")}catch{return{ok:!1,reason:`no PLAN.md in ${e}`,next:null}}const r=parsePlanStatus(n),s=healPlanStatus(n,r);s.changed&&t&&(fs.writeFileSync(planPath(e),s.text),n=s.text);const a=new Set(r.headerDone);for(const[e,t]of r.statusDone)t&&a.add(e);const o=[...r.headerNums].filter(e=>!a.has(e)).sort((e,t)=>e-t)[0];return null==o?{ok:!0,text:n,parsed:r,healed:s,next:null,title:null}:{ok:!0,text:n,parsed:r,healed:s,next:o,title:extractPhaseTitle(n,o)}}module.exports={STATUSES:STATUSES,dataDir:dataDir,queuePath:queuePath,runsPath:runsPath,lockPath:lockPath,ensureDir:ensureDir,readQueue:readQueue,writeQueue:writeQueue,loadQueue:loadQueue,saveQueue:saveQueue,nextId:nextId,upsert:upsert,addTask:addTask,findTask:findTask,markRunning:markRunning,settle:settle,retryTask:retryTask,clearQueue:clearQueue,isAlive:isAlive,recoverStale:recoverStale,pendingCount:pendingCount,pending:pending,lockHolder:lockHolder,acquireLock:acquireLock,heartbeatLock:heartbeatLock,releaseLock:releaseLock,LOCK_STALE_MS:9e4,LOCK_BEAT_MS:LOCK_BEAT_MS,appendRun:appendRun,readRuns:readRuns,planPath:planPath,parsePlanStatus:parsePlanStatus,extractPhaseTitle:extractPhaseTitle,healPlanStatus:healPlanStatus,reconcilePlan:reconcilePlan};
|
|
@@ -6271,7 +6271,7 @@ function bootstrap() {
|
|
|
6271
6271
|
// `createPtyIpc` probes it once at bootstrap; `aegis:ptyHello`'s caps tell
|
|
6272
6272
|
// the renderer whether to open the embedded panel or fall back to the
|
|
6273
6273
|
// `openCliFace` path above — that choice is the renderer's, not main's.
|
|
6274
|
-
createPtyIpc(ipcMain, {
|
|
6274
|
+
const ptyHost = createPtyIpc(ipcMain, {
|
|
6275
6275
|
appInfo: {
|
|
6276
6276
|
packaged: app.isPackaged,
|
|
6277
6277
|
resourcesPath: process.resourcesPath,
|
|
@@ -6281,6 +6281,66 @@ function bootstrap() {
|
|
|
6281
6281
|
},
|
|
6282
6282
|
});
|
|
6283
6283
|
|
|
6284
|
+
// ON10 — the terminal as its OWN window. ON9's panel lived inside this
|
|
6285
|
+
// window: an overlay that covered the chat and could not be moved off the
|
|
6286
|
+
// app. This opens the same shell detached, so N terminals and the chat are
|
|
6287
|
+
// all usable at once. No new backend: pty-host.js keys sessions by id and
|
|
6288
|
+
// ptyExec pushes frames to `event.sender`, so each window owns its own
|
|
6289
|
+
// shells with the handler above unchanged.
|
|
6290
|
+
//
|
|
6291
|
+
// Refused unless the probe above found a real PTY backend — opening an
|
|
6292
|
+
// empty window that cannot run anything would be a worse answer than the
|
|
6293
|
+
// renderer's existing fallback to an external terminal.
|
|
6294
|
+
const ptyWindows = new Set();
|
|
6295
|
+
ipcMain.handle(`${IPC_PREFIX}openPtyWindow`, () => {
|
|
6296
|
+
const hello = ptyHost.hello(0);
|
|
6297
|
+
const caps = (hello && hello.ok && hello.r && hello.r.caps) || [];
|
|
6298
|
+
if (!caps.includes('pty')) {
|
|
6299
|
+
return { ok: false, reason: 'no PTY backend in this build' };
|
|
6300
|
+
}
|
|
6301
|
+
const icon = iconForPlatform(resolveIconsDir(app.isPackaged, process.resourcesPath, __dirname), process.platform);
|
|
6302
|
+
// Cascade so the second and third shells do not land exactly on top of
|
|
6303
|
+
// the first — the user asked for several at once, and stamping them at
|
|
6304
|
+
// identical coordinates reads as "it did not open".
|
|
6305
|
+
const offset = (ptyWindows.size % 6) * 28;
|
|
6306
|
+
const base = mainWindowRef && !mainWindowRef.isDestroyed() ? mainWindowRef.getBounds() : { x: 80, y: 80 };
|
|
6307
|
+
const win = new BrowserWindow({
|
|
6308
|
+
width: 900,
|
|
6309
|
+
height: 560,
|
|
6310
|
+
x: base.x + 60 + offset,
|
|
6311
|
+
y: base.y + 60 + offset,
|
|
6312
|
+
minWidth: 380,
|
|
6313
|
+
minHeight: 240,
|
|
6314
|
+
show: false,
|
|
6315
|
+
backgroundColor: '#0d1117',
|
|
6316
|
+
title: 'Terminal — aegiscode',
|
|
6317
|
+
// A real OS frame, deliberately: it drags, resizes, snaps and lands on
|
|
6318
|
+
// a second monitor using the window manager's own behaviour. The
|
|
6319
|
+
// movable in-app panel could never do that, and hand-rolling a drag
|
|
6320
|
+
// handle would only reproduce what the frame already gives us.
|
|
6321
|
+
icon,
|
|
6322
|
+
webPreferences: {
|
|
6323
|
+
preload: path.join(__dirname, 'preload.js'),
|
|
6324
|
+
contextIsolation: true,
|
|
6325
|
+
nodeIntegration: false,
|
|
6326
|
+
sandbox: true,
|
|
6327
|
+
},
|
|
6328
|
+
});
|
|
6329
|
+
win.setMenuBarVisibility(false);
|
|
6330
|
+
ptyWindows.add(win);
|
|
6331
|
+
win.on('closed', () => ptyWindows.delete(win));
|
|
6332
|
+
win.once('ready-to-show', () => {
|
|
6333
|
+
if (!win.isDestroyed()) win.show();
|
|
6334
|
+
});
|
|
6335
|
+
win.loadFile(path.join(__dirname, 'renderer', 'pty-window.html'));
|
|
6336
|
+
return { ok: true };
|
|
6337
|
+
});
|
|
6338
|
+
ipcMain.handle(`${IPC_PREFIX}closePtyWindow`, (event) => {
|
|
6339
|
+
const from = event && event.sender ? BrowserWindow.fromWebContents(event.sender) : null;
|
|
6340
|
+
if (from && ptyWindows.has(from) && !from.isDestroyed()) from.close();
|
|
6341
|
+
return { ok: true };
|
|
6342
|
+
});
|
|
6343
|
+
|
|
6284
6344
|
// Funnel instrumentation (Phase 2 of docs/upgrade-conversion-plan.md):
|
|
6285
6345
|
// aegis:telemetryEvent / aegis:telemetryReport, backed by
|
|
6286
6346
|
// lib/local/telemetry.js.
|
|
@@ -7005,6 +7065,21 @@ function bootstrap() {
|
|
|
7005
7065
|
// exports can be unit-tested without an Electron binary.
|
|
7006
7066
|
const session = electron.session;
|
|
7007
7067
|
session.defaultSession.setPermissionRequestHandler((webContents, permission, callback, details) => {
|
|
7068
|
+
// Copy-to-clipboard: 'clipboard-sanitized-write' is what Chromium asks
|
|
7069
|
+
// for behind navigator.clipboard.writeText() — the only clipboard call
|
|
7070
|
+
// this app makes (the whole-message "copy" button in app.js and the
|
|
7071
|
+
// per-fenced-code-block one in markdown.js; neither reads the
|
|
7072
|
+
// clipboard). A recent-enough Chromium routes it through this handler
|
|
7073
|
+
// the same as 'media', and with no explicit grant here it denied every
|
|
7074
|
+
// copy in the app with no prompt and no console error — the button's
|
|
7075
|
+
// own "copy failed" was the only symptom. Granted to any of this app's
|
|
7076
|
+
// windows, not gated to the main window like dictation is below: there
|
|
7077
|
+
// is no feature a clipboard write from the quick launcher would turn on
|
|
7078
|
+
// that is not already reachable from the main window.
|
|
7079
|
+
if (permission === 'clipboard-sanitized-write') {
|
|
7080
|
+
const url = webContents && typeof webContents.getURL === 'function' ? webContents.getURL() : null;
|
|
7081
|
+
return callback(isOwnRenderer(url));
|
|
7082
|
+
}
|
|
7008
7083
|
if (permission !== 'media') return callback(false);
|
|
7009
7084
|
if (!isMainWindowUrl(webContents)) return callback(false);
|
|
7010
7085
|
// `details.mediaTypes` names what was asked for: ['audio'] for dictation.
|
|
@@ -7015,6 +7090,12 @@ function bootstrap() {
|
|
|
7015
7090
|
return callback(true);
|
|
7016
7091
|
});
|
|
7017
7092
|
session.defaultSession.setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
|
|
7093
|
+
// Same grant as the request handler above — Electron queries the check
|
|
7094
|
+
// handler separately (`navigator.permissions.query`), and a mismatch
|
|
7095
|
+
// between the two is what made the earlier dictation grant read as
|
|
7096
|
+
// denied from the renderer's own feature detection (see the comment
|
|
7097
|
+
// above `setPermissionCheckHandler` is registered alongside for).
|
|
7098
|
+
if (permission === 'clipboard-sanitized-write') return isOwnRenderer(requestingOrigin);
|
|
7018
7099
|
if (permission !== 'media') return false;
|
|
7019
7100
|
if (!isMainWindowUrl(webContents)) return false;
|
|
7020
7101
|
return isOwnRenderer(requestingOrigin);
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const foreignMemory=require("../client/foreign-memory.js");function createTools(e){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const t=e,o={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${t.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const o=await t.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),s=o.choices&&o.choices[0]||{};return`${s.message&&s.message.content||"(empty response)"}\n\n— ${[o.model?`model: ${o.model}`:null,o.usage?`tokens: ${o.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map(e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`)].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.tokenBankBalance(),o=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],s=(e.ledger||[]).slice(0,5);if(s.length){o.push("","Recent activity:");for(const e of s){const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,s=Math.abs(t),r=`${t<0?"-":"+"}€${s<.01?s.toFixed(4):s.toFixed(2)}`,i="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||i||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";o.push(` ${e.created_at||""} ${n}${a} ${r}`)}}else o.push("No spend yet.");var r;return(e.balance_eur||0)<=0&&o.push("",`Balance is empty — top up at ${r="topup","function"==typeof t.promptUrl?t.promptUrl(r,"topup_bank"):`https://aegiscloud.org/go/${r}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),o.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const o=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const t of e){const e=(t.models||[]).map(e=>"string"==typeof e?e:e&&e.id).filter(Boolean),s=t.configured?" ✓ set"+(t.masked?` (${t.masked})`:""):"";o.push(""),o.push(` ${t.id}${s}`),t.label&&o.push(` ${t.label}`),e.length&&o.push(` models: ${e.join(", ")}`),t.key_prefix&&o.push(` key starts with: ${t.key_prefix}`),t.key_url&&o.push(` get a key: ${t.key_url}`)}return o.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.byokStatus(),o=Object.entries(e||{});if(!o.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let s={};try{const e=await t.byokProviders();for(const t of e.providers||[])s[t.id]=t.label||""}catch{}return`BYOK keys:\n${o.map(([e,t])=>{const o=t&&t.set;return` ${e}${s[e]?` ${s[e]}`:""}: ${o?`set (${t.masked})`:"not set"}`}).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await t.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const o=(await t.memorySearch(e.query,e.limit||5)).entries||[];return o.length?o.map((e,t)=>{const o=e.timestamp||e.createdAt||"",s=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";return`${t+1}. ${e.content}${s}${o?`\n (${o})`:""}`}).join("\n"):`No memory entries matched "${e.query}".`}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const o={id:t.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await t.memorySave(o)).saved||1} memory entry (id ${o.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const o=e.limit||1e3,s=foreignMemory.scan({sources:e.sources,limit:o}),r=foreignMemory.describe(s);if(!s.entries.length)return`${r}\n\nNothing to import.`;if(!e.confirm)return[r,"",`Dry run — ${s.totals.entries} entries would be saved to AEGIS memory under ${s.totals.sourcesWithEntries} session(s) (${s.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let i=0;const n=[];for(const o of foreignMemory.chunk(s.entries,200))try{const e=await t.memorySaveBatch(o);i+=e&&e.saved||o.length}catch(e){n.push(e.message);break}return n.length?`${r}\n\nSaved ${i} of ${s.totals.entries} entries, then stopped: ${n[0]}`:`${r}\n\nSaved ${i} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const o=(await t.memoryList(e.limit||10)).entries||[];if(!o.length)return"AEGIS cloud memory is empty.";const s=o.map((e,t)=>`${t+1}. ${e.content}`).join("\n");return`Recent ${o.length} entries:\n${s}`}}};return{TOOLS:o,toolList:function(){return Object.entries(o).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema}))}}}module.exports={createTools:createTools};
|
|
3
|
+
"use strict";const foreignMemory=require("../client/foreign-memory.js");function createTools(e,t={}){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const o=t&&"object"==typeof t.localWiki?t.localWiki:null,i=e,s={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${i.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const t=await i.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),o=t.choices&&t.choices[0]||{};return`${o.message&&o.message.content||"(empty response)"}\n\n— ${[t.model?`model: ${t.model}`:null,t.usage?`tokens: ${t.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await i.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map(e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`)].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.tokenBankBalance(),t=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],o=(e.ledger||[]).slice(0,5);if(o.length){t.push("","Recent activity:");for(const e of o){const o=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,i=Math.abs(o),s=`${o<0?"-":"+"}€${i<.01?i.toFixed(4):i.toFixed(2)}`,r="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||r||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";t.push(` ${e.created_at||""} ${n}${a} ${s}`)}}else t.push("No spend yet.");var s;return(e.balance_eur||0)<=0&&t.push("",`Balance is empty — top up at ${s="topup","function"==typeof i.promptUrl?i.promptUrl(s,"topup_bank"):`https://aegiscloud.org/go/${s}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),t.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await i.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const t=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const o of e){const e=(o.models||[]).map(e=>"string"==typeof e?e:e&&e.id).filter(Boolean),i=o.configured?" ✓ set"+(o.masked?` (${o.masked})`:""):"";t.push(""),t.push(` ${o.id}${i}`),o.label&&t.push(` ${o.label}`),e.length&&t.push(` models: ${e.join(", ")}`),o.key_prefix&&t.push(` key starts with: ${o.key_prefix}`),o.key_url&&t.push(` get a key: ${o.key_url}`)}return t.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.byokStatus(),t=Object.entries(e||{});if(!t.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let o={};try{const e=await i.byokProviders();for(const t of e.providers||[])o[t.id]=t.label||""}catch{}return`BYOK keys:\n${t.map(([e,t])=>{const i=t&&t.set;return` ${e}${o[e]?` ${o[e]}`:""}: ${i?`set (${t.masked})`:"not set"}`}).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await i.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const t=(await i.memorySearch(e.query,e.limit||5)).entries||[],s=o?o.search(e.query,e.limit||5):[];if(!s.length&&!t.length)return`No memory entries matched "${e.query}".`;const r=[];let n=0;for(const e of s)r.push(`${++n}. [wiki] ${e.title}: ${e.value??""}\n ${e.body}`);for(const e of t){const t=e.timestamp||e.createdAt||"",o=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";r.push(`${++n}. ${e.content}${o}${t?`\n (${t})`:""}`)}return r.join("\n")}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const t={id:i.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await i.memorySave(t)).saved||1} memory entry (id ${t.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const t=e.limit||1e3,o=foreignMemory.scan({sources:e.sources,limit:t}),s=foreignMemory.describe(o);if(!o.entries.length)return`${s}\n\nNothing to import.`;if(!e.confirm)return[s,"",`Dry run — ${o.totals.entries} entries would be saved to AEGIS memory under ${o.totals.sourcesWithEntries} session(s) (${o.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let r=0;const n=[];for(const t of foreignMemory.chunk(o.entries,200))try{const e=await i.memorySaveBatch(t);r+=e&&e.saved||t.length}catch(e){n.push(e.message);break}return n.length?`${s}\n\nSaved ${r} of ${o.totals.entries} entries, then stopped: ${n[0]}`:`${s}\n\nSaved ${r} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const t=(await i.memoryList(e.limit||10)).entries||[];if(!t.length)return"AEGIS cloud memory is empty.";const o=t.map((e,t)=>`${t+1}. ${e.content}`).join("\n");return`Recent ${t.length} entries:\n${o}`}}};return{TOOLS:s,toolList:function(){return Object.entries(s).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema}))}}}module.exports={createTools:createTools};
|
|
@@ -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 queue=require("./queue.js"),gitScope=require("./git-scope.js"),DEFAULT_ROUNDS=40,MAX_ROUND_STOPS=3,WRITE_TOOLS=new Set(["writeFile","editFile"]),DEFAULT_AUTO_CONTINUES=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:3}const AUTO_ROUNDS_OFF=new Set(["0","false","off","no"]);function autoRoundsDefault(e=process.env){const t=e&&e.AEGIS_AUTO_ROUNDS;if(null==t)return!0;const o=String(t).trim().toLowerCase();return!o||!AUTO_ROUNDS_OFF.has(o)}function autoContinuePlan({on:e=!1,used:t=0,limit:o=3}={}){const n=Number.isFinite(o)&&o>0?Math.floor(o):3,r=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?r>=n?{auto:!1,used:0,cap:n}:{auto:!0,used:r+1,cap:n}:{auto:!1,used:r,cap:n}}function writtenPath(e){const t=e&&e.args||{},o=t.file_path||t.path;return o?String(o):""}const DEFAULT_MODEL="nexus-brain",MODEL_CLASSES=Object.freeze(["aegis","byok","local","pro"]),AEGIS_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,AEGIS_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain"]);function isAegisModel(e){return AEGIS_MODEL_RE.test(String(null==e?"":e).trim())}function normalizeClass(e){return String(null==e?"":e).trim().toLowerCase()||"aegis"}function looksLikeByokModel(e){const t=String(null==e?"":e).trim(),o=t.indexOf(":");return o>0&&o<t.length-1}function modelRefusal(e,t){const o=String(null==e?"":e).trim(),n=normalizeClass(t);if(!MODEL_CLASSES.includes(n))return`"${t}" is not a model class the queue serves (${MODEL_CLASSES.join("/")})`;if("aegis"===n)return!o||isAegisModel(o)?"":`the autonomous queue's Aegis Cloud class runs pooled-brain models only (nexus-brain, ${AEGIS_MODEL_IDS.join("/")} aliases); "${o}" is not one`;if("byok"===n)return o?looksLikeByokModel(o)?"":`"${o}" is not a byok model id — it must be "<provider>:<model>" (pick one from /models)`:'a byok task needs a model, as "<provider>:<model>" (pick one from /models)';if("pro"===n){if(!o)return"";let e;try{e=require("./claude-pro.js").PRO_MODELS}catch{return"a pro task's model cannot be checked right now — queue it with no --model to let the claude CLI pick"}const t=(Array.isArray(e)?e:[]).map(e=>String(e&&e.id).trim());return t.includes(o.toLowerCase())?"":`the autonomous queue's Pro class runs the subscription through the claude CLI, which accepts only its own model aliases (${t.join("/")}); "${o}" is not one`}return o?"":"a local task needs a model — the tag of whatever is pulled into the local daemon"}const AUTONOMOUS_REQUEST_RE=/\bautonomously\b|\bon your own\b|\bwithout asking\b|\bend[- ]to[- ]end\b|\bno (?:more )?questions\b|\bfully autonomous\b|\bqueue it\b/i;function isAutonomousRequest(e){return AUTONOMOUS_REQUEST_RE.test(String(e||""))}function maxRounds(e=process.env,t){const o=Number.parseInt(t,10);if(Number.isFinite(o)&&o>0)return o;const n=Number.parseInt(e&&e.AEGIS_AUTONOMOUS_MAX_ROUNDS||"",10);return Number.isFinite(n)&&n>0?n:40}function withRoundHorizon(e,t,o){const n="AEGIS_AUTONOMOUS_MAX_ROUNDS",r=[];for(const e of[t,process.env])e&&-1===r.indexOf(e)&&r.push(e);const s=r.map(e=>({target:e,had:Object.prototype.hasOwnProperty.call(e,n),prev:e[n]}));try{for(const t of r)t[n]=String(e)}catch{}const i=()=>{for(const e of s)try{e.had?e.target[n]=e.prev:delete e.target[n]}catch{}};let a;try{a=o()}catch(e){throw i(),e}return a&&"function"==typeof a.then?a.then(e=>(i(),e),e=>{throw i(),e}):(i(),a)}function resolveModel({model:e,env:t,cls:o}={}){const n=String(e||"").trim();if("aegis"!==normalizeClass(o))return n;if(n)return n;const r=t||process.env,s=String(r.AEGIS_AUTONOMOUS_MODEL||r.AEGIS_MODEL||"").trim();return isAegisModel(s)?s:"nexus-brain"}function ignoredEnvModel({model:e,env:t,cls:o}={}){if("aegis"!==normalizeClass(o))return"";if(String(e||"").trim())return"";const n=t||process.env,r=String(n.AEGIS_AUTONOMOUS_MODEL||n.AEGIS_MODEL||"").trim();return!r||isAegisModel(r)?"":`${String(n.AEGIS_AUTONOMOUS_MODEL||"").trim()?"AEGIS_AUTONOMOUS_MODEL":"AEGIS_MODEL"}="${r}" is not an Aegis Cloud model — running on nexus-brain instead`}function resolveFanout(e={},t=process.env){const o=e||{};if(!0===o.autonomous||!1===o.singlePass)return!0;const n=t||process.env;return/^(1|true|yes|on)$/i.test(String(n.AEGIS_AUTONOMOUS_FANOUT||"").trim())}function resolveEffort({effort:e,env:t,fanout:o}={}){const n=t||process.env;return String(e||n.AEGIS_AUTONOMOUS_EFFORT||"").trim()||(o?"high":"medium")}function autonomousDirective(e=40){return["# Autonomous mode",`You are running autonomously, not in a conversation: there is no user to answer a question or approve a plan. You have up to ${e} tool rounds this turn; use as many as the task needs.`,"Work the task end to end:","1. Plan in one line, then start acting in the same turn — never end a turn on a plan.","2. Read only what you need to make the change (no fishing through the repo).","2b. If this demand has been made before, establish whether it was met: check recalled memory, the queue file, PLAN.md, and git history for the earlier attempt. When it was fixed and the problem is back, state how it was fixed then and why it regressed, and fix that cause — a blind re-fix is a regression, not a resolution.","3. Make the change with Write/Edit/Bash, then VERIFY it: re-read the result and run the relevant test/command.","4. If verification fails, fix it and verify again — loop until it passes or you are genuinely blocked.",'5. Do not ask for permission, do not hand the work back, do not stop at "let me check…".',"6. Finish with a short report: what changed (file paths), the command you ran to verify, its result, and any remaining blocker."].join("\n")}function digestLine(e,t){const o=String(e.task||"").replace(/\s+/g," ").trim().slice(0,120),n=Boolean(t&&t.ok&&t.stoppedOnRounds)?"⏸":t&&t.ok?"✓":"✗",r=t&&Array.isArray(t.files)&&t.files.slice(0,6)||[],s=r.length?` — touched: ${r.join(", ")}${t.files.length>r.length?", …":""}`:"",i=!t||t.ok?"":` — ${String(t&&t.error||"failed").slice(0,120)}`;return`- #${e.id} ${n} ${o}${s}${i}`}function appendDigest(e,t,{keep:o=6}={}){return String(e||"").split("\n").filter(Boolean).concat(t).slice(-o).join("\n")}function taskPrompt(e,{carry:t="",rounds:o=40}={}){const n=[autonomousDirective(o)];return t&&n.push("# Earlier tasks in this run\nWork already done by this queue — do not redo it, build on it:\n"+t),n.push("# Task\n"+String(e.task||"").trim()),n.join("\n\n")}function assistantText(e){if(!e||"object"!=typeof e)return"";const t=Array.isArray(e.choices)?e.choices[0]:null,o=t&&t.message?t.message.content:e.content;return"string"==typeof o?o:Array.isArray(o)?o.map(e=>"string"==typeof e?e:e&&"string"==typeof e.text?e.text:"").join(""):""}function errorText(e){return e?"string"==typeof e?e:String(e.message||e.error||e):"unknown error"}function createQueueWorker({engine:e,env:t=process.env,log:o=()=>{},git:n=gitScope,now:r=Date.now,canFanOut:s=()=>!0}={}){if(!e||"function"!=typeof e.chat)throw new Error("autonomous: a local engine with chat() is required");const i=e=>{try{o(e)}catch{}};async function a(o,{carry:a="",commit:l}={}){const c=o.cwd||process.cwd(),m=normalizeClass(o.class),h=modelRefusal(o.model,m);if(h){const e={ok:!1,error:h,model:o.model,class:m,ms:0};return i({type:"finish",taskId:o.id,ok:!1,result:e}),e}const p=resolveModel({model:o.model,env:t,cls:m}),f=ignoredEnvModel({model:o.model,env:t,cls:m});f&&i({type:"note",taskId:o.id,note:f});const g="aegis"===m&&resolveFanout(o,t),k=g&&(()=>{try{return!1!==s()}catch{return!1}})();g&&!k&&i({type:"note",taskId:o.id,note:"fan-out needs Pro (the cloud drain that keeps running after you close the laptop) — this task ran as a single pass"});const S=resolveEffort({effort:o.effort,env:t,fanout:k}),O=maxRounds(t,o.maxRounds);let y=null,E=0;const A=new Set,v=e=>{if(e&&"object"==typeof e)if(e.approval)y=e.approval;else if(e.tool){if("done"===e.tool.phase&&(E+=1,WRITE_TOOLS.has(e.tool.name)&&!1!==e.tool.ok)){const t=writtenPath(e.tool);t&&A.add(t)}i({type:"tool",taskId:o.id,tool:e.tool})}else"string"==typeof e.delta?i({type:"delta",taskId:o.id,text:e.delta}):"string"==typeof e.reasoning&&i({type:"reasoning",taskId:o.id,text:e.reasoning})},w=void 0===l?Boolean(o.commit):Boolean(l),_=w?u(()=>n.gitStatusSnapshot(c),null):null;i({type:"start",taskId:o.id,model:p,class:m,cwd:c,rounds:O,fanout:k,effort:S});const M=r();let b;try{const n=await withRoundHorizon(O,t,()=>e.chat({class:m,model:p,prompt:taskPrompt(o,{carry:a,rounds:O}),autonomous:k,singlePass:!k,effort:S,workers:k&&o.workers||void 0,env:{cwd:c},maxRounds:O,sessionId:d(o.id),stream:!0},v));b={ok:!0,output:assistantText(n),usage:n&&n.usage||null,stoppedOnRounds:Boolean(n&&n.stoppedOnRounds),rounds:E||void 0},y&&(b.ok=!1,b.error=`tool approval was requested for "${y.tool||y.name||"a tool"}" with no one to answer it — construct the queue engine with approvals disabled (getConfirmMode: () => false)`)}catch(e){b={ok:!1,error:errorText(e)}}return b.ms=Math.max(0,r()-M),w&&(b.commit=u(()=>n.scopedCommit(c,{message:commitMessage(o),before:_,written:[...A]}),{ok:!1,error:"git-scope unavailable"}),b.files=function(e,t){return!e||e.error?[]:Array.isArray(e.paths)?e.paths:[...t]}(b.commit,A)),i({type:"finish",taskId:o.id,ok:b.ok,result:b}),b}function u(e,t){try{return e()}catch{return t}}async function l({commit:e,max:o=0,stopOnError:n=!1,carry:r=""}={}){const s=queue.acquireLock(t);if(!s.ok)return i({type:"locked",holder:s.holder}),{ok:!1,locked:!0,holder:s.holder,ran:[],carry:r};const a=[];try{for(;!(o>0&&a.length>=o);){const o=queue.loadQueue(t),s=queue.recoverStale(o);s.length&&(queue.saveQueue(t,o),i({type:"recovered",ids:s}));const u=queue.pending(o)[0];if(!u)break;const l=await c(u,{commit:e,carry:r});if(r=l.carry,a.push(l),!l.ok&&n)break}}finally{queue.releaseLock(t)}return{ok:!0,ran:a,carry:r}}async function c(e,{commit:o,carry:n=""}={}){const s=queue.loadQueue(t),i=queue.markRunning(s,e.id,{now:r()});if(!i)return{ok:!1,error:`unknown task #${e.id}`,carry:n};const u=Number(i.roundStops)||0;queue.saveQueue(t,s);const l=await a(i,{carry:n,commit:o}),c=Boolean(l.ok&&l.stoppedOnRounds),d=c?u+1:0,m=c&&d>3,h=m?{...l,ok:!1,error:`stopped at its tool-round horizon ${d} times in a row without finishing — raise AEGIS_AUTONOMOUS_MAX_ROUNDS or split the task into smaller ones`}:l,p=m?"error":c?"pending":h.ok?"done":"error",f=queue.loadQueue(t);queue.settle(f,i.id,{status:p,result:{ok:h.ok,output:h.output||"",usage:h.usage||null,ms:h.ms,commit:h.commit||null,files:h.files||[]},error:h.ok?null:h.error,now:r()});const g=queue.findTask(f,i.id);return g&&(g.roundStops=d),queue.saveQueue(t,f),queue.appendRun(t,{id:i.id,task:i.task,cwd:i.cwd,model:resolveModel({model:i.model,env:t}),status:"pending"===p?"stopped":p,at:new Date(r()).toISOString(),ms:h.ms,usage:h.usage||null,files:h.files||[],error:h.ok?null:h.error}),{...h,id:i.id,carry:appendDigest(n,digestLine(i,h))}}const d=e=>`queue-${e}`;return{runTask:a,runOne:c,proceed:l,reconcile:async function({cwd:e=process.cwd(),auto:o=!1,commit:n,max:r=0,stopOnError:s=!1}={}){const a=queue.reconcilePlan(e,{write:!0});if(!a.ok)return{ok:!1,error:a.reason};if(a.healed&&a.healed.changed&&i({type:"healed",phases:a.healed.added}),null==a.next)return{ok:!0,exhausted:!0};const u=`Work Phase ${a.next} from PLAN.md`,c=queue.loadQueue(t).find(t=>t.cwd===e&&String(t.task).startsWith(u)&&"done"!==t.status);if(c){if(i({type:"already-queued",phase:a.next,id:c.id,status:c.status}),!o)return{ok:!0,phase:a.next,id:c.id,existing:!0}}else{const o=queue.addTask(t,{task:`${u} ("${a.title}") at ${e}. Read the full "## Phase ${a.next}" section in PLAN.md at the repo root for the spec, exit criteria and constraints, and implement it exactly as scoped there. Keep the repo's checks green (\`npm run check\`, plus that package's tests). When every exit criterion is met, mark the "## Phase ${a.next}" heading with ✅ in PLAN.md and update its line in the top Status checklist.`,cwd:e,source:"reconcile",model:resolveModel({env:t})});i({type:"queued",phase:a.next,id:o.id,title:a.title})}if(!o)return{ok:!0,phase:a.next,title:a.title};const d=await l({commit:n,max:r,stopOnError:s});return{ok:!0,phase:a.next,title:a.title,...d}},cancel:function(t){if(null==t)return{ok:!1,error:"cancel needs a task id"};if("function"!=typeof e.cancel)return{ok:!1,error:"this engine cannot cancel a turn"};const o=e.cancel(d(t));return{ok:Boolean(o&&o.ok),sessionId:d(t)}},sessionIdFor:d,resolveModel:e=>resolveModel({...e,env:t})}}function commitMessage(e){const t=String(e.task||"queued task").split("\n")[0].replace(/\s+/g," ").trim();return`autonomous: ${t.slice(0,66)}${t.length>66?"…":""}`}module.exports={DEFAULT_MODEL:"nexus-brain",DEFAULT_ROUNDS:40,MAX_ROUND_STOPS:3,MODEL_CLASSES:MODEL_CLASSES,AEGIS_MODEL_IDS:AEGIS_MODEL_IDS,isAegisModel:isAegisModel,normalizeClass:normalizeClass,looksLikeByokModel:looksLikeByokModel,modelRefusal:modelRefusal,WRITE_TOOLS:WRITE_TOOLS,writtenPath:writtenPath,isAutonomousRequest:isAutonomousRequest,maxRounds:maxRounds,withRoundHorizon:withRoundHorizon,DEFAULT_AUTO_CONTINUES:3,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault,autoContinuePlan:autoContinuePlan,resolveModel:resolveModel,ignoredEnvModel:ignoredEnvModel,resolveEffort:resolveEffort,resolveFanout:resolveFanout,autonomousDirective:autonomousDirective,taskPrompt:taskPrompt,appendDigest:appendDigest,digestLine:digestLine,assistantText:assistantText,errorText:errorText,commitMessage:commitMessage,createQueueWorker:createQueueWorker};
|
|
3
|
+
"use strict";const queue=require("./queue.js"),gitScope=require("./git-scope.js"),DEFAULT_ROUNDS=40,MAX_ROUND_STOPS=3,WRITE_TOOLS=new Set(["writeFile","editFile"]),DEFAULT_AUTO_CONTINUES=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:3}const AUTO_ROUNDS_OFF=new Set(["0","false","off","no"]);function autoRoundsDefault(e=process.env){const t=e&&e.AEGIS_AUTO_ROUNDS;if(null==t)return!0;const o=String(t).trim().toLowerCase();return!o||!AUTO_ROUNDS_OFF.has(o)}function autoContinuePlan({on:e=!1,used:t=0,limit:o=3}={}){const n=Number.isFinite(o)&&o>0?Math.floor(o):3,r=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?r>=n?{auto:!1,used:0,cap:n}:{auto:!0,used:r+1,cap:n}:{auto:!1,used:r,cap:n}}function writtenPath(e){const t=e&&e.args||{},o=t.file_path||t.path;return o?String(o):""}const DEFAULT_MODEL="nexus-brain",MODEL_CLASSES=Object.freeze(["aegis","byok","local","pro"]),AEGIS_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,AEGIS_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain"]);function isAegisModel(e){return AEGIS_MODEL_RE.test(String(null==e?"":e).trim())}function normalizeClass(e){return String(null==e?"":e).trim().toLowerCase()||"aegis"}function looksLikeByokModel(e){const t=String(null==e?"":e).trim(),o=t.indexOf(":");return o>0&&o<t.length-1}function modelRefusal(e,t){const o=String(null==e?"":e).trim(),n=normalizeClass(t);if(!MODEL_CLASSES.includes(n))return`"${t}" is not a model class the queue serves (${MODEL_CLASSES.join("/")})`;if("aegis"===n)return!o||isAegisModel(o)?"":`the autonomous queue's Aegis Cloud class runs pooled-brain models only (nexus-brain, ${AEGIS_MODEL_IDS.join("/")} aliases); "${o}" is not one`;if("byok"===n)return o?looksLikeByokModel(o)?"":`"${o}" is not a byok model id — it must be "<provider>:<model>" (pick one from /models)`:'a byok task needs a model, as "<provider>:<model>" (pick one from /models)';if("pro"===n){if(!o)return"";let e;try{e=require("./claude-pro.js").PRO_MODELS}catch{return"a pro task's model cannot be checked right now — queue it with no --model to let the claude CLI pick"}const t=(Array.isArray(e)?e:[]).map(e=>String(e&&e.id).trim());return t.includes(o.toLowerCase())?"":`the autonomous queue's Pro class runs the subscription through the claude CLI, which accepts only its own model aliases (${t.join("/")}); "${o}" is not one`}return o?"":"a local task needs a model — the tag of whatever is pulled into the local daemon"}const AUTONOMOUS_REQUEST_RE=/\bautonomously\b|\bon your own\b|\bwithout asking\b|\bend[- ]to[- ]end\b|\bno (?:more )?questions\b|\bfully autonomous\b|\bqueue it\b/i;function isAutonomousRequest(e){return AUTONOMOUS_REQUEST_RE.test(String(e||""))}function maxRounds(e=process.env,t){const o=Number.parseInt(t,10);if(Number.isFinite(o)&&o>0)return o;const n=Number.parseInt(e&&e.AEGIS_AUTONOMOUS_MAX_ROUNDS||"",10);return Number.isFinite(n)&&n>0?n:40}function withRoundHorizon(e,t,o){const n="AEGIS_AUTONOMOUS_MAX_ROUNDS",r=[];for(const e of[t,process.env])e&&-1===r.indexOf(e)&&r.push(e);const s=r.map(e=>({target:e,had:Object.prototype.hasOwnProperty.call(e,n),prev:e[n]}));try{for(const t of r)t[n]=String(e)}catch{}const i=()=>{for(const e of s)try{e.had?e.target[n]=e.prev:delete e.target[n]}catch{}};let a;try{a=o()}catch(e){throw i(),e}return a&&"function"==typeof a.then?a.then(e=>(i(),e),e=>{throw i(),e}):(i(),a)}function resolveModel({model:e,env:t,cls:o}={}){const n=String(e||"").trim();if("aegis"!==normalizeClass(o))return n;if(n)return n;const r=t||process.env,s=String(r.AEGIS_AUTONOMOUS_MODEL||r.AEGIS_MODEL||"").trim();return isAegisModel(s)?s:"nexus-brain"}function ignoredEnvModel({model:e,env:t,cls:o}={}){if("aegis"!==normalizeClass(o))return"";if(String(e||"").trim())return"";const n=t||process.env,r=String(n.AEGIS_AUTONOMOUS_MODEL||n.AEGIS_MODEL||"").trim();return!r||isAegisModel(r)?"":`${String(n.AEGIS_AUTONOMOUS_MODEL||"").trim()?"AEGIS_AUTONOMOUS_MODEL":"AEGIS_MODEL"}="${r}" is not an Aegis Cloud model — running on nexus-brain instead`}function resolveFanout(e={},t=process.env){const o=e||{};if(!0===o.autonomous||!1===o.singlePass)return!0;const n=t||process.env;return/^(1|true|yes|on)$/i.test(String(n.AEGIS_AUTONOMOUS_FANOUT||"").trim())}function resolveEffort({effort:e,env:t,fanout:o}={}){const n=t||process.env;return String(e||n.AEGIS_AUTONOMOUS_EFFORT||"").trim()||(o?"high":"medium")}function autonomousDirective(e=40){return["# Autonomous mode",`You are running autonomously, not in a conversation: there is no user to answer a question or approve a plan. You have up to ${e} tool rounds this turn; use as many as the task needs.`,"Work the task end to end:","1. Plan in one line, then start acting in the same turn — never end a turn on a plan.","2. Read only what you need to make the change (no fishing through the repo).","2b. If this demand has been made before, establish whether it was met: check recalled memory, the queue file, PLAN.md, and git history for the earlier attempt. When it was fixed and the problem is back, state how it was fixed then and why it regressed, and fix that cause — a blind re-fix is a regression, not a resolution.","3. Make the change with Write/Edit/Bash, then VERIFY it: re-read the result and run the relevant test/command.","4. If verification fails, fix it and verify again — loop until it passes or you are genuinely blocked.",'5. Do not ask for permission, do not hand the work back, do not stop at "let me check…".',"6. Finish with a short report: what changed (file paths), the command you ran to verify, its result, and any remaining blocker."].join("\n")}function digestLine(e,t){const o=String(e.task||"").replace(/\s+/g," ").trim().slice(0,120),n=Boolean(t&&t.ok&&t.stoppedOnRounds)?"⏸":t&&t.ok?"✓":"✗",r=t&&Array.isArray(t.files)&&t.files.slice(0,6)||[],s=r.length?` — touched: ${r.join(", ")}${t.files.length>r.length?", …":""}`:"",i=!t||t.ok?"":` — ${String(t&&t.error||"failed").slice(0,120)}`;return`- #${e.id} ${n} ${o}${s}${i}`}function appendDigest(e,t,{keep:o=6}={}){return String(e||"").split("\n").filter(Boolean).concat(t).slice(-o).join("\n")}function taskPrompt(e,{carry:t="",rounds:o=40}={}){const n=[autonomousDirective(o)];return t&&n.push("# Earlier tasks in this run\nWork already done by this queue — do not redo it, build on it:\n"+t),n.push("# Task\n"+String(e.task||"").trim()),n.join("\n\n")}function assistantText(e){if(!e||"object"!=typeof e)return"";const t=Array.isArray(e.choices)?e.choices[0]:null,o=t&&t.message?t.message.content:e.content;return"string"==typeof o?o:Array.isArray(o)?o.map(e=>"string"==typeof e?e:e&&"string"==typeof e.text?e.text:"").join(""):""}function errorText(e){return e?"string"==typeof e?e:String(e.message||e.error||e):"unknown error"}function createQueueWorker({engine:e,env:t=process.env,log:o=()=>{},git:n=gitScope,now:r=Date.now,canFanOut:s=()=>!0}={}){if(!e||"function"!=typeof e.chat)throw new Error("autonomous: a local engine with chat() is required");const i=e=>{try{o(e)}catch{}};async function a(o,{carry:a="",commit:l}={}){const c=o.cwd||process.cwd(),m=normalizeClass(o.class),h=modelRefusal(o.model,m);if(h){const e={ok:!1,error:h,model:o.model,class:m,ms:0};return i({type:"finish",taskId:o.id,ok:!1,result:e}),e}const p=resolveModel({model:o.model,env:t,cls:m}),f=ignoredEnvModel({model:o.model,env:t,cls:m});f&&i({type:"note",taskId:o.id,note:f});const g="aegis"===m&&resolveFanout(o,t),k=g&&(()=>{try{return!1!==s()}catch{return!1}})();g&&!k&&i({type:"note",taskId:o.id,note:"fan-out needs Pro (the cloud drain that keeps running after you close the laptop) — this task ran as a single pass"});const S=resolveEffort({effort:o.effort,env:t,fanout:k}),O=maxRounds(t,o.maxRounds);let y=null,E=0;const A=new Set,v=e=>{if(e&&"object"==typeof e)if(e.approval)y=e.approval;else if(e.tool){if("done"===e.tool.phase&&(E+=1,WRITE_TOOLS.has(e.tool.name)&&!1!==e.tool.ok)){const t=writtenPath(e.tool);t&&A.add(t)}i({type:"tool",taskId:o.id,tool:e.tool})}else"string"==typeof e.delta?i({type:"delta",taskId:o.id,text:e.delta}):"string"==typeof e.reasoning&&i({type:"reasoning",taskId:o.id,text:e.reasoning})},_=void 0===l?Boolean(o.commit):Boolean(l),w=_?u(()=>n.gitStatusSnapshot(c),null):null;i({type:"start",taskId:o.id,model:p,class:m,cwd:c,rounds:O,fanout:k,effort:S});const M=r();let b;try{const n=await withRoundHorizon(O,t,()=>e.chat({class:m,model:p,prompt:taskPrompt(o,{carry:a,rounds:O}),autonomous:k,singlePass:!k,effort:S,workers:k&&o.workers||void 0,env:{cwd:c},maxRounds:O,sessionId:d(o.id),stream:!0},v));b={ok:!0,output:assistantText(n),usage:n&&n.usage||null,stoppedOnRounds:Boolean(n&&n.stoppedOnRounds),rounds:E||void 0},y&&(b.ok=!1,b.error=`tool approval was requested for "${y.tool||y.name||"a tool"}" with no one to answer it — construct the queue engine with approvals disabled (getConfirmMode: () => false)`)}catch(e){b={ok:!1,error:errorText(e)}}return b.ms=Math.max(0,r()-M),_&&(b.commit=u(()=>n.scopedCommit(c,{message:commitMessage(o),before:w,written:[...A]}),{ok:!1,error:"git-scope unavailable"}),b.files=function(e,t){return!e||e.error?[]:Array.isArray(e.paths)?e.paths:[...t]}(b.commit,A)),i({type:"finish",taskId:o.id,ok:b.ok,result:b}),b}function u(e,t){try{return e()}catch{return t}}async function l({commit:e,max:o=0,stopOnError:n=!1,carry:r=""}={}){const s=queue.acquireLock(t);if(!s.ok)return i({type:"locked",holder:s.holder}),{ok:!1,locked:!0,holder:s.holder,ran:[],carry:r};let a=null;try{a=setInterval(()=>queue.heartbeatLock(t),queue.LOCK_BEAT_MS),"function"==typeof a.unref&&a.unref()}catch{a=null}s.stoleFrom&&i({type:"reclaimed",holder:s.stoleFrom});const u=[];try{for(;!(o>0&&u.length>=o);){const o=queue.loadQueue(t),s=queue.recoverStale(o);s.length&&(queue.saveQueue(t,o),i({type:"recovered",ids:s}));const a=queue.pending(o)[0];if(!a)break;const l=await c(a,{commit:e,carry:r});if(r=l.carry,u.push(l),!l.ok&&n)break}}finally{a&&clearInterval(a),queue.releaseLock(t)}return{ok:!0,ran:u,carry:r}}async function c(e,{commit:o,carry:n=""}={}){const s=queue.loadQueue(t),i=queue.markRunning(s,e.id,{now:r()});if(!i)return{ok:!1,error:`unknown task #${e.id}`,carry:n};const u=Number(i.roundStops)||0;queue.saveQueue(t,s);const l=await a(i,{carry:n,commit:o}),c=Boolean(l.ok&&l.stoppedOnRounds),d=c?u+1:0,m=c&&d>3,h=m?{...l,ok:!1,error:`stopped at its tool-round horizon ${d} times in a row without finishing — raise AEGIS_AUTONOMOUS_MAX_ROUNDS or split the task into smaller ones`}:l,p=m?"error":c?"pending":h.ok?"done":"error",f=queue.loadQueue(t);queue.settle(f,i.id,{status:p,result:{ok:h.ok,output:h.output||"",usage:h.usage||null,ms:h.ms,commit:h.commit||null,files:h.files||[]},error:h.ok?null:h.error,now:r()});const g=queue.findTask(f,i.id);return g&&(g.roundStops=d),queue.saveQueue(t,f),queue.appendRun(t,{id:i.id,task:i.task,cwd:i.cwd,model:resolveModel({model:i.model,env:t}),status:"pending"===p?"stopped":p,at:new Date(r()).toISOString(),ms:h.ms,usage:h.usage||null,files:h.files||[],error:h.ok?null:h.error}),{...h,id:i.id,carry:appendDigest(n,digestLine(i,h))}}const d=e=>`queue-${e}`;return{runTask:a,runOne:c,proceed:l,reconcile:async function({cwd:e=process.cwd(),auto:o=!1,commit:n,max:r=0,stopOnError:s=!1}={}){const a=queue.reconcilePlan(e,{write:!0});if(!a.ok)return{ok:!1,error:a.reason};if(a.healed&&a.healed.changed&&i({type:"healed",phases:a.healed.added}),null==a.next)return{ok:!0,exhausted:!0};const u=`Work Phase ${a.next} from PLAN.md`,c=queue.loadQueue(t).find(t=>t.cwd===e&&String(t.task).startsWith(u)&&"done"!==t.status);if(c){if(i({type:"already-queued",phase:a.next,id:c.id,status:c.status}),!o)return{ok:!0,phase:a.next,id:c.id,existing:!0}}else{const o=queue.addTask(t,{task:`${u} ("${a.title}") at ${e}. Read the full "## Phase ${a.next}" section in PLAN.md at the repo root for the spec, exit criteria and constraints, and implement it exactly as scoped there. Keep the repo's checks green (\`npm run check\`, plus that package's tests). When every exit criterion is met, mark the "## Phase ${a.next}" heading with ✅ in PLAN.md and update its line in the top Status checklist.`,cwd:e,source:"reconcile",model:resolveModel({env:t})});i({type:"queued",phase:a.next,id:o.id,title:a.title})}if(!o)return{ok:!0,phase:a.next,title:a.title};const d=await l({commit:n,max:r,stopOnError:s});return{ok:!0,phase:a.next,title:a.title,...d}},cancel:function(t){if(null==t)return{ok:!1,error:"cancel needs a task id"};if("function"!=typeof e.cancel)return{ok:!1,error:"this engine cannot cancel a turn"};const o=e.cancel(d(t));return{ok:Boolean(o&&o.ok),sessionId:d(t)}},sessionIdFor:d,resolveModel:e=>resolveModel({...e,env:t})}}function commitMessage(e){const t=String(e.task||"queued task").split("\n")[0].replace(/\s+/g," ").trim();return`autonomous: ${t.slice(0,66)}${t.length>66?"…":""}`}module.exports={DEFAULT_MODEL:"nexus-brain",DEFAULT_ROUNDS:40,MAX_ROUND_STOPS:3,MODEL_CLASSES:MODEL_CLASSES,AEGIS_MODEL_IDS:AEGIS_MODEL_IDS,isAegisModel:isAegisModel,normalizeClass:normalizeClass,looksLikeByokModel:looksLikeByokModel,modelRefusal:modelRefusal,WRITE_TOOLS:WRITE_TOOLS,writtenPath:writtenPath,isAutonomousRequest:isAutonomousRequest,maxRounds:maxRounds,withRoundHorizon:withRoundHorizon,DEFAULT_AUTO_CONTINUES:3,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault,autoContinuePlan:autoContinuePlan,resolveModel:resolveModel,ignoredEnvModel:ignoredEnvModel,resolveEffort:resolveEffort,resolveFanout:resolveFanout,autonomousDirective:autonomousDirective,taskPrompt:taskPrompt,appendDigest:appendDigest,digestLine:digestLine,assistantText:assistantText,errorText:errorText,commitMessage:commitMessage,createQueueWorker:createQueueWorker};
|
|
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
|
|
|
134
134
|
* (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
|
|
135
135
|
* after obfuscation), never by hand.
|
|
136
136
|
*/
|
|
137
|
-
const SEALED = '
|
|
137
|
+
const SEALED = 'fb7b17fcebd59e8eeea8107198b7259c11c5c280e34a97d2a82fddaf599b1838';
|
|
138
138
|
|
|
139
139
|
/**
|
|
140
140
|
* Ask the question. Never throws — a check that can break the program it is
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),STATUSES=Object.freeze(["pending","running","done","error"]);function dataDir(e=process.env){const t=e||{},n=t.AEGISCODE_HOME||t.AEGIS_HOME;return n?path.resolve(n):path.join(os.homedir(),".aegiscode")}function queuePath(e=process.env){return e&&e.AEGIS_QUEUE_FILE||path.join(dataDir(e),"queue.jsonl")}function runsPath(e=process.env){return e&&e.AEGIS_RUNS_FILE||path.join(dataDir(e),"runs.jsonl")}function lockPath(e=process.env){return e&&e.AEGIS_QUEUE_LOCK||path.join(dataDir(e),"queue.lock")}function ensureDir(e){return fs.mkdirSync(e,{recursive:!0}),e}function readQueue(e){let t="";try{t=fs.readFileSync(e,"utf8")}catch{return[]}const n=[];for(const e of t.split("\n")){const t=e.trim();if(t)try{const e=JSON.parse(t);e&&"object"==typeof e&&null!=e.id&&n.push(e)}catch{}}return n}function writeQueue(e,t){ensureDir(path.dirname(e));const n=t.map(e=>JSON.stringify(e)).join("\n")+(t.length?"\n":""),r=`${e}.${process.pid}.tmp`;return fs.writeFileSync(r,n,{mode:384}),fs.renameSync(r,e),t}function loadQueue(e=process.env){return readQueue(queuePath(e))}function saveQueue(e,t){return writeQueue(queuePath(e),t)}function nextId(e){let t=0;for(const n of e){const e=Number(n&&n.id);Number.isFinite(e)&&e>t&&(t=e)}return t+1}function upsert(e,t){const n=Array.isArray(e)?e:[],r=n.findIndex(e=>e&&e.id===t.id);return-1===r?n.push(t):n[r]={...n[r],...t},n}function addTask(e,t={}){const n=String(null==t.task?"":t.task).trim();if(!n)throw new Error("queue: a task needs text");const r=require("./autonomous.js"),s=r.normalizeClass(t.class),
|
|
3
|
+
"use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),STATUSES=Object.freeze(["pending","running","done","error"]);function dataDir(e=process.env){const t=e||{},n=t.AEGISCODE_HOME||t.AEGIS_HOME;return n?path.resolve(n):path.join(os.homedir(),".aegiscode")}function queuePath(e=process.env){return e&&e.AEGIS_QUEUE_FILE||path.join(dataDir(e),"queue.jsonl")}function runsPath(e=process.env){return e&&e.AEGIS_RUNS_FILE||path.join(dataDir(e),"runs.jsonl")}function lockPath(e=process.env){return e&&e.AEGIS_QUEUE_LOCK||path.join(dataDir(e),"queue.lock")}function ensureDir(e){return fs.mkdirSync(e,{recursive:!0}),e}function readQueue(e){let t="";try{t=fs.readFileSync(e,"utf8")}catch{return[]}const n=[];for(const e of t.split("\n")){const t=e.trim();if(t)try{const e=JSON.parse(t);e&&"object"==typeof e&&null!=e.id&&n.push(e)}catch{}}return n}function writeQueue(e,t){ensureDir(path.dirname(e));const n=t.map(e=>JSON.stringify(e)).join("\n")+(t.length?"\n":""),r=`${e}.${process.pid}.tmp`;return fs.writeFileSync(r,n,{mode:384}),fs.renameSync(r,e),t}function loadQueue(e=process.env){return readQueue(queuePath(e))}function saveQueue(e,t){return writeQueue(queuePath(e),t)}function nextId(e){let t=0;for(const n of e){const e=Number(n&&n.id);Number.isFinite(e)&&e>t&&(t=e)}return t+1}function upsert(e,t){const n=Array.isArray(e)?e:[],r=n.findIndex(e=>e&&e.id===t.id);return-1===r?n.push(t):n[r]={...n[r],...t},n}function addTask(e,t={}){const n=String(null==t.task?"":t.task).trim();if(!n)throw new Error("queue: a task needs text");const r=require("./autonomous.js"),s=r.normalizeClass(t.class),a=String(null==t.model?"":t.model).trim(),o=r.modelRefusal(a,s);if(o)throw new Error(`queue: ${o}`);const u=loadQueue(e),i=t.now||Date.now(),c={id:nextId(u),task:n,cwd:t.cwd||process.cwd(),class:s,model:a||null,effort:t.effort||null,workers:Number.isInteger(t.workers)?t.workers:null,singlePass:Boolean(t.singlePass),commit:Boolean(t.commit),maxRounds:Number.isInteger(t.maxRounds)?t.maxRounds:null,source:t.source||"manual",status:"pending",attempts:0,created:i,updated:i};return upsert(u,c),saveQueue(e,u),c}function findTask(e,t){const n=Number(t);return(e||[]).find(e=>Number(e&&e.id)===n)||null}function markRunning(e,t,n={}){const r=findTask(e,t);if(!r)return null;const s=n.now||Date.now();return r.status="running",r.pid=n.pid||process.pid,r.startedAt=s,r.updated=s,r.attempts=(Number(r.attempts)||0)+1,r}function settle(e,t,{status:n,result:r,error:s,now:a=Date.now()}={}){const o=findTask(e,t);return o?(o.status=STATUSES.includes(n)?n:"error",o.updated=a,o.finishedAt=a,delete o.pid,void 0!==r&&(o.result=r),s?o.error=String(s):delete o.error,o):null}function retryTask(e,t,n={}){const r=loadQueue(e),s=findTask(r,t);return s?(s.status="pending",s.updated=n.now||Date.now(),delete s.error,delete s.pid,delete s.roundStops,saveQueue(e,r),s):null}function clearQueue(e,{all:t=!1}={}){const n=loadQueue(e),r=t?[]:n.filter(e=>"pending"===e.status||"running"===e.status),s=n.length-r.length;return saveQueue(e,r),{removed:s,kept:r.length}}function isAlive(e){const t=Number(e);if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return Boolean(e&&"EPERM"===e.code)}}function recoverStale(e,{isAliveFn:t=isAlive,now:n=Date.now()}={}){const r=[];for(const s of e||[])s&&"running"===s.status&&(s.pid&&t(s.pid)||(s.status="pending",s.updated=n,s.recoveredAt=n,delete s.pid,r.push(s.id)));return r}function pendingCount(e){return(e||[]).filter(e=>e&&"pending"===e.status).length}const LOCK_STALE_MS=9e4,LOCK_BEAT_MS=Math.floor(3e4);function pending(e){return(e||[]).filter(e=>e&&"pending"===e.status)}function lockHolder(e=process.env){try{return JSON.parse(fs.readFileSync(lockPath(e),"utf8"))}catch{return null}}function acquireLock(e=process.env,{pid:t=process.pid,now:n=Date.now(),isAliveFn:r=isAlive,staleMs:s=9e4}={}){const a=lockPath(e),o=lockHolder(e);if(o&&o.pid&&o.pid!==t&&r(o.pid)){const e=Number(o.beatAt||o.startedAt||0);if(!(s>0&&e>0&&n-e>s))return{ok:!1,holder:o,stale:!1}}ensureDir(path.dirname(a));const u={pid:t,host:os.hostname(),startedAt:n,beatAt:n};return fs.writeFileSync(a,JSON.stringify(u),{mode:384}),{ok:!0,holder:u,stoleFrom:o&&o.pid!==t?o:null}}function heartbeatLock(e=process.env,{pid:t=process.pid,now:n=Date.now()}={}){const r=lockHolder(e);if(!r||r.pid!==t)return{ok:!1,holder:r};const s={...r,beatAt:n};try{return ensureDir(path.dirname(lockPath(e))),fs.writeFileSync(lockPath(e),JSON.stringify(s),{mode:384}),{ok:!0,holder:s}}catch(e){return{ok:!1,holder:r,error:e.message}}}function releaseLock(e=process.env,{pid:t=process.pid}={}){const n=lockHolder(e);if(n&&n.pid&&n.pid!==t)return{ok:!1,holder:n};try{return fs.unlinkSync(lockPath(e)),{ok:!0}}catch{return{ok:!0,already:!0}}}function appendRun(e,t){const n=runsPath(e);return ensureDir(path.dirname(n)),fs.appendFileSync(n,JSON.stringify(t)+"\n",{mode:384}),t}function readRuns(e=process.env,{limit:t=20}={}){let n="";try{n=fs.readFileSync(runsPath(e),"utf8")}catch{return[]}const r=n.split("\n").filter(e=>e.trim()),s=t>0?r.slice(-t):r,a=[];for(const e of s)try{a.push(JSON.parse(e))}catch{}return a}function planPath(e){return path.join(e,"PLAN.md")}function parsePlanStatus(e){const t=new Map,n=new Set,r=new Set;let s=!1;for(const a of String(e||"").split("\n")){if(/^Status:/.test(a)){s=!0;continue}if(s){const e=a.match(/^- \[([ x])\] Phase (\d+)/);if(e){t.set(Number(e[2]),"x"===e[1]);continue}if(""===a.trim()||/^\s+\S/.test(a))continue;s=!1}const e=a.match(/^##\s*Phase\s+(\d+)\b/);if(e){const t=Number(e[1]);r.add(t),/✅/.test(a.slice(e[0].length))&&n.add(t)}}return{statusDone:t,headerDone:n,headerNums:r}}function extractPhaseTitle(e,t){const n=String(e||"").match(new RegExp(`^## Phase ${t}\\b(.*)$`,"m"));return n&&n[1].trim().replace(/^(✅|⚠️)\s*/,"").replace(/\s*(✅|⚠️)$/,"").replace(/^[—-]\s*/,"").trim()||`Phase ${t}`}function healPlanStatus(e,t){const n=[...t.headerDone].filter(e=>!t.statusDone.has(e)).sort((e,t)=>e-t);if(!n.length)return{text:e,changed:!1,added:[]};const r=String(e||"").split("\n"),s=r.findIndex(e=>/^Status:/.test(e));if(-1===s)return{text:e,changed:!1,added:[]};let a=-1;for(let e=s+1;e<r.length;e++)if(/^- \[[ x]\] Phase \d+/.test(r[e]))a=e;else if(""!==r[e].trim()&&!/^\s+\S/.test(r[e]))break;if(-1===a)return{text:e,changed:!1,added:[]};const o=n.map(t=>`- [x] Phase ${t} — ${extractPhaseTitle(e,t)}`);return r.splice(a+1,0,...o),{text:r.join("\n"),changed:!0,added:n}}function reconcilePlan(e,{write:t=!1}={}){let n;try{n=fs.readFileSync(planPath(e),"utf8")}catch{return{ok:!1,reason:`no PLAN.md in ${e}`,next:null}}const r=parsePlanStatus(n),s=healPlanStatus(n,r);s.changed&&t&&(fs.writeFileSync(planPath(e),s.text),n=s.text);const a=new Set(r.headerDone);for(const[e,t]of r.statusDone)t&&a.add(e);const o=[...r.headerNums].filter(e=>!a.has(e)).sort((e,t)=>e-t)[0];return null==o?{ok:!0,text:n,parsed:r,healed:s,next:null,title:null}:{ok:!0,text:n,parsed:r,healed:s,next:o,title:extractPhaseTitle(n,o)}}module.exports={STATUSES:STATUSES,dataDir:dataDir,queuePath:queuePath,runsPath:runsPath,lockPath:lockPath,ensureDir:ensureDir,readQueue:readQueue,writeQueue:writeQueue,loadQueue:loadQueue,saveQueue:saveQueue,nextId:nextId,upsert:upsert,addTask:addTask,findTask:findTask,markRunning:markRunning,settle:settle,retryTask:retryTask,clearQueue:clearQueue,isAlive:isAlive,recoverStale:recoverStale,pendingCount:pendingCount,pending:pending,lockHolder:lockHolder,acquireLock:acquireLock,heartbeatLock:heartbeatLock,releaseLock:releaseLock,LOCK_STALE_MS:9e4,LOCK_BEAT_MS:LOCK_BEAT_MS,appendRun:appendRun,readRuns:readRuns,planPath:planPath,parsePlanStatus:parsePlanStatus,extractPhaseTitle:extractPhaseTitle,healPlanStatus:healPlanStatus,reconcilePlan:reconcilePlan};
|
package/vendor/desktop/main.js
CHANGED
|
@@ -6271,7 +6271,7 @@ function bootstrap() {
|
|
|
6271
6271
|
// `createPtyIpc` probes it once at bootstrap; `aegis:ptyHello`'s caps tell
|
|
6272
6272
|
// the renderer whether to open the embedded panel or fall back to the
|
|
6273
6273
|
// `openCliFace` path above — that choice is the renderer's, not main's.
|
|
6274
|
-
createPtyIpc(ipcMain, {
|
|
6274
|
+
const ptyHost = createPtyIpc(ipcMain, {
|
|
6275
6275
|
appInfo: {
|
|
6276
6276
|
packaged: app.isPackaged,
|
|
6277
6277
|
resourcesPath: process.resourcesPath,
|
|
@@ -6281,6 +6281,66 @@ function bootstrap() {
|
|
|
6281
6281
|
},
|
|
6282
6282
|
});
|
|
6283
6283
|
|
|
6284
|
+
// ON10 — the terminal as its OWN window. ON9's panel lived inside this
|
|
6285
|
+
// window: an overlay that covered the chat and could not be moved off the
|
|
6286
|
+
// app. This opens the same shell detached, so N terminals and the chat are
|
|
6287
|
+
// all usable at once. No new backend: pty-host.js keys sessions by id and
|
|
6288
|
+
// ptyExec pushes frames to `event.sender`, so each window owns its own
|
|
6289
|
+
// shells with the handler above unchanged.
|
|
6290
|
+
//
|
|
6291
|
+
// Refused unless the probe above found a real PTY backend — opening an
|
|
6292
|
+
// empty window that cannot run anything would be a worse answer than the
|
|
6293
|
+
// renderer's existing fallback to an external terminal.
|
|
6294
|
+
const ptyWindows = new Set();
|
|
6295
|
+
ipcMain.handle(`${IPC_PREFIX}openPtyWindow`, () => {
|
|
6296
|
+
const hello = ptyHost.hello(0);
|
|
6297
|
+
const caps = (hello && hello.ok && hello.r && hello.r.caps) || [];
|
|
6298
|
+
if (!caps.includes('pty')) {
|
|
6299
|
+
return { ok: false, reason: 'no PTY backend in this build' };
|
|
6300
|
+
}
|
|
6301
|
+
const icon = iconForPlatform(resolveIconsDir(app.isPackaged, process.resourcesPath, __dirname), process.platform);
|
|
6302
|
+
// Cascade so the second and third shells do not land exactly on top of
|
|
6303
|
+
// the first — the user asked for several at once, and stamping them at
|
|
6304
|
+
// identical coordinates reads as "it did not open".
|
|
6305
|
+
const offset = (ptyWindows.size % 6) * 28;
|
|
6306
|
+
const base = mainWindowRef && !mainWindowRef.isDestroyed() ? mainWindowRef.getBounds() : { x: 80, y: 80 };
|
|
6307
|
+
const win = new BrowserWindow({
|
|
6308
|
+
width: 900,
|
|
6309
|
+
height: 560,
|
|
6310
|
+
x: base.x + 60 + offset,
|
|
6311
|
+
y: base.y + 60 + offset,
|
|
6312
|
+
minWidth: 380,
|
|
6313
|
+
minHeight: 240,
|
|
6314
|
+
show: false,
|
|
6315
|
+
backgroundColor: '#0d1117',
|
|
6316
|
+
title: 'Terminal — aegiscode',
|
|
6317
|
+
// A real OS frame, deliberately: it drags, resizes, snaps and lands on
|
|
6318
|
+
// a second monitor using the window manager's own behaviour. The
|
|
6319
|
+
// movable in-app panel could never do that, and hand-rolling a drag
|
|
6320
|
+
// handle would only reproduce what the frame already gives us.
|
|
6321
|
+
icon,
|
|
6322
|
+
webPreferences: {
|
|
6323
|
+
preload: path.join(__dirname, 'preload.js'),
|
|
6324
|
+
contextIsolation: true,
|
|
6325
|
+
nodeIntegration: false,
|
|
6326
|
+
sandbox: true,
|
|
6327
|
+
},
|
|
6328
|
+
});
|
|
6329
|
+
win.setMenuBarVisibility(false);
|
|
6330
|
+
ptyWindows.add(win);
|
|
6331
|
+
win.on('closed', () => ptyWindows.delete(win));
|
|
6332
|
+
win.once('ready-to-show', () => {
|
|
6333
|
+
if (!win.isDestroyed()) win.show();
|
|
6334
|
+
});
|
|
6335
|
+
win.loadFile(path.join(__dirname, 'renderer', 'pty-window.html'));
|
|
6336
|
+
return { ok: true };
|
|
6337
|
+
});
|
|
6338
|
+
ipcMain.handle(`${IPC_PREFIX}closePtyWindow`, (event) => {
|
|
6339
|
+
const from = event && event.sender ? BrowserWindow.fromWebContents(event.sender) : null;
|
|
6340
|
+
if (from && ptyWindows.has(from) && !from.isDestroyed()) from.close();
|
|
6341
|
+
return { ok: true };
|
|
6342
|
+
});
|
|
6343
|
+
|
|
6284
6344
|
// Funnel instrumentation (Phase 2 of docs/upgrade-conversion-plan.md):
|
|
6285
6345
|
// aegis:telemetryEvent / aegis:telemetryReport, backed by
|
|
6286
6346
|
// lib/local/telemetry.js.
|
|
@@ -7005,6 +7065,21 @@ function bootstrap() {
|
|
|
7005
7065
|
// exports can be unit-tested without an Electron binary.
|
|
7006
7066
|
const session = electron.session;
|
|
7007
7067
|
session.defaultSession.setPermissionRequestHandler((webContents, permission, callback, details) => {
|
|
7068
|
+
// Copy-to-clipboard: 'clipboard-sanitized-write' is what Chromium asks
|
|
7069
|
+
// for behind navigator.clipboard.writeText() — the only clipboard call
|
|
7070
|
+
// this app makes (the whole-message "copy" button in app.js and the
|
|
7071
|
+
// per-fenced-code-block one in markdown.js; neither reads the
|
|
7072
|
+
// clipboard). A recent-enough Chromium routes it through this handler
|
|
7073
|
+
// the same as 'media', and with no explicit grant here it denied every
|
|
7074
|
+
// copy in the app with no prompt and no console error — the button's
|
|
7075
|
+
// own "copy failed" was the only symptom. Granted to any of this app's
|
|
7076
|
+
// windows, not gated to the main window like dictation is below: there
|
|
7077
|
+
// is no feature a clipboard write from the quick launcher would turn on
|
|
7078
|
+
// that is not already reachable from the main window.
|
|
7079
|
+
if (permission === 'clipboard-sanitized-write') {
|
|
7080
|
+
const url = webContents && typeof webContents.getURL === 'function' ? webContents.getURL() : null;
|
|
7081
|
+
return callback(isOwnRenderer(url));
|
|
7082
|
+
}
|
|
7008
7083
|
if (permission !== 'media') return callback(false);
|
|
7009
7084
|
if (!isMainWindowUrl(webContents)) return callback(false);
|
|
7010
7085
|
// `details.mediaTypes` names what was asked for: ['audio'] for dictation.
|
|
@@ -7015,6 +7090,12 @@ function bootstrap() {
|
|
|
7015
7090
|
return callback(true);
|
|
7016
7091
|
});
|
|
7017
7092
|
session.defaultSession.setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
|
|
7093
|
+
// Same grant as the request handler above — Electron queries the check
|
|
7094
|
+
// handler separately (`navigator.permissions.query`), and a mismatch
|
|
7095
|
+
// between the two is what made the earlier dictation grant read as
|
|
7096
|
+
// denied from the renderer's own feature detection (see the comment
|
|
7097
|
+
// above `setPermissionCheckHandler` is registered alongside for).
|
|
7098
|
+
if (permission === 'clipboard-sanitized-write') return isOwnRenderer(requestingOrigin);
|
|
7018
7099
|
if (permission !== 'media') return false;
|
|
7019
7100
|
if (!isMainWindowUrl(webContents)) return false;
|
|
7020
7101
|
return isOwnRenderer(requestingOrigin);
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "aegis-desktop",
|
|
3
3
|
"productName": "aegis one",
|
|
4
4
|
"desktopName": "aegis-desktop",
|
|
5
|
-
"version": "1.0.
|
|
5
|
+
"version": "1.0.59",
|
|
6
6
|
"description": "Thin Electron host for AEGIS — a local chat UI over the shared client/aegis.js transport. Ships transport + UI only; engine logic stays server-side.",
|
|
7
7
|
"author": {
|
|
8
8
|
"name": "AEGIS Code",
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
3
|
"use strict";const{contextBridge:contextBridge,ipcRenderer:ipcRenderer}=require("electron"),IPC_PREFIX="aegis:",MODEL_PREFIX="model:",SYNC_PREFIX="sync:",QUICK_PREFIX="quick:",QUEUE_PREFIX="queue:",AUTO_PREFIX="auto:",QUEUE_PROGRESS_CHANNEL="queue:progress",QUEUE_CHANGED_CHANNEL="queue:changed",CHAT_DELTA_CHANNEL="aegis:chatDelta",PTY_EVENT_CHANNEL="aegis:ptyEvent",UPDATE_STATUS_CHANNEL="aegis:updateStatus",ACCOUNT_STATUS_CHANNEL="aegis:accountStatusChanged",MENU_NEW_CHAT_CHANNEL="aegis:menuNewChat",MENU_SEARCH_CHANNEL="aegis:menuSearch",MENU_SEARCH_MEMORY_CHANNEL="aegis:menuSearchMemory",MENU_CREDITS_CHANNEL="aegis:menuCredits",MENU_PALETTE_CHANNEL="aegis:menuPalette",MENU_TOGGLE_SIDEBAR_CHANNEL="aegis:menuToggleSidebar",MENU_FIND_CHANNEL="aegis:menuFind",MENU_GO_BACK_CHANNEL="aegis:menuGoBack",MENU_GO_FORWARD_CHANNEL="aegis:menuGoForward",MENU_EXPORT_MARKDOWN_CHANNEL="aegis:menuExportMarkdown",MENU_EXPORT_JSON_CHANNEL="aegis:menuExportJson",MENU_FINGERPRINT_CHANNEL="aegis:menuFingerprint",MENU_GOOGLE_DRIVE_CHANNEL="aegis:menuGoogleDrive",DEEP_LINK_CHANNEL="aegis:deepLink",QUICK_LAUNCHER_PUSH_CHANNEL="aegis:quickLauncherPush";function invoke(e,n){return ipcRenderer.invoke("aegis:"+e,void 0===n?void 0:n)}function invokeModel(e,n){return ipcRenderer.invoke("model:"+e,void 0===n?void 0:n)}function invokeSync(e,n){return ipcRenderer.invoke("sync:"+e,void 0===n?void 0:n)}function invokeQuick(e,n){return ipcRenderer.invoke("quick:"+e,void 0===n?void 0:n)}function invokeQueue(e,n){return ipcRenderer.invoke("queue:"+e,void 0===n?void 0:n)}function invokeAuto(e,n){return ipcRenderer.invoke("auto:"+e,void 0===n?void 0:n)}function deltaListener(e,n){const o=e||null;return(e,i)=>{(i&&i.id?i.id:null)===o&&n(i)}}const api={status:()=>invoke("status"),attachments:Object.freeze({pathFor:e=>{try{const{webUtils:n}=require("electron");return n&&"function"==typeof n.getPathForFile&&n.getPathForFile(e)||""}catch{return""}},ingest:e=>invoke("attachments:ingest",{path:String(null==e?"":e)})}),setApiKey:e=>invoke("setApiKey",{key:e}),verifyApiKey:()=>invoke("verifyApiKey"),tokenBankBalance:()=>invoke("tokenBankBalance"),billingCheckout:()=>invoke("billingCheckout"),tokenBankTopup:e=>invoke("tokenBankTopup",{amountEur:e}),listModels:()=>invoke("listModels"),readTextFile:(e,n)=>{try{return ipcRenderer.sendSync("model:readTextFile",{file:e,cwd:n})}catch{return null}},chatCompletion:(e,n)=>{const o=e||{};if("function"!=typeof n)return invoke("chatCompletion",{...o,stream:!1});const i=deltaListener(o.sessionId,n),r=()=>ipcRenderer.removeListener("aegis:chatDelta",i);return ipcRenderer.on("aegis:chatDelta",i),invoke("chatCompletion",{...o,stream:!0}).then(e=>(r(),e),e=>{throw r(),e})},byokStatus:()=>invoke("byokStatus"),byokSet:(e,n)=>invoke("byokSet",{provider:e,apiKey:n}),memorySearch:(e,n)=>invoke("memorySearch",{query:e,limit:n}),memorySave:e=>invoke("memorySave",{entry:e}),memoryList:e=>invoke("memoryList",{limit:e}),verifyToken:e=>invoke("verifyToken",{token:e}),memoryActivate:e=>invoke("memoryActivate",{token:e}),memoryPull:e=>invoke("memoryPull",{since:e}),memorySaveBatch:e=>invoke("memorySaveBatch",{entries:e}),memoryImport:e=>invoke("memoryImport",e||{}),sessionsImportScan:()=>invoke("sessionsImportScan"),sessionsImport:e=>invoke("sessionsImport",e||{}),importConversation:e=>invoke("importConversation",e||{}),openExternal:e=>invoke("openExternal",{url:e}),fingerprintStatus:()=>invoke("fingerprintStatus"),fingerprintKeygen:e=>invoke("fingerprintKeygen",e||{}),fingerprintMint:e=>invoke("fingerprintMint",e||{}),fingerprintVerify:e=>invoke("fingerprintVerify",e||{}),fingerprintBackup:e=>invoke("fingerprintBackup",e||{}),
|
|
4
4
|
// The vault: publish a sealed record (default gdrive:AEGIS-AGPL/records),
|
|
5
|
-
fingerprintPublish:e=>invoke("fingerprintPublish",e||{}),fingerprintAnchor:e=>invoke("fingerprintAnchor",e||{}),fingerprintVault:()=>invoke("fingerprintVault"),fingerprintVaultAudit:()=>invoke("fingerprintVaultAudit"),getConfirmMode:()=>invoke("getConfirmMode"),setConfirmMode:e=>invoke("setConfirmMode",{enabled:Boolean(e)}),getDevMode:()=>invoke("getDevMode"),setDevMode:e=>invoke("setDevMode",{enabled:Boolean(e)}),getModelAutoSync:()=>invoke("getModelAutoSync"),setModelAutoSync:e=>invoke("setModelAutoSync",{enabled:Boolean(e)}),getAccountUsername:()=>invoke("getAccountUsername"),setAccountUsername:e=>invoke("setAccountUsername",{username:null==e?null:String(e)}),getFontScale:()=>invoke("getFontScale"),setFontScale:e=>invoke("setFontScale",{scale:Number(e)}),getAccent:()=>invoke("getAccent"),setAccent:e=>invoke("setAccent",{name:String(e)}),getPermissionMode:()=>invoke("getPermissionMode"),setPermissionMode:e=>invoke("setPermissionMode",{mode:e?"plan":null}),permRulesList:()=>invoke("permRulesList"),permRulesAdd:(e,n)=>invoke("permRulesAdd",{list:String(e||""),rule:String(n||"")}),permRulesRemove:(e,n)=>invoke("permRulesRemove",{list:String(e||""),rule:String(n||"")}),personaRead:()=>invoke("personaRead"),personaPatch:e=>invoke("personaPatch",{patch:e||{}}),getSandboxPolicy:()=>invoke("getSandboxPolicy"),setSandboxPolicy:(e,n)=>invoke("setSandboxPolicy",{mode:String(e||""),network:String(n||"")}),getVaultBackend:()=>invoke("getVaultBackend"),openCliFace:e=>invoke("openCliFace",{args:Array.isArray(e)?e.map(String):[]}),pty:Object.freeze({hello:()=>invoke("ptyHello",{}),exec:(e,n)=>invoke("ptyExec",{id:e,params:n||{}}),write:(e,n)=>invoke("ptyWrite",{id:e,data:String(null==n?"":n)}),resize:(e,n,o)=>invoke("ptyResize",{id:e,cols:Number(n)||0,rows:Number(o)||0}),cancel:e=>invoke("ptyCancel",{id:e}),onEvent:(e,n)=>{const o=(o,i)=>{i&&i.id===e&&n(i)};return ipcRenderer.on("aegis:ptyEvent",o),()=>ipcRenderer.removeListener("aegis:ptyEvent",o)}}),setVaultBackend:e=>invoke("setVaultBackend",{backend:String(e||"")}),telemetryEvent:(e,n)=>{const o=n||{};return invoke("telemetryEvent",{event:null==e?"":String(e),campaign:null==o.campaign?null:String(o.campaign),surface:null==o.surface?null:String(o.surface)})},telemetryReport:()=>invoke("telemetryReport"),covenantStatus:()=>invoke("covenantStatus"),covenantGapReport:()=>invoke("covenantGapReport"),getMemoryPersist:()=>invoke("memoryPersist.get"),setMemoryPersist:e=>invoke("memoryPersist.set",{enabled:Boolean(e)}),checkForUpdates:()=>invoke("checkForUpdates"),downloadUpdate:()=>invoke("downloadUpdate"),quitAndInstallUpdate:()=>invoke("quitAndInstallUpdate"),updateStatus:()=>invoke("updateStatus"),onUpdateStatus:e=>{const n=(n,o)=>e(o);return ipcRenderer.on("aegis:updateStatus",n),()=>ipcRenderer.removeListener("aegis:updateStatus",n)},accountStatus:()=>invoke("accountStatus"),registerAccount:()=>invoke("registerAccount"),onAccountStatus:e=>{const n=(n,o)=>e(o);return ipcRenderer.on(ACCOUNT_STATUS_CHANNEL,n),()=>ipcRenderer.removeListener(ACCOUNT_STATUS_CHANNEL,n)},driveSignIn:()=>invoke("driveSignIn"),driveConnect:()=>invoke("driveConnect"),driveStatus:()=>invoke("driveStatus"),driveSyncMemory:()=>invoke("driveSyncMemory"),driveBackupConversation:e=>invoke("driveBackupConversation",{sessionId:e}),speechStatus:()=>invoke("speechStatus"),speechSet:e=>{const n=e||{},o={};return"boolean"==typeof n.enabled&&(o.enabled=n.enabled),"string"==typeof n.engine&&(o.engine="local"===n.engine?"local":"none"),"string"==typeof n.model&&(o.model=n.model),"string"==typeof n.language&&(o.language=n.language),null!=n.maxSeconds&&Number.isFinite(Number(n.maxSeconds))&&(o.maxSeconds=Number(n.maxSeconds)),invoke("speechSet",o)},speechTranscribe:e=>{const n=e||{};return invoke("speechTranscribe",{audio:n.audio,ext:null==n.ext?"webm":String(n.ext)})},skillsList:()=>invoke("skillsList"),skillsRead:e=>invoke("skillsRead",{name:String(null==e?"":e)}),skillsCreate:e=>{const n=e||{};return invoke("skillsCreate",{name:String(null==n.name?"":n.name),description:String(null==n.description?"":n.description),body:String(null==n.body?"":n.body),targetDir:String(null==n.targetDir?"":n.targetDir)})},skillsRemove:e=>invoke("skillsRemove",{name:String(null==e?"":e)}),skillsImport:e=>{const n=e||{};return invoke("skillsImport",{url:String(null==n.url?"":n.url),name:String(null==n.name?"":n.name),targetDir:String(null==n.targetDir?"":n.targetDir)})},onMenuNewChat:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuNewChat",n),()=>ipcRenderer.removeListener("aegis:menuNewChat",n)},onMenuSearch:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuSearch",n),()=>ipcRenderer.removeListener("aegis:menuSearch",n)},onMenuSearchMemory:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuSearchMemory",n),()=>ipcRenderer.removeListener("aegis:menuSearchMemory",n)},onMenuCredits:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuCredits",n),()=>ipcRenderer.removeListener("aegis:menuCredits",n)},credits:()=>invoke("credits"),onMenuPalette:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuPalette",n),()=>ipcRenderer.removeListener("aegis:menuPalette",n)},onMenuToggleSidebar:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuToggleSidebar",n),()=>ipcRenderer.removeListener("aegis:menuToggleSidebar",n)},onMenuFind:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuFind",n),()=>ipcRenderer.removeListener("aegis:menuFind",n)},onMenuGoBack:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuGoBack",n),()=>ipcRenderer.removeListener("aegis:menuGoBack",n)},onMenuGoForward:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuGoForward",n),()=>ipcRenderer.removeListener("aegis:menuGoForward",n)},setNavState:e=>invoke("setNavState",e),onMenuExportMarkdown:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuExportMarkdown",n),()=>ipcRenderer.removeListener("aegis:menuExportMarkdown",n)},onMenuFingerprint:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuFingerprint",n),()=>ipcRenderer.removeListener("aegis:menuFingerprint",n)},onMenuGoogleDrive:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuGoogleDrive",n),()=>ipcRenderer.removeListener("aegis:menuGoogleDrive",n)},onMenuExportJson:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuExportJson",n),()=>ipcRenderer.removeListener("aegis:menuExportJson",n)},exportSession:(e,n)=>invoke("exportSession",{sessionId:e,format:n}),onDeepLink:e=>{const n=(n,o)=>e(o);return ipcRenderer.on("aegis:deepLink",n),()=>ipcRenderer.removeListener("aegis:deepLink",n)},onQuickLauncherPush:e=>{const n=(n,o)=>e(o);return ipcRenderer.on("aegis:quickLauncherPush",n),()=>ipcRenderer.removeListener("aegis:quickLauncherPush",n)}},models={listClasses:()=>invokeModel("listClasses"),listModels:e=>invokeModel("listModels",{class:e}),chat:(e,n)=>{const o=e||{};if("function"!=typeof n)return invokeModel("chat",o);const i=deltaListener(o.sessionId,n),r=()=>ipcRenderer.removeListener("aegis:chatDelta",i);return ipcRenderer.on("aegis:chatDelta",i),invokeModel("chat",o).then(e=>(r(),e),e=>{throw r(),e})},settings:{get:()=>invokeModel("settings.get"),set:(e,n)=>invokeModel("settings.set",{provider:e,baseURL:n&&n.baseURL,key:n&&n.key}),remove:e=>invokeModel("settings.remove",{provider:e})},userModels:{get:()=>invokeModel("userModels.get"),add:(e,n)=>invokeModel("userModels.add",{provider:e,model:n}),remove:(e,n)=>invokeModel("userModels.remove",{provider:e,model:n}),discover:e=>invokeModel("userModels.discover",{provider:e}),addAll:(e,n)=>invokeModel("userModels.addAll",{provider:e,ids:n}),canDiscover:e=>invokeModel("userModels.canDiscover",{provider:e}),discoverable:()=>invokeModel("userModels.discoverable"),syncPlan:e=>invokeModel("userModels.syncPlan",{only:e}),syncApply:(e,n)=>invokeModel("userModels.syncApply",{plan:e,only:n}),syncStatus:()=>invokeModel("userModels.syncStatus"),syncNow:e=>invokeModel("userModels.syncNow",{only:e})},cancel:e=>invokeModel("cancel",{sessionId:e}),respondApproval:(e,n)=>invokeModel("respondApproval",{approvalId:e,decision:n}),respondRoundsAsk:(e,n)=>invokeModel("respondRoundsAsk",{roundsAskId:e,decision:n}),clearApprovals:e=>invokeModel("clearApprovals",{sessionId:e}),listUndoable:e=>invokeModel("listUndoable",{sessionId:e}),undoMutation:(e,n)=>invokeModel("undoMutation",{sessionId:e,id:n})},sync={listSessions:()=>invokeSync("listSessions"),searchSessions:(e,n)=>invokeSync("searchSessions",{query:e,limit:n}),open:e=>invokeSync("open",{sessionId:e}),save:e=>invokeSync("save",e||{}),nameSession:e=>invokeSync("nameSession",{sessionId:e&&e.sessionId,prompt:e&&e.prompt,class:e&&e.class,model:e&&e.model}),append:(e,n)=>invokeSync("append",{sessionId:e,message:n}),delete:e=>invokeSync("delete",{sessionId:e}),rename:(e,n)=>invokeSync("rename",{sessionId:e,title:n}),push:()=>invokeSync("push"),pull:()=>invokeSync("pull"),status:()=>invokeSync("status"),auto:()=>invokeSync("auto"),memoryPersistState:()=>invokeSync("memoryPersistState")},quickLauncher={status:()=>invokeQuick("status"),setConfig:e=>invokeQuick("setConfig",{enabled:e&&e.enabled,shortcut:e&&e.shortcut}),pushToMain:e=>invokeQuick("pushToMain",e||{})},queue={enqueue:e=>invokeQueue("enqueue",queueTaskFields(e)),list:()=>invokeQueue("list"),clear:e=>invokeQueue("clear",{all:Boolean(e)}),entitlement:e=>invokeQueue("entitlement",{force:Boolean(e)}),retry:e=>queueWithId("retry",e),remove:e=>queueWithId("remove",e),drain:()=>invokeQueue("drain",{}),proceed:()=>invokeQueue("proceed",{}),stop:e=>{const n=queueTaskId(e);return invokeQueue("stop",null==n?{}:{id:n})},onProgress:e=>{if("function"!=typeof e)return()=>{};const n=(n,o)=>e(o);return ipcRenderer.on("queue:progress",n),()=>ipcRenderer.removeListener("queue:progress",n)},onChanged:e=>{if("function"!=typeof e)return()=>{};const n=()=>e();return ipcRenderer.on("queue:changed",n),()=>ipcRenderer.removeListener("queue:changed",n)}},auto={status:()=>invokeAuto("autoStatus"),setDrain:e=>{const n=e||{},o={enabled:Boolean(n.enabled)};return null!=n.intervalMs&&Number.isFinite(Number(n.intervalMs))&&(o.intervalMs=Number(n.intervalMs)),invokeAuto("autoSetDrain",o)},setMint:e=>{const n=e||{};return invokeAuto("autoSetMint",{enabled:Boolean(n.enabled),publish:Boolean(n.publish)})},sealNow:e=>invokeAuto("autoSealNow",{publish:Boolean(e)})};function queueTaskId(e){const n=Number(e);return Number.isInteger(n)&&n>0?n:null}function queueWithId(e,n){const o=queueTaskId(n);return null==o?Promise.resolve({ok:!1,reason:`${e} needs a task id`}):invokeQueue(e,{id:o})}function queueTaskFields(e){const n=e||{};return{task:String(null==n.task?"":n.task),cwd:String(null==n.cwd?"":n.cwd),class:null==n.class?null:String(n.class),model:null==n.model?null:String(n.model),effort:null==n.effort?null:String(n.effort),workers:null==n.workers?null:Number(n.workers),maxRounds:null==n.maxRounds?null:Number(n.maxRounds),fanout:Boolean(n.fanout),commit:Boolean(n.commit)}}contextBridge.exposeInMainWorld("aegis",Object.freeze(api)),contextBridge.exposeInMainWorld("models",Object.freeze(models)),contextBridge.exposeInMainWorld("sync",Object.freeze(sync)),contextBridge.exposeInMainWorld("quickLauncher",Object.freeze(quickLauncher)),contextBridge.exposeInMainWorld("queue",Object.freeze(queue)),contextBridge.exposeInMainWorld("auto",Object.freeze(auto));
|
|
5
|
+
fingerprintPublish:e=>invoke("fingerprintPublish",e||{}),fingerprintAnchor:e=>invoke("fingerprintAnchor",e||{}),fingerprintVault:()=>invoke("fingerprintVault"),fingerprintVaultAudit:()=>invoke("fingerprintVaultAudit"),getConfirmMode:()=>invoke("getConfirmMode"),setConfirmMode:e=>invoke("setConfirmMode",{enabled:Boolean(e)}),getDevMode:()=>invoke("getDevMode"),setDevMode:e=>invoke("setDevMode",{enabled:Boolean(e)}),getModelAutoSync:()=>invoke("getModelAutoSync"),setModelAutoSync:e=>invoke("setModelAutoSync",{enabled:Boolean(e)}),getAccountUsername:()=>invoke("getAccountUsername"),setAccountUsername:e=>invoke("setAccountUsername",{username:null==e?null:String(e)}),getFontScale:()=>invoke("getFontScale"),setFontScale:e=>invoke("setFontScale",{scale:Number(e)}),getAccent:()=>invoke("getAccent"),setAccent:e=>invoke("setAccent",{name:String(e)}),getPermissionMode:()=>invoke("getPermissionMode"),setPermissionMode:e=>invoke("setPermissionMode",{mode:e?"plan":null}),permRulesList:()=>invoke("permRulesList"),permRulesAdd:(e,n)=>invoke("permRulesAdd",{list:String(e||""),rule:String(n||"")}),permRulesRemove:(e,n)=>invoke("permRulesRemove",{list:String(e||""),rule:String(n||"")}),personaRead:()=>invoke("personaRead"),personaPatch:e=>invoke("personaPatch",{patch:e||{}}),getSandboxPolicy:()=>invoke("getSandboxPolicy"),setSandboxPolicy:(e,n)=>invoke("setSandboxPolicy",{mode:String(e||""),network:String(n||"")}),getVaultBackend:()=>invoke("getVaultBackend"),openCliFace:e=>invoke("openCliFace",{args:Array.isArray(e)?e.map(String):[]}),openPtyWindow:()=>invoke("openPtyWindow",{}),closePtyWindow:()=>invoke("closePtyWindow",{}),pty:Object.freeze({hello:()=>invoke("ptyHello",{}),exec:(e,n)=>invoke("ptyExec",{id:e,params:n||{}}),write:(e,n)=>invoke("ptyWrite",{id:e,data:String(null==n?"":n)}),resize:(e,n,o)=>invoke("ptyResize",{id:e,cols:Number(n)||0,rows:Number(o)||0}),cancel:e=>invoke("ptyCancel",{id:e}),onEvent:(e,n)=>{const o=(o,i)=>{i&&i.id===e&&n(i)};return ipcRenderer.on("aegis:ptyEvent",o),()=>ipcRenderer.removeListener("aegis:ptyEvent",o)}}),setVaultBackend:e=>invoke("setVaultBackend",{backend:String(e||"")}),telemetryEvent:(e,n)=>{const o=n||{};return invoke("telemetryEvent",{event:null==e?"":String(e),campaign:null==o.campaign?null:String(o.campaign),surface:null==o.surface?null:String(o.surface)})},telemetryReport:()=>invoke("telemetryReport"),covenantStatus:()=>invoke("covenantStatus"),covenantGapReport:()=>invoke("covenantGapReport"),getMemoryPersist:()=>invoke("memoryPersist.get"),setMemoryPersist:e=>invoke("memoryPersist.set",{enabled:Boolean(e)}),checkForUpdates:()=>invoke("checkForUpdates"),downloadUpdate:()=>invoke("downloadUpdate"),quitAndInstallUpdate:()=>invoke("quitAndInstallUpdate"),updateStatus:()=>invoke("updateStatus"),onUpdateStatus:e=>{const n=(n,o)=>e(o);return ipcRenderer.on("aegis:updateStatus",n),()=>ipcRenderer.removeListener("aegis:updateStatus",n)},accountStatus:()=>invoke("accountStatus"),registerAccount:()=>invoke("registerAccount"),onAccountStatus:e=>{const n=(n,o)=>e(o);return ipcRenderer.on(ACCOUNT_STATUS_CHANNEL,n),()=>ipcRenderer.removeListener(ACCOUNT_STATUS_CHANNEL,n)},driveSignIn:()=>invoke("driveSignIn"),driveConnect:()=>invoke("driveConnect"),driveStatus:()=>invoke("driveStatus"),driveSyncMemory:()=>invoke("driveSyncMemory"),driveBackupConversation:e=>invoke("driveBackupConversation",{sessionId:e}),speechStatus:()=>invoke("speechStatus"),speechSet:e=>{const n=e||{},o={};return"boolean"==typeof n.enabled&&(o.enabled=n.enabled),"string"==typeof n.engine&&(o.engine="local"===n.engine?"local":"none"),"string"==typeof n.model&&(o.model=n.model),"string"==typeof n.language&&(o.language=n.language),null!=n.maxSeconds&&Number.isFinite(Number(n.maxSeconds))&&(o.maxSeconds=Number(n.maxSeconds)),invoke("speechSet",o)},speechTranscribe:e=>{const n=e||{};return invoke("speechTranscribe",{audio:n.audio,ext:null==n.ext?"webm":String(n.ext)})},skillsList:()=>invoke("skillsList"),skillsRead:e=>invoke("skillsRead",{name:String(null==e?"":e)}),skillsCreate:e=>{const n=e||{};return invoke("skillsCreate",{name:String(null==n.name?"":n.name),description:String(null==n.description?"":n.description),body:String(null==n.body?"":n.body),targetDir:String(null==n.targetDir?"":n.targetDir)})},skillsRemove:e=>invoke("skillsRemove",{name:String(null==e?"":e)}),skillsImport:e=>{const n=e||{};return invoke("skillsImport",{url:String(null==n.url?"":n.url),name:String(null==n.name?"":n.name),targetDir:String(null==n.targetDir?"":n.targetDir)})},onMenuNewChat:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuNewChat",n),()=>ipcRenderer.removeListener("aegis:menuNewChat",n)},onMenuSearch:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuSearch",n),()=>ipcRenderer.removeListener("aegis:menuSearch",n)},onMenuSearchMemory:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuSearchMemory",n),()=>ipcRenderer.removeListener("aegis:menuSearchMemory",n)},onMenuCredits:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuCredits",n),()=>ipcRenderer.removeListener("aegis:menuCredits",n)},credits:()=>invoke("credits"),onMenuPalette:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuPalette",n),()=>ipcRenderer.removeListener("aegis:menuPalette",n)},onMenuToggleSidebar:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuToggleSidebar",n),()=>ipcRenderer.removeListener("aegis:menuToggleSidebar",n)},onMenuFind:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuFind",n),()=>ipcRenderer.removeListener("aegis:menuFind",n)},onMenuGoBack:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuGoBack",n),()=>ipcRenderer.removeListener("aegis:menuGoBack",n)},onMenuGoForward:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuGoForward",n),()=>ipcRenderer.removeListener("aegis:menuGoForward",n)},setNavState:e=>invoke("setNavState",e),onMenuExportMarkdown:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuExportMarkdown",n),()=>ipcRenderer.removeListener("aegis:menuExportMarkdown",n)},onMenuFingerprint:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuFingerprint",n),()=>ipcRenderer.removeListener("aegis:menuFingerprint",n)},onMenuGoogleDrive:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuGoogleDrive",n),()=>ipcRenderer.removeListener("aegis:menuGoogleDrive",n)},onMenuExportJson:e=>{const n=()=>e();return ipcRenderer.on("aegis:menuExportJson",n),()=>ipcRenderer.removeListener("aegis:menuExportJson",n)},exportSession:(e,n)=>invoke("exportSession",{sessionId:e,format:n}),onDeepLink:e=>{const n=(n,o)=>e(o);return ipcRenderer.on("aegis:deepLink",n),()=>ipcRenderer.removeListener("aegis:deepLink",n)},onQuickLauncherPush:e=>{const n=(n,o)=>e(o);return ipcRenderer.on("aegis:quickLauncherPush",n),()=>ipcRenderer.removeListener("aegis:quickLauncherPush",n)}},models={listClasses:()=>invokeModel("listClasses"),listModels:e=>invokeModel("listModels",{class:e}),chat:(e,n)=>{const o=e||{};if("function"!=typeof n)return invokeModel("chat",o);const i=deltaListener(o.sessionId,n),r=()=>ipcRenderer.removeListener("aegis:chatDelta",i);return ipcRenderer.on("aegis:chatDelta",i),invokeModel("chat",o).then(e=>(r(),e),e=>{throw r(),e})},settings:{get:()=>invokeModel("settings.get"),set:(e,n)=>invokeModel("settings.set",{provider:e,baseURL:n&&n.baseURL,key:n&&n.key}),remove:e=>invokeModel("settings.remove",{provider:e})},userModels:{get:()=>invokeModel("userModels.get"),add:(e,n)=>invokeModel("userModels.add",{provider:e,model:n}),remove:(e,n)=>invokeModel("userModels.remove",{provider:e,model:n}),discover:e=>invokeModel("userModels.discover",{provider:e}),addAll:(e,n)=>invokeModel("userModels.addAll",{provider:e,ids:n}),canDiscover:e=>invokeModel("userModels.canDiscover",{provider:e}),discoverable:()=>invokeModel("userModels.discoverable"),syncPlan:e=>invokeModel("userModels.syncPlan",{only:e}),syncApply:(e,n)=>invokeModel("userModels.syncApply",{plan:e,only:n}),syncStatus:()=>invokeModel("userModels.syncStatus"),syncNow:e=>invokeModel("userModels.syncNow",{only:e})},cancel:e=>invokeModel("cancel",{sessionId:e}),respondApproval:(e,n)=>invokeModel("respondApproval",{approvalId:e,decision:n}),respondRoundsAsk:(e,n)=>invokeModel("respondRoundsAsk",{roundsAskId:e,decision:n}),clearApprovals:e=>invokeModel("clearApprovals",{sessionId:e}),listUndoable:e=>invokeModel("listUndoable",{sessionId:e}),undoMutation:(e,n)=>invokeModel("undoMutation",{sessionId:e,id:n})},sync={listSessions:()=>invokeSync("listSessions"),searchSessions:(e,n)=>invokeSync("searchSessions",{query:e,limit:n}),open:e=>invokeSync("open",{sessionId:e}),save:e=>invokeSync("save",e||{}),nameSession:e=>invokeSync("nameSession",{sessionId:e&&e.sessionId,prompt:e&&e.prompt,class:e&&e.class,model:e&&e.model}),append:(e,n)=>invokeSync("append",{sessionId:e,message:n}),delete:e=>invokeSync("delete",{sessionId:e}),rename:(e,n)=>invokeSync("rename",{sessionId:e,title:n}),push:()=>invokeSync("push"),pull:()=>invokeSync("pull"),status:()=>invokeSync("status"),auto:()=>invokeSync("auto"),memoryPersistState:()=>invokeSync("memoryPersistState")},quickLauncher={status:()=>invokeQuick("status"),setConfig:e=>invokeQuick("setConfig",{enabled:e&&e.enabled,shortcut:e&&e.shortcut}),pushToMain:e=>invokeQuick("pushToMain",e||{})},queue={enqueue:e=>invokeQueue("enqueue",queueTaskFields(e)),list:()=>invokeQueue("list"),clear:e=>invokeQueue("clear",{all:Boolean(e)}),entitlement:e=>invokeQueue("entitlement",{force:Boolean(e)}),retry:e=>queueWithId("retry",e),remove:e=>queueWithId("remove",e),drain:()=>invokeQueue("drain",{}),proceed:()=>invokeQueue("proceed",{}),stop:e=>{const n=queueTaskId(e);return invokeQueue("stop",null==n?{}:{id:n})},onProgress:e=>{if("function"!=typeof e)return()=>{};const n=(n,o)=>e(o);return ipcRenderer.on("queue:progress",n),()=>ipcRenderer.removeListener("queue:progress",n)},onChanged:e=>{if("function"!=typeof e)return()=>{};const n=()=>e();return ipcRenderer.on("queue:changed",n),()=>ipcRenderer.removeListener("queue:changed",n)}},auto={status:()=>invokeAuto("autoStatus"),setDrain:e=>{const n=e||{},o={enabled:Boolean(n.enabled)};return null!=n.intervalMs&&Number.isFinite(Number(n.intervalMs))&&(o.intervalMs=Number(n.intervalMs)),invokeAuto("autoSetDrain",o)},setMint:e=>{const n=e||{};return invokeAuto("autoSetMint",{enabled:Boolean(n.enabled),publish:Boolean(n.publish)})},sealNow:e=>invokeAuto("autoSealNow",{publish:Boolean(e)})};function queueTaskId(e){const n=Number(e);return Number.isInteger(n)&&n>0?n:null}function queueWithId(e,n){const o=queueTaskId(n);return null==o?Promise.resolve({ok:!1,reason:`${e} needs a task id`}):invokeQueue(e,{id:o})}function queueTaskFields(e){const n=e||{};return{task:String(null==n.task?"":n.task),cwd:String(null==n.cwd?"":n.cwd),class:null==n.class?null:String(n.class),model:null==n.model?null:String(n.model),effort:null==n.effort?null:String(n.effort),workers:null==n.workers?null:Number(n.workers),maxRounds:null==n.maxRounds?null:Number(n.maxRounds),fanout:Boolean(n.fanout),commit:Boolean(n.commit)}}contextBridge.exposeInMainWorld("aegis",Object.freeze(api)),contextBridge.exposeInMainWorld("models",Object.freeze(models)),contextBridge.exposeInMainWorld("sync",Object.freeze(sync)),contextBridge.exposeInMainWorld("quickLauncher",Object.freeze(quickLauncher)),contextBridge.exposeInMainWorld("queue",Object.freeze(queue)),contextBridge.exposeInMainWorld("auto",Object.freeze(auto));
|