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
|
@@ -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 ANSI_RE=/\x1b\[[0-9;]*[A-Za-z]/g,{caps:caps,cellWidth:cellWidth}=require("./caps.js"),cwidth=t=>cellWidth(t);function stripAnsi(t){return String(t).replace(ANSI_RE,"")}function w(t){let e=0;for(const o of stripAnsi(t))e+=cwidth(o);return e}function clip(t,e){if(w(t)<=e)return t;let o="",
|
|
3
|
+
"use strict";const ANSI_RE=/\x1b\[[0-9;]*[A-Za-z]/g,{caps:caps,cellWidth:cellWidth}=require("./caps.js"),cwidth=t=>cellWidth(t);function stripAnsi(t){return String(t).replace(ANSI_RE,"")}function w(t){let e=0;for(const o of stripAnsi(t))e+=cwidth(o);return e}function clip(t,e){if(w(t)<=e)return t;let o="",n=0;for(const i of String(t)){const t=cwidth(i);if(n+t>e)break;o+=i,n+=t}return o}function pad(t,e){const o=clip(t,e);return o+" ".repeat(Math.max(0,e-w(o)))}function padStart(t,e){const o=clip(t,e);return" ".repeat(Math.max(0,e-w(o)))+o}function span(t,e){return{t:e,s:t,w:w(e)}}const lineWidth=t=>t.reduce((t,e)=>t+e.w,0);function padLine(t,e){let o=0;const n=[];for(const i of t){if(o>=e)break;let t=i.t,s=i.w;if(o+s>e){const n=e-o;let i="",r=0;for(const e of[...t]){const t=w(e);if(r+t>n)break;i+=e,r+=t}t=i,s=r}n.push({t:t,s:i.s,w:s}),o+=s}return o<e&&n.push(span(""," ".repeat(e-o))),n}const getSize=()=>{const t=caps();return{cols:t.cols,rows:t.rows}};function wrapLine(t,e,o=""){const n=Math.max(8,e);if(w(t)<=n)return[t];const i=t.split(" "),s=[];let r="";for(const t of i){const e=r?`${r} ${t}`:t;if(w(e)<=n){r=e;continue}if(r&&s.push(r),w(t)<=n){r=t;continue}let o=t;for(;w(o)>n;){const t=clip(o,n);s.push(t),o=o.slice(t.length)}r=o}return!r&&s.length||s.push(r),s}function wrapBlock(t,e,o="",n=!1){const i=[];for(const n of String(t).split("\n"))""!==n?wrapLine(n,e-w(o)).forEach(t=>i.push(o+t)):i.push("");return i}const ESC={hideCursor:"[?25l",showCursor:"[?25h",clearToEnd:"[0K",clearLine:"[2K",clearScreen:"[2J[H",up:t=>t>0?`[${t}A`:"",down:t=>t>0?`[${t}B`:"",col:t=>`[${t}G`,eraseDown:"[0J"},hideCursor=()=>process.stdout.write("[?25l"),showCursor=()=>process.stdout.write("[?25h"),moveTo=(t,e)=>process.stdout.write(`[${t};${e}H`);function clearScreen(){process.stdout.write("[2J[H")}let inAlt=!1;function enterAltScreen(){inAlt||(inAlt=!0,process.stdout.write("[?1049h"))}function leaveAltScreen(){inAlt&&(inAlt=!1,process.stdout.write("[?1049l"),flushExitNotice())}let exitNotice=null;function queueExitNotice(t){exitNotice=t}function flushExitNotice(){if(null===exitNotice)return;const t=exitNotice;exitNotice=null,process.stdout.write(t)}const hasExitNotice=()=>null!==exitNotice,isAltScreen=()=>inAlt,enableBracketedPaste=()=>process.stdout.write("[?2004h"),disableBracketedPaste=()=>process.stdout.write("[?2004l"),enableMouseTracking=()=>process.stdout.write("[?1000h[?1002h[?1006h"),disableMouseTracking=()=>process.stdout.write("[?1000l[?1002l[?1006l"),SELECT_ON="[7m",SELECT_OFF="[27m";function selectionRange(t,e){return t.row<e.row||t.row===e.row&&t.col<=e.col?{startRow:t.row,startCol:t.col,endRow:e.row,endCol:e.col}:{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function sliceLine(t,e,o){const n=[];let i=0;for(const s of t){const t=i;if(i+=s.w,i<=e||t>=o)continue;let r=s.t,c=t;if(c<e){const t=e-c;let o=0,n=0;for(const e of r){if(o>=t)break;o+=w(e),n+=e.length}r=r.slice(n),c+=o}if(c+w(r)>o){let t=0,e="";for(const n of r){const i=w(n);if(c+t+i>o)break;e+=n,t+=i}r=e}r&&n.push({t:r,s:s.s,w:w(r)})}return n}function selectionText(t,e){const o=[];for(let n=e.startRow;n<=e.endRow;n++){const i=t[n]||[],s=n===e.startRow?e.startCol:0,r=n===e.endRow?e.endCol:1/0;o.push(sliceLine(i,s,r).map(t=>t.t).join("").replace(/[ \t]+$/,""))}for(;o.length&&""===o[0];)o.shift();for(;o.length&&""===o[o.length-1];)o.pop();return o.join("\n")}function applySelection(t,e,o){const n=t.slice();for(let t=e.startRow;t<=e.endRow;t++){if(t<0||t>=n.length)continue;const i=padLine(n[t]||[],o),s=t===e.startRow?e.startCol:0,r=t===e.endRow?e.endCol:o,c=sliceLine(i,s,r);c.length&&(n[t]=[...sliceLine(i,0,s),{t:"",s:"[7m",w:0},...c,{t:"",s:"[27m",w:0},...sliceLine(i,r,o)])}return n}function paint(t){const{rows:e,cols:o}=getSize();let n="[H";for(let i=0;i<e;i++){n+="[0m";const s=t[i];if(s){const t=padLine(s,o);for(const e of t)n+=e.s+e.t;n+="[0K"}else n+="[0K";i<e-1&&(n+="\n")}n+="[0m",process.stdout.write(n)}function paintFrom(t,e){const{rows:o,cols:n}=getSize();let i="";for(let s=0;s<o-e;s++){const o=t[e+s];if(s>0&&(i+="\n"),i+="[0K",i+="[0m",o){const t=padLine(o,n);for(const e of t)i+=e.s+e.t}}i+="[0m",process.stdout.write(i)}function termWidth(t=80){const{cols:e}=getSize();return e>0?e:Math.max(20,t)}class LiveRegion{constructor(t=process.stdout){this.out=t,this.rows=0,this.active=!1}update(t){const e=Math.max(1,getSize().cols),o=t.reduce((t,o)=>t+Math.max(1,Math.ceil(w(o)/e)),0),n=t.map(t=>ESC.col(1)+t+ESC.clearToEnd).join("\n");this.active?this.out.write(ESC.col(1)+ESC.up(this.rows-1)+ESC.eraseDown+n):(this.out.write(n),this.active=!0),this.rows=o}clear(){this.active&&(this.out.write(ESC.col(1)+ESC.up(this.rows-1)+ESC.eraseDown),this.rows=0,this.active=!1)}}module.exports={queueExitNotice:queueExitNotice,flushExitNotice:flushExitNotice,hasExitNotice:hasExitNotice,w:w,clip:clip,pad:pad,padStart:padStart,stripAnsi:stripAnsi,wrapLine:wrapLine,wrapBlock:wrapBlock,span:span,lineWidth:lineWidth,padLine:padLine,paint:paint,paintFrom:paintFrom,getSize:getSize,EC:ESC,hideCursor:hideCursor,showCursor:showCursor,moveTo:moveTo,clearScreen:clearScreen,enterAltScreen:enterAltScreen,leaveAltScreen:leaveAltScreen,isAltScreen:isAltScreen,enableBracketedPaste:enableBracketedPaste,disableBracketedPaste:disableBracketedPaste,enableMouseTracking:enableMouseTracking,disableMouseTracking:disableMouseTracking,SELECT_ON:"[7m",SELECT_OFF:"[27m",selectionRange:selectionRange,sliceLine:sliceLine,selectionText:selectionText,applySelection:applySelection,LiveRegion:LiveRegion,termWidth:termWidth};
|
|
@@ -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};
|
|
@@ -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{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,"..",".."),SALT="aegis-desktop-interlock-v1",PAD="aegis-desktop-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).toString(16)}return t}const UNITS=Object.freeze([{id:"d1",rel:Buffer.from("bWFpbi5qcw==","base64").toString("utf8")},{id:"d2",rel:Buffer.from("bGliL2xvY2FsL3NoZWxsLmpz","base64").toString("utf8")},{id:"d3",rel:Buffer.from("bGliL2xvY2FsL3Rvb2xzLmpz","base64").toString("utf8")},{id:"d4",rel:Buffer.from("bGliL2xvY2FsL2V4ZWMtcGxhbi5qcw==","base64").toString("utf8")},{id:"d5",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3guanM=","base64").toString("utf8")},{id:"d6",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tcnVsZXMuanM=","base64").toString("utf8")},{id:"d7",rel:Buffer.from("bGliL2xvY2FsL3Blcm0td3JpdGUuanM=","base64").toString("utf8")},{id:"d8",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tc3RvcmUuanM=","base64").toString("utf8")},{id:"d9",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtc2VhdGJlbHQuanM=","base64").toString("utf8")},{id:"d10",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYXBwY29udGFpbmVyLmpz","base64").toString("utf8")},{id:"d11",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYndyYXAuanM=","base64").toString("utf8")}]),SEALED="
|
|
3
|
+
"use strict";const{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,"..",".."),SALT="aegis-desktop-interlock-v1",PAD="aegis-desktop-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).toString(16)}return t}const UNITS=Object.freeze([{id:"d1",rel:Buffer.from("bWFpbi5qcw==","base64").toString("utf8")},{id:"d2",rel:Buffer.from("bGliL2xvY2FsL3NoZWxsLmpz","base64").toString("utf8")},{id:"d3",rel:Buffer.from("bGliL2xvY2FsL3Rvb2xzLmpz","base64").toString("utf8")},{id:"d4",rel:Buffer.from("bGliL2xvY2FsL2V4ZWMtcGxhbi5qcw==","base64").toString("utf8")},{id:"d5",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3guanM=","base64").toString("utf8")},{id:"d6",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tcnVsZXMuanM=","base64").toString("utf8")},{id:"d7",rel:Buffer.from("bGliL2xvY2FsL3Blcm0td3JpdGUuanM=","base64").toString("utf8")},{id:"d8",rel:Buffer.from("bGliL2xvY2FsL3Blcm0tc3RvcmUuanM=","base64").toString("utf8")},{id:"d9",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtc2VhdGJlbHQuanM=","base64").toString("utf8")},{id:"d10",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYXBwY29udGFpbmVyLmpz","base64").toString("utf8")},{id:"d11",rel:Buffer.from("bGliL2xvY2FsL3NhbmRib3gtYndyYXAuanM=","base64").toString("utf8")}]),SEALED="d52aecc5027b818f4bce66299286d3c2ff1d36ed34f1ad9e60fd3e0314e6b062";function check(){const e=[];for(const t of UNITS){const r=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(r))return{tripped:!0,code:"d1",units:UNITS.length};try{e.push(sha256(readFileSync(r)))}catch{return{tripped:!0,code:"d1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),r=SEALED.trim();return 64!==r.length?{tripped:!0,code:"d2",units:UNITS.length}:unmask(r)!==t?{tripped:!0,code:"d3",units:UNITS.length}:{tripped:!1,code:null,units:UNITS.length}}function line(e){return e&&e.tripped?`aegis-desktop: reduced mode (${e.code}) — this build is not the one that was published.\n`:null}let ARMED=null;function armed(){if(null!==ARMED)return ARMED;let e;try{e=check()}catch{e={tripped:!0,code:"d2",units:UNITS.length}}if(ARMED=Boolean(e.tripped),ARMED){process.env.AEGIS_REDUCED_MODE="1";const t=line(e);t&&process.stderr.write(t)}return ARMED}function sealOf(e){const t=e.map(e=>sha256(readFileSync(e)));return sha256(`${SALT}\n${t.join("\n")}`)}module.exports={UNITS:UNITS,SALT:SALT,PAD:PAD,check:check,armed:armed,line:line,sealOf:sealOf,mask:unmask};
|
|
@@ -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};
|