aegis-desktop 1.0.19 → 1.0.21

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.
@@ -1,3 +1,714 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{spawn:spawn,spawnSync:spawnSync}=require("node:child_process"),crypto=require("node:crypto");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`shell.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const IS_WIN32=platform.IS_WIN32,OUTPUT_CAP=3e4,MAX_TIMEOUT=6e5,DEFAULT_TIMEOUT=12e4,POSIX_SHELL_NAMES=["bash","sh","dash","ksh","zsh"],POSIX_FALLBACK_NAMES=["bash","sh"],POSIX_PROBE="if [ 1 -eq 1 ]; then exit 0; fi",SHELL_PROBE_TIMEOUT=4e3;function shellName(e){return String(e||"").trim().split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/,"")}function isPosixShellName(e){return POSIX_SHELL_NAMES.includes(shellName(e))}function probePosixShell(e,{env:s,timeout:t=SHELL_PROBE_TIMEOUT}={}){try{const n=spawnSync(e,["-c",POSIX_PROBE],{env:s,encoding:"utf8",timeout:t,windowsHide:!0,stdio:"ignore"});return!n.error&&0===n.status}catch{return!1}}function shellSeams(e){const s=e&&"object"==typeof e?e:{};return{platform:"string"==typeof s.platform&&s.platform?s.platform:process.platform,env:s.env&&"object"==typeof s.env?s.env:process.env,exists:"function"==typeof s.exists?s.exists:void 0,probe:"function"==typeof s.probe?s.probe:void 0,injected:"function"==typeof s.probe||"function"==typeof s.exists}}function considerPosixCandidate(e,s,t,n){const i=String(s.cmd||"").trim();if(!i)return t.push({candidate:s.source||"(unset)",ok:!1,reason:"unset"}),null;if(!isPosixShellName(i))return t.push({candidate:i,ok:!1,reason:`${s.source||"candidate"} is not a POSIX shell — ${shellName(i)||i} is a different language (fish/csh/nu), so it was never executed and never sent POSIX syntax`}),null;const o=platform.resolveExecutable(i,{platform:e.platform,env:e.env,exists:e.exists});if(!o)return t.push({candidate:i,ok:!1,reason:/[\\/]/.test(i)?"not present":"not found on PATH"}),null;const r=e.probe?Boolean(e.probe(o,["-c",POSIX_PROBE])):probePosixShell(o,{env:e.env});return n.push(o),r?(t.push({candidate:o,ok:!0,reason:"verified: one `-c` POSIX script exited 0"}),{ok:!0,cmd:o,arg:"-c",kind:"posix-sh",source:s.source,verified:!0}):(t.push({candidate:o,ok:!1,reason:`failed the POSIX probe (\`-c\` with \`${POSIX_PROBE}\` did not exit 0) — refused`}),null)}function resolvePosixSessionShell(e){const s=[],t=[],n=String(e.env&&e.env.SHELL||"").trim(),i=[];n?i.push({cmd:n,source:"$SHELL"}):s.push({candidate:"$SHELL",ok:!1,reason:"$SHELL is unset"});for(const e of POSIX_FALLBACK_NAMES)i.push({cmd:e,source:`PATH:${e}`});let o=null;for(const n of i)if(o=considerPosixCandidate(e,n,s,t),o)break;const r=n&&!isPosixShellName(n)?n:null;return o?{...o,unsupported:r,caveat:r?`$SHELL is ${r}, which is not a POSIX shell — the session runs the POSIX dialect through ${o.cmd} instead, and ${r} is never sent brace groups, \`exec 2>&1\` or \`$?\``:null,error:null,executed:t,tried:s}:{ok:!1,cmd:null,arg:null,kind:null,source:"refused",verified:!1,unsupported:r,caveat:null,error:r?`exec: refusing to run — $SHELL is "${r}", which is not a POSIX shell (fish/csh/nushell are a different language), and no sh/bash could be verified on PATH to run the POSIX dialect instead. Set SHELL to bash or sh, or put one on PATH.`:`exec: no POSIX shell available — $SHELL is ${n?`"${n}"`:"unset"} and no sh/bash passed the POSIX probe; set SHELL to bash or sh, or put one on PATH.`,executed:t,tried:s}}const SHELL_CACHE=new Map;function resolveSessionShell(e={}){const s=shellSeams(e);if("win32"===s.platform){const e=platform.shellSpec({platform:"win32",env:s.env}),t=platform.resolveExecutable("powershell",{platform:"win32",env:s.env,exists:s.exists})||"powershell.exe";return{ok:!0,cmd:t,arg:"-",kind:"powershell",source:"powershell.exe",verified:!0,unsupported:null,caveat:null,error:null,oneShot:{cmd:t,arg:"-Command",kind:"powershell",source:"powershell.exe"},executed:[],tried:[{candidate:t,ok:!0,reason:"the Windows default (PowerShell session AND one-shot)"},{candidate:e.cmd,ok:!1,reason:"cmd.exe is never used for one-shot: it cannot parse the PowerShell quoting the session teaches"}]}}const t=[s.platform,s.env&&s.env.SHELL,s.env&&s.env.PATH].join("\0");if(!s.injected&&SHELL_CACHE.has(t))return SHELL_CACHE.get(t);const n=resolvePosixSessionShell(s);return s.injected||SHELL_CACHE.set(t,n),n}const{cap:spillCap}=require("./spill.js");function cap(e){return spillCap(e,OUTPUT_CAP)}const TAIL_KEEP=65536,BUFFER_CEILING=OUTPUT_CAP+TAIL_KEEP,ELISION="\n… (earlier output elided — command produced more than the buffer ceiling)\n";function appendBounded(e,s){const t=e+s;return t.length<=BUFFER_CEILING?t:t.slice(0,OUTPUT_CAP)+ELISION+t.slice(-TAIL_KEEP)}function oneShotShellSpec(e={}){const s=resolveSessionShell(e);if(!s.ok)return{ok:!1,cmd:null,arg:null,kind:null,error:s.error,spec:s};if("powershell"===s.kind){const t=s.oneShot||platform.shellSpec({platform:"win32",env:shellSeams(e).env});return{ok:!0,cmd:t.cmd,arg:t.arg,kind:t.kind||"powershell",error:null,spec:s}}return{ok:!0,cmd:s.cmd,arg:s.arg,kind:"posix-sh",error:null,spec:s}}function oneShotShell({command:e,timeout:s=12e4,working_directory:t,shellOptions:n}={}){return new Promise((i=>{const o=shellSeams(n),r=resolveSessionShell(n);if(!r||!r.ok)return void i({content:r&&r.error||"exec: no usable shell",isError:!0});const l="powershell"===r.kind?r.oneShot:r,h=spawn(l.cmd,[l.arg,String(e||"")],{cwd:t||process.cwd(),timeout:Math.min(Number(s)||12e4,6e5),env:o.env});let c="",d="";h.stdout.on("data",(e=>{c=appendBounded(c,e.toString())})),h.stderr.on("data",(e=>{d=appendBounded(d,e.toString())})),h.on("error",(e=>i({content:`error: ${e.message}`,isError:!0}))),h.on("close",(e=>{const s=`${c}${d?`\n${d}`:""}`.trim()||`(exit ${e})`;i({content:cap(s),isError:0!==e})}))}))}class ShellSession{constructor({cwd:e,shellOptions:s}={}){this.sentinel=`__AEGIS_SH_${crypto.randomBytes(8).toString("hex")}__`,this.marker=`${this.sentinel}EXIT:`,this.buf="",this.alive=!1,this._pending=null,this.cwd=e||process.cwd(),this.disposed=!1,this._respawns=0,this._degradedNoted=!1,this.shellOptions=s||{},this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(e)}_start(e){if(!this.shell||!this.shell.ok)return void(this.alive=!1);const s=shellSeams(this.shellOptions).env;try{this.child="powershell"===this.shell.kind?spawn(this.shell.cmd,["-NoLogo","-NoProfile","-NonInteractive","-Command","-"],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]}):spawn(this.shell.cmd,[],{cwd:e||process.cwd(),env:s,stdio:["pipe","pipe","pipe"]})}catch{return void(this.alive=!1)}this.alive=!0;const t=e=>{this.buf=appendBounded(this.buf,e.toString()),this._pending&&this._pending()};if(this.child.stdout.on("data",t),this.child.stderr.on("data",t),this.child.on("exit",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),this.child.on("error",(()=>{this.alive=!1,this._pending&&this._pending(!0)})),"posix-sh"===this.shell.kind)try{this.child.stdin.write("exec 2>&1\n")}catch{this.alive=!1}}run(e,{timeout:s=12e4,working_directory:t}={}){const n=this.shell&&"posix-sh"===this.shell.kind&&this.shell.verified;if(!this.alive||!this.child||this.shell&&"posix-sh"===this.shell.kind&&!n)return!this.alive&&this.shellError?Promise.resolve({content:this.shellError,isError:!0}):!this.alive&&!this.disposed&&this._respawns<1&&(this._respawns+=1,this.buf="",this.shell=resolveSessionShell(this.shellOptions),this.shellError=this.shell.ok?null:this.shell.error,this._start(this.cwd),this.alive)?this.run(e,{timeout:s,working_directory:t}):oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>this._noteDegraded(e,this.alive?"no usable session dialect":"the persistent session is not running")));let i=String(e||"");return new Promise((o=>{let r=!1;const l=e=>{r||(r=!0,clearTimeout(h),this._pending=null,o(e))},h=setTimeout((()=>{const e=cap(this.buf.trim());this.dispose(),l({content:`${e}${e?"\n":""}(timed out after ${s}ms)`,isError:!0})}),Math.min(Number(s)||12e4,6e5));let c;if(this._pending=e=>{if(e&&!this.buf.includes(this.marker))return void l({content:cap(this.buf.trim())||"(shell session ended)",isError:!0});const s=this.buf.indexOf(this.marker);if(-1===s)return;const t=this.buf.slice(s+this.marker.length),n=t.indexOf("\n");if(-1===n)return;const i=parseInt(t.slice(0,n),10),o=this.buf.slice(0,s).replace(/\n+$/,"");this.buf=t.slice(n+1),l({content:cap(o||`(exit ${i})`),isError:0!==i})},n)t&&(i=`( cd ${shq(t)} && ${i} )`),c=`{ ${i.trim()?i:":"}\n} </dev/null\nprintf '\\n%s%d\\n' '${this.sentinel}EXIT:' "$?"\n`;else{const e=i.trim()?i:"Write-Output $null",s="$__c = if ($LASTEXITCODE -ne $null) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }";c=t?`Push-Location -LiteralPath ${pshq(t)}\ntry {\n${e}\n${s}\n} finally {\nPop-Location\n}\n`:`${e}\n${s}\n`,c+=`Write-Output ("${this.marker}" + $__c)\n`}try{this.child.stdin.write(c)}catch{return this.alive=!1,void oneShotShell({command:e,timeout:s,working_directory:t,shellOptions:this.shellOptions}).then((e=>l(this._noteDegraded(e,"the session stdin rejected the command"))))}this._pending&&this._pending()}))}_noteDegraded(e,s){const t=e&&"object"==typeof e?e:{content:String(null==e?"":e),isError:!0};if(this._degradedNoted)return t;this._degradedNoted=!0;const n=`[shell_degraded] ran one-shot via ${this.shell&&this.shell.cmd?this.shell.cmd:"unknown shell"} (${s}); session dialect was ${this.shell&&this.shell.kind?this.shell.kind:"none"} — quoting contracts may differ`;return{...t,content:`${n}\n${t.content||""}`}}dispose(){if(this.disposed=!0,this.alive=!1,this.child){try{this.child.stdin.end()}catch{}try{this.child.kill("SIGKILL")}catch{}this.child=null}}}function shq(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function pshq(e){return`'${String(e).replace(/'/g,"''")}'`}module.exports={ShellSession:ShellSession,oneShotShell:oneShotShell,IS_WIN32:IS_WIN32,resolveSessionShell:resolveSessionShell,oneShotShellSpec:oneShotShellSpec,isPosixShellName:isPosixShellName,POSIX_SHELL_NAMES:POSIX_SHELL_NAMES,POSIX_PROBE:POSIX_PROBE,appendBounded:appendBounded,OUTPUT_CAP:OUTPUT_CAP,BUFFER_CEILING:BUFFER_CEILING,TAIL_KEEP:TAIL_KEEP};
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * shell.js — a persistent shell session for the `exec` tool, ported from
10
+ * the upstream engine reference (client half of the same design).
11
+ *
12
+ * The desktop `exec` tool used to spawn ONE process per call: `cd /foo` in
13
+ * one turn had no effect on the next call, so a model that wanted to work
14
+ * inside a subdirectory had to prefix every single command with `cd X &&`.
15
+ * This keeps ONE long-lived shell per chat turn — a probed POSIX sh/bash on
16
+ * macOS/Linux, PowerShell on Windows (no bash there by default) — feeding it
17
+ * commands over stdin and framing each command's output with a per-session
18
+ * random sentinel printed alongside the exit code. On POSIX, stderr is merged
19
+ * into stdout (`exec 2>&1`) so ordering is preserved; PowerShell's stderr pipe
20
+ * is merged the same way by listening on both streams.
21
+ *
22
+ * Phase 30.3 — the shell is PROBED, never assumed. Until this step the session
23
+ * spawned `process.env.SHELL || '/bin/bash'` and then fed it brace groups, `exec
24
+ * 2>&1` and `$?` — all POSIX-only. Windows was handled; a POSIX host whose
25
+ * `$SHELL` is fish, csh or nushell was not, and those three reject that syntax
26
+ * outright (a brace group to fish is not a syntax error you can ignore: it
27
+ * silently runs the wrong thing and eats the sentinel, hanging the session to
28
+ * its timeout). So `resolveSessionShell()` below only ever returns a shell it
29
+ * has actually EXECUTED once with a POSIX-only probe script, and the dialect the
30
+ * script builder uses follows the verified dialect — `this.shell.kind` — rather
31
+ * than the OS. A `$SHELL` naming a known-non-POSIX shell (fish/csh/tcsh/nu/
32
+ * xonsh) is never adopted and never probed; it is named in the evidence trail
33
+ * and in the caveat, and if no sh/bash can be verified at all the session
34
+ * REFUSES with a message naming it, instead of quietly feeding it POSIX syntax.
35
+ *
36
+ * Self-contained (node:child_process + node:crypto + the shared
37
+ * client/platform.js) and never throws: run() always resolves
38
+ * { content, isError }. If the session can't start or dies, run() falls back to
39
+ * a one-shot spawn so `exec` keeps working.
40
+ */
41
+
42
+ const { spawn, spawnSync } = require('node:child_process');
43
+ const crypto = require('node:crypto');
44
+
45
+ // The second gate (see lib/local/integrity.js). Asked here because THIS module
46
+ // is where a command actually reaches the operating system — a file that can
47
+ // spawn must not run in a build whose own bytes have been rewritten, and it
48
+ // must ask for itself rather than trust that main.js asked. Deleting the call
49
+ // in main.js then still leaves this one behind, and this file is covered by
50
+ // the digest, so silencing it here is itself a change to the digest.
51
+ const integrity = require('./integrity.js');
52
+
53
+ // The ONE platform module (client/platform.js, Phase 30.1) — resolved the same
54
+ // two ways this repo resolves every shared module (see tools.js/engine.js):
55
+ // repo-relative in a checkout and in the CLI's mirrored vendor tree, then the
56
+ // staged app-dir copy a packaged desktop build carries. Executable lookup goes
57
+ // through it (`resolveExecutable`) rather than through a path literal, so the
58
+ // Windows half of that search is exercised by tests on this Linux host.
59
+ let platform;
60
+ try {
61
+ platform = require('../../../client/platform.js');
62
+ } catch (err) {
63
+ try {
64
+ platform = require('../../vendor/platform.js');
65
+ } catch {
66
+ throw new Error(
67
+ `shell.js: cannot load the shared platform module (client/platform.js, ` +
68
+ `or its staged copy): ${err && err.message ? err.message : err}`
69
+ );
70
+ }
71
+ }
72
+
73
+ const IS_WIN32 = platform.IS_WIN32;
74
+ const OUTPUT_CAP = 30_000;
75
+ const MAX_TIMEOUT = 600_000;
76
+ const DEFAULT_TIMEOUT = 120_000;
77
+
78
+ // ---------------------------------------------------------------------------
79
+ // Dialect resolution (Phase 30.3)
80
+ // ---------------------------------------------------------------------------
81
+
82
+ /**
83
+ * The shells whose `-c` we are allowed to treat as POSIX sh. Anything else —
84
+ * fish, csh/tcsh, nushell, xonsh, elvish, pwsh — is a different LANGUAGE, not a
85
+ * differently-named sh: it is never spawned for a session and never handed the
86
+ * brace-group framing below.
87
+ */
88
+ const POSIX_SHELL_NAMES = ['bash', 'sh', 'dash', 'ksh', 'zsh'];
89
+
90
+ /** Substitute candidates, in order, when `$SHELL` is unusable. */
91
+ const POSIX_FALLBACK_NAMES = ['bash', 'sh'];
92
+
93
+ /**
94
+ * The probe script: builtins only (no PATH, no filesystem, no output), and
95
+ * POSIX-only syntax — fish, csh and nu all reject this construct, so a clean
96
+ * exit 0 is evidence that `-c` really runs POSIX sh here, rather than evidence
97
+ * that a binary with the right name exists. Same probe the engine's Phase 21b
98
+ * resolution uses.
99
+ */
100
+ const POSIX_PROBE = 'if [ 1 -eq 1 ]; then exit 0; fi';
101
+ const SHELL_PROBE_TIMEOUT = 4000;
102
+
103
+ /** Last path segment of a shell reference, minus a `.exe`, lower-cased. */
104
+ function shellName(cmd) {
105
+ return String(cmd || '')
106
+ .trim()
107
+ .split(/[\\/]/)
108
+ .pop()
109
+ .toLowerCase()
110
+ .replace(/\.exe$/, '');
111
+ }
112
+
113
+ /** True for the shells whose `-c` may be treated as POSIX sh. */
114
+ function isPosixShellName(cmd) {
115
+ return POSIX_SHELL_NAMES.includes(shellName(cmd));
116
+ }
117
+
118
+ /** The real probe: spawn `cmd -c <POSIX_PROBE>`, true only on a clean exit 0. */
119
+ function probePosixShell(cmd, { env, timeout = SHELL_PROBE_TIMEOUT } = {}) {
120
+ try {
121
+ const res = spawnSync(cmd, ['-c', POSIX_PROBE], {
122
+ env,
123
+ encoding: 'utf8',
124
+ timeout,
125
+ windowsHide: true,
126
+ stdio: 'ignore',
127
+ });
128
+ return !res.error && res.status === 0;
129
+ } catch {
130
+ return false;
131
+ }
132
+ }
133
+
134
+ /** Normalize the injected seams, defaulting each to the real thing. */
135
+ function shellSeams(options) {
136
+ const o = options && typeof options === 'object' ? options : {};
137
+ return {
138
+ platform: typeof o.platform === 'string' && o.platform ? o.platform : process.platform,
139
+ env: o.env && typeof o.env === 'object' ? o.env : process.env,
140
+ exists: typeof o.exists === 'function' ? o.exists : undefined,
141
+ probe: typeof o.probe === 'function' ? o.probe : undefined,
142
+ injected: typeof o.probe === 'function' || typeof o.exists === 'function',
143
+ };
144
+ }
145
+
146
+ /**
147
+ * Try one candidate. Returns a verified spec or null, recording why in `tried`
148
+ * and every shell it actually executed in `executed`.
149
+ *
150
+ * The name gate comes FIRST and applies to every candidate, including `$SHELL`:
151
+ * fish is refused on its name, before a probe could ever adopt it, so there is
152
+ * no ordering in which a fish gets spawned and then handed POSIX syntax.
153
+ */
154
+ function considerPosixCandidate(o, candidate, tried, executed) {
155
+ const raw = String(candidate.cmd || '').trim();
156
+ if (!raw) {
157
+ tried.push({ candidate: candidate.source || '(unset)', ok: false, reason: 'unset' });
158
+ return null;
159
+ }
160
+ if (!isPosixShellName(raw)) {
161
+ tried.push({
162
+ candidate: raw,
163
+ ok: false,
164
+ reason:
165
+ `${candidate.source || 'candidate'} is not a POSIX shell — ${shellName(raw) || raw} is a ` +
166
+ 'different language (fish/csh/nu), so it was never executed and never sent POSIX syntax',
167
+ });
168
+ return null;
169
+ }
170
+ const resolved = platform.resolveExecutable(raw, {
171
+ platform: o.platform,
172
+ env: o.env,
173
+ exists: o.exists,
174
+ });
175
+ if (!resolved) {
176
+ tried.push({
177
+ candidate: raw,
178
+ ok: false,
179
+ reason: /[\\/]/.test(raw) ? 'not present' : 'not found on PATH',
180
+ });
181
+ return null;
182
+ }
183
+ const ok = o.probe
184
+ ? Boolean(o.probe(resolved, ['-c', POSIX_PROBE]))
185
+ : probePosixShell(resolved, { env: o.env });
186
+ executed.push(resolved);
187
+ if (!ok) {
188
+ tried.push({
189
+ candidate: resolved,
190
+ ok: false,
191
+ reason: `failed the POSIX probe (\`-c\` with \`${POSIX_PROBE}\` did not exit 0) — refused`,
192
+ });
193
+ return null;
194
+ }
195
+ tried.push({
196
+ candidate: resolved,
197
+ ok: true,
198
+ reason: 'verified: one `-c` POSIX script exited 0',
199
+ });
200
+ return { ok: true, cmd: resolved, arg: '-c', kind: 'posix-sh', source: candidate.source, verified: true };
201
+ }
202
+
203
+ /**
204
+ * Resolve the session shell on a POSIX host, with the evidence for the answer.
205
+ *
206
+ * Returns { ok, cmd, arg, kind, source, verified, unsupported, caveat, error,
207
+ * tried[] }:
208
+ *
209
+ * - `$SHELL` wins when it NAMES a POSIX shell and passes the probe;
210
+ * - a `$SHELL` naming fish/csh/nu/xonsh (or anything else non-POSIX, including
211
+ * garbage) is refused by name, recorded in `tried`, and named in `caveat`
212
+ * when a substitute is found and in `error` when none can be;
213
+ * - when `$SHELL` is unusable the POSIX dialect runs through an explicit
214
+ * `bash`/`sh` found on PATH — resolved by client/platform.js, not by a path
215
+ * literal — and only after that substitute passed the probe itself;
216
+ * - `ok:false` means NO shell was verified: the caller must report `error`
217
+ * (which names the unsupported `$SHELL`) instead of spawning anything.
218
+ */
219
+ function resolvePosixSessionShell(o) {
220
+ const tried = [];
221
+ const executed = [];
222
+ const envShell = String((o.env && o.env.SHELL) || '').trim();
223
+ const candidates = [];
224
+
225
+ if (!envShell) {
226
+ tried.push({ candidate: '$SHELL', ok: false, reason: '$SHELL is unset' });
227
+ } else {
228
+ candidates.push({ cmd: envShell, source: '$SHELL' });
229
+ }
230
+ for (const name of POSIX_FALLBACK_NAMES) {
231
+ candidates.push({ cmd: name, source: `PATH:${name}` });
232
+ }
233
+
234
+ let hit = null;
235
+ for (const candidate of candidates) {
236
+ hit = considerPosixCandidate(o, candidate, tried, executed);
237
+ if (hit) break;
238
+ }
239
+
240
+ const unsupported = envShell && !isPosixShellName(envShell) ? envShell : null;
241
+ if (hit) {
242
+ return {
243
+ ...hit,
244
+ unsupported,
245
+ caveat: unsupported
246
+ ? `$SHELL is ${unsupported}, which is not a POSIX shell — the session runs the POSIX ` +
247
+ `dialect through ${hit.cmd} instead, and ${unsupported} is never sent brace groups, ` +
248
+ '`exec 2>&1` or `$?`'
249
+ : null,
250
+ error: null,
251
+ executed,
252
+ tried,
253
+ };
254
+ }
255
+
256
+ const error = unsupported
257
+ ? `exec: refusing to run — $SHELL is "${unsupported}", which is not a POSIX shell ` +
258
+ '(fish/csh/nushell are a different language), and no sh/bash could be verified on PATH ' +
259
+ 'to run the POSIX dialect instead. Set SHELL to bash or sh, or put one on PATH.'
260
+ : `exec: no POSIX shell available — $SHELL is ${envShell ? `"${envShell}"` : 'unset'} and no ` +
261
+ 'sh/bash passed the POSIX probe; set SHELL to bash or sh, or put one on PATH.';
262
+ return {
263
+ ok: false,
264
+ cmd: null,
265
+ arg: null,
266
+ kind: null,
267
+ source: 'refused',
268
+ verified: false,
269
+ unsupported,
270
+ caveat: null,
271
+ error,
272
+ executed,
273
+ tried,
274
+ };
275
+ }
276
+
277
+ // Verified verdicts are cached per (platform, $SHELL, PATH) so the probe runs
278
+ // once per process — but never when a seam was injected: a test double must not
279
+ // be able to poison the real verdicts.
280
+ const SHELL_CACHE = new Map();
281
+
282
+ /**
283
+ * Which shell runs the session here, and the evidence for that answer.
284
+ *
285
+ * Windows keeps PowerShell (there is no bash there by default), exactly as
286
+ * before; everywhere else the answer comes from resolvePosixSessionShell above
287
+ * and is only ever a shell that passed the POSIX probe. `options` is the same
288
+ * injected seam the shared platform module takes —
289
+ * `{ platform, env, exists, probe }` — so every branch is exercised on this
290
+ * Linux host (test/shell-dialect.test.mjs) rather than on a runner this project
291
+ * does not have.
292
+ */
293
+ function resolveSessionShell(options = {}) {
294
+ const o = shellSeams(options);
295
+ if (o.platform === 'win32') {
296
+ const cmdSpec = platform.shellSpec({ platform: 'win32', env: o.env });
297
+ const powershell =
298
+ platform.resolveExecutable('powershell', { platform: 'win32', env: o.env, exists: o.exists }) ||
299
+ 'powershell.exe';
300
+ // ONE-SHOT NOW SPEAKS THE SESSION'S DIALECT TOO (2026-02-14 report, item 1).
301
+ //
302
+ // This used to be `oneShot: cmdSpec` — PowerShell for the session, cmd.exe
303
+ // for every one-shot — and that mismatch is what made `exec` silently wrong
304
+ // mid-turn. When the live session died (sentinel timeout, killed child, a
305
+ // rejected stdin write) the degrade paths below run one-shot, so from that
306
+ // moment on every remaining command in the turn was parsed by cmd.exe while
307
+ // the model kept emitting PowerShell quoting. cmd.exe answers
308
+ // `'"Write-Output \"' is not recognized as an internal or external command`
309
+ // — localized, so on sv-SE it reads `Felaktig syntax för filnamn, katalognamn
310
+ // eller volymetikett`, which looks like a filesystem fault and not a shell
311
+ // change — and nothing in the tool result said the shell had switched.
312
+ //
313
+ // `-Command` accepts exactly the quoting the session accepts, so a
314
+ // degradation is now a transport change and not a language change. cmd.exe
315
+ // is no longer reachable from this path at all: if PowerShell cannot be
316
+ // resolved the spawn fails loudly (oneShotShell reports `error: …`) instead
317
+ // of quietly running the command in a shell that cannot read it.
318
+ const oneShot = {
319
+ cmd: powershell,
320
+ arg: '-Command',
321
+ kind: 'powershell',
322
+ source: 'powershell.exe',
323
+ };
324
+ return {
325
+ ok: true,
326
+ cmd: powershell,
327
+ arg: '-',
328
+ kind: 'powershell',
329
+ source: 'powershell.exe',
330
+ verified: true,
331
+ unsupported: null,
332
+ caveat: null,
333
+ error: null,
334
+ oneShot,
335
+ executed: [],
336
+ tried: [
337
+ { candidate: powershell, ok: true, reason: 'the Windows default (PowerShell session AND one-shot)' },
338
+ {
339
+ candidate: cmdSpec.cmd,
340
+ ok: false,
341
+ reason: 'cmd.exe is never used for one-shot: it cannot parse the PowerShell quoting the session teaches',
342
+ },
343
+ ],
344
+ };
345
+ }
346
+
347
+ const key = [o.platform, o.env && o.env.SHELL, o.env && o.env.PATH].join('\u0000');
348
+ if (!o.injected && SHELL_CACHE.has(key)) return SHELL_CACHE.get(key);
349
+ const spec = resolvePosixSessionShell(o);
350
+ if (!o.injected) SHELL_CACHE.set(key, spec);
351
+ return spec;
352
+ }
353
+
354
+ // The reported text spills instead of being destroyed — same helper as
355
+ // tools.js, for the same reason (the answer to a wide grep is usually past the
356
+ // cap, and re-running a narrower command costs a whole round). What gets spilled
357
+ // here is the BUFFER's text, which appendBounded has already bounded to
358
+ // OUTPUT_CAP + TAIL_KEEP — so for a genuine flood the file holds the head and
359
+ // the tail with an elision marker between them, not a command's whole output.
360
+ // That is deliberate: the buffer bound exists so a tool call cannot OOM the app,
361
+ // and it is not lifted just to make the spill complete.
362
+ const { cap: spillCap } = require('./spill.js');
363
+
364
+ function cap(s) {
365
+ return spillCap(s, OUTPUT_CAP);
366
+ }
367
+
368
+ // The buffer is BOUNDED WHILE IT FILLS, not just when it is reported.
369
+ //
370
+ // `cap()` above runs on close, which is fine for the text the user sees but
371
+ // useless as a memory bound: between the spawn and the exit the raw stream is
372
+ // accumulated in this process with no ceiling at all, so a command that never
373
+ // stops printing (`yes`, `cat /dev/zero`, a runaway build log) grows the MAIN
374
+ // process's heap for as long as the timeout allows — up to 10 minutes — before
375
+ // the truncation it was always going to get. A tool call must not be able to
376
+ // OOM the app it runs in.
377
+ //
378
+ // The window kept is head + tail, because neither end may be dropped:
379
+ // - the HEAD is what the user and the model are shown (OUTPUT_CAP already
380
+ // says only that much is reported);
381
+ // - the TAIL is where the exit sentinel lives for a session (`printf
382
+ // '__AEGIS_SH_…EXIT:%d'`) — dropping it would not merely lose output, it
383
+ // would hang the session until the timeout, because the resolver scans the
384
+ // buffer for a marker that can never arrive.
385
+ // 64 KiB of tail is ~1500× the sentinel line, and surviving a chunk boundary
386
+ // needs only the sentinel's own length.
387
+ const TAIL_KEEP = 64 * 1024;
388
+ const BUFFER_CEILING = OUTPUT_CAP + TAIL_KEEP;
389
+ const ELISION = '\n… (earlier output elided — command produced more than the buffer ceiling)\n';
390
+
391
+ /** Append one stream chunk to `prev`, keeping the bounded head+tail window.
392
+ * Pure, so the streaming paths and their tests agree on the policy. */
393
+ function appendBounded(prev, chunk) {
394
+ const next = prev + chunk;
395
+ if (next.length <= BUFFER_CEILING) return next;
396
+ // Elide the MIDDLE: head stays visible, tail keeps the sentinel reachable.
397
+ // The marker makes the missing bytes explicit rather than letting the two
398
+ // halves read as contiguous output.
399
+ return next.slice(0, OUTPUT_CAP) + ELISION + next.slice(-TAIL_KEEP);
400
+ }
401
+
402
+ /**
403
+ * The spec for a ONE-SHOT command (no live session) — the same resolution, so
404
+ * the `exec` tool's no-session path and this module's fallback cannot disagree
405
+ * about which shell speaks the dialect the command was written in.
406
+ *
407
+ * Windows keeps cmd.exe (`/d /s /c`), exactly what it used before; everywhere
408
+ * else the answer is a PROBED POSIX sh/bash, and `{ ok:false, error }` when
409
+ * nothing could be verified — the caller reports `error` (which names the
410
+ * unsupported `$SHELL`) instead of shelling out in a language it does not speak.
411
+ */
412
+ function oneShotShellSpec(options = {}) {
413
+ const spec = resolveSessionShell(options);
414
+ if (!spec.ok) {
415
+ return { ok: false, cmd: null, arg: null, kind: null, error: spec.error, spec };
416
+ }
417
+ if (spec.kind === 'powershell') {
418
+ // The session's own one-shot spec (PowerShell `-Command`), so the `exec`
419
+ // tool's no-session path and this module's fallback cannot disagree about
420
+ // the dialect — which is exactly how cmd.exe used to sneak back in.
421
+ const shot = spec.oneShot || platform.shellSpec({ platform: 'win32', env: shellSeams(options).env });
422
+ return { ok: true, cmd: shot.cmd, arg: shot.arg, kind: shot.kind || 'powershell', error: null, spec };
423
+ }
424
+ return { ok: true, cmd: spec.cmd, arg: spec.arg, kind: 'posix-sh', error: null, spec };
425
+ }
426
+
427
+ /**
428
+ * One-shot fallback — the pre-session behavior, used when no live session.
429
+ *
430
+ * The dialect is resolved the same way the session's is: a POSIX `-c` runs in a
431
+ * verified sh/bash (never in an unprobed `$SHELL`), and when nothing can be
432
+ * verified the refusal names the shell that was refused rather than shelling out
433
+ * to it in a language it does not speak.
434
+ */
435
+ function oneShotShell({ command, timeout = DEFAULT_TIMEOUT, working_directory, shellOptions } = {}) {
436
+ return new Promise((resolve) => {
437
+ // Refuse to spawn at all in a build that failed the second gate. Resolved
438
+ // as an isError result rather than a throw: run() always resolves, and a
439
+ // gate that turns a tool call into an exception is a gate an attacker
440
+ // would rather have present.
441
+ if (integrity.armed()) {
442
+ resolve({ content: 'exec: unavailable in this build', isError: true });
443
+ return;
444
+ }
445
+ const o = shellSeams(shellOptions);
446
+ const spec = resolveSessionShell(shellOptions);
447
+ if (!spec || !spec.ok) {
448
+ resolve({ content: (spec && spec.error) || 'exec: no usable shell', isError: true });
449
+ return;
450
+ }
451
+ const call = spec.kind === 'powershell' ? spec.oneShot : spec;
452
+ const child = spawn(call.cmd, [call.arg, String(command || '')], {
453
+ cwd: working_directory || process.cwd(),
454
+ timeout: Math.min(Number(timeout) || DEFAULT_TIMEOUT, MAX_TIMEOUT),
455
+ env: o.env,
456
+ });
457
+ let out = '';
458
+ let err = '';
459
+ // Bounded both ways: a one-shot command with no live session is just as
460
+ // capable of printing forever as a session command (appendBounded's header).
461
+ child.stdout.on('data', (d) => { out = appendBounded(out, d.toString()); });
462
+ child.stderr.on('data', (d) => { err = appendBounded(err, d.toString()); });
463
+ child.on('error', (e) => resolve({ content: `error: ${e.message}`, isError: true }));
464
+ child.on('close', (code) => {
465
+ const body = `${out}${err ? `\n${err}` : ''}`.trim() || `(exit ${code})`;
466
+ resolve({ content: cap(body), isError: code !== 0 });
467
+ });
468
+ });
469
+ }
470
+
471
+ class ShellSession {
472
+ constructor({ cwd, shellOptions } = {}) {
473
+ this.sentinel = `__AEGIS_SH_${crypto.randomBytes(8).toString('hex')}__`;
474
+ this.marker = `${this.sentinel}EXIT:`;
475
+ this.buf = '';
476
+ this.alive = false;
477
+ this._pending = null; // resolver-scan for the in-flight command
478
+ this.cwd = cwd || process.cwd();
479
+ this.disposed = false; // an explicit dispose() must NOT be self-healed
480
+ this._respawns = 0; // one self-heal attempt per session, never a loop
481
+ this._degradedNoted = false; // the degrade marker is emitted once per session
482
+ this.shellOptions = shellOptions || {};
483
+ // Resolved BEFORE anything is spawned or written: `shell.kind` is what the
484
+ // command framing below branches on, so an unverified `$SHELL` can never
485
+ // receive POSIX syntax — it is never spawned at all.
486
+ this.shell = resolveSessionShell(this.shellOptions);
487
+ this.shellError = this.shell.ok ? null : this.shell.error;
488
+ this._start(cwd);
489
+ }
490
+
491
+ _start(cwd) {
492
+ if (!this.shell || !this.shell.ok) {
493
+ // Refused: no shell was verified, so nothing is spawned. run() reports
494
+ // this.shellError (which names the unsupported $SHELL).
495
+ this.alive = false;
496
+ return;
497
+ }
498
+ const env = shellSeams(this.shellOptions).env;
499
+ try {
500
+ this.child = this.shell.kind === 'powershell'
501
+ // -Command - reads the script from stdin as a non-interactive session,
502
+ // so there are no prompts to pollute output, but state still persists.
503
+ ? spawn(this.shell.cmd, ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '-'], {
504
+ cwd: cwd || process.cwd(),
505
+ env,
506
+ stdio: ['pipe', 'pipe', 'pipe'],
507
+ })
508
+ // No args → the shell reads commands from stdin as a non-interactive
509
+ // script, so there are no prompts to pollute output, but state persists.
510
+ // This is a shell that PASSED the POSIX probe (see resolveSessionShell).
511
+ : spawn(this.shell.cmd, [], {
512
+ cwd: cwd || process.cwd(),
513
+ env,
514
+ stdio: ['pipe', 'pipe', 'pipe'],
515
+ });
516
+ } catch {
517
+ this.alive = false;
518
+ return;
519
+ }
520
+ this.alive = true;
521
+ const onData = (d) => {
522
+ // Bounded — see appendBounded. The tail is kept precisely so the sentinel
523
+ // this session's resolver scans for survives a command that floods stdout.
524
+ this.buf = appendBounded(this.buf, d.toString());
525
+ if (this._pending) this._pending();
526
+ };
527
+ this.child.stdout.on('data', onData);
528
+ this.child.stderr.on('data', onData);
529
+ this.child.on('exit', () => { this.alive = false; if (this._pending) this._pending(true); });
530
+ this.child.on('error', () => { this.alive = false; if (this._pending) this._pending(true); });
531
+ // Merge stderr into stdout for the whole session so output ordering is
532
+ // faithful and the sentinel (printed to fd1) always lands after it.
533
+ // PowerShell errors already arrive on the stderr pipe onData folds in
534
+ // above, so only a POSIX session needs the explicit redirect — and `exec`
535
+ // redirection is POSIX, which is why this is gated on the VERIFIED dialect
536
+ // rather than on `!IS_WIN32`.
537
+ if (this.shell.kind === 'posix-sh') {
538
+ try { this.child.stdin.write('exec 2>&1\n'); } catch { this.alive = false; }
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Run one command in the session. Resolves { content, isError }. A dead or
544
+ * unstartable session (or a working_directory that must not persist)
545
+ * degrades gracefully. `working_directory` is scoped to this one command (a
546
+ * subshell on POSIX, Push-Location/Pop-Location on PowerShell) so it doesn't
547
+ * move the session's cwd.
548
+ */
549
+ run(command, { timeout = DEFAULT_TIMEOUT, working_directory } = {}) {
550
+ // The second gate, on the live-session path (see oneShotShell above and
551
+ // lib/local/integrity.js). Both paths ask: a refused build must not reach
552
+ // the OS through either one.
553
+ if (integrity.armed()) {
554
+ return Promise.resolve({ content: 'exec: unavailable in this build', isError: true });
555
+ }
556
+ const posixSession = this.shell && this.shell.kind === 'posix-sh' && this.shell.verified;
557
+ if (!this.alive || !this.child || ((this.shell && this.shell.kind === 'posix-sh') && !posixSession)) {
558
+ if (!this.alive && this.shellError) {
559
+ return Promise.resolve({ content: this.shellError, isError: true });
560
+ }
561
+ // SELF-HEAL BEFORE DEGRADING. The old path latched: once the live session
562
+ // died (a timeout kill, a child exit, a spawn error) every remaining
563
+ // command in the turn ran one-shot, and on Windows that one-shot used to
564
+ // be cmd.exe — so the agent stayed silently wrong for the rest of the
565
+ // turn. Re-probe and re-spawn ONCE instead, and only then fall through.
566
+ if (!this.alive && !this.disposed && this._respawns < 1) {
567
+ this._respawns += 1;
568
+ this.buf = '';
569
+ this.shell = resolveSessionShell(this.shellOptions);
570
+ this.shellError = this.shell.ok ? null : this.shell.error;
571
+ this._start(this.cwd);
572
+ if (this.alive) return this.run(command, { timeout, working_directory });
573
+ }
574
+ return oneShotShell({ command, timeout, working_directory, shellOptions: this.shellOptions })
575
+ .then((result) => this._noteDegraded(result, !this.alive ? 'the persistent session is not running' : 'no usable session dialect'));
576
+ }
577
+ let cmd = String(command || '');
578
+
579
+ return new Promise((resolve) => {
580
+ let settled = false;
581
+ const finish = (result) => {
582
+ if (settled) return;
583
+ settled = true;
584
+ clearTimeout(timer);
585
+ this._pending = null;
586
+ resolve(result);
587
+ };
588
+
589
+ const timer = setTimeout(() => {
590
+ // A hung command (e.g. one that reads stdin) can never reach the
591
+ // sentinel — kill the poisoned session and report what we have.
592
+ const partial = cap(this.buf.trim());
593
+ this.dispose();
594
+ finish({ content: `${partial}${partial ? '\n' : ''}(timed out after ${timeout}ms)`, isError: true });
595
+ }, Math.min(Number(timeout) || DEFAULT_TIMEOUT, MAX_TIMEOUT));
596
+
597
+ this._pending = (died) => {
598
+ if (died && !this.buf.includes(this.marker)) {
599
+ finish({ content: cap(this.buf.trim()) || '(shell session ended)', isError: true });
600
+ return;
601
+ }
602
+ const idx = this.buf.indexOf(this.marker);
603
+ if (idx === -1) return; // sentinel not here yet — wait for more data
604
+ const after = this.buf.slice(idx + this.marker.length);
605
+ const nl = after.indexOf('\n');
606
+ if (nl === -1) return; // exit-code line still arriving
607
+ const code = parseInt(after.slice(0, nl), 10);
608
+ const output = this.buf.slice(0, idx).replace(/\n+$/, '');
609
+ this.buf = after.slice(nl + 1); // leftover for the next command (usually '')
610
+ finish({ content: cap(output || `(exit ${code})`), isError: code !== 0 });
611
+ };
612
+
613
+ // Send the command, then print the sentinel + exit code on its own line.
614
+ let script;
615
+ if (!posixSession) {
616
+ // Push-Location/Pop-Location scope working_directory to this one
617
+ // command without moving the session's persistent cwd. $__c captures
618
+ // the real exit status before Pop-Location's own success would
619
+ // otherwise overwrite $?/$LASTEXITCODE.
620
+ const body = cmd.trim() ? cmd : 'Write-Output $null';
621
+ const exitCapture =
622
+ '$__c = if ($LASTEXITCODE -ne $null) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }';
623
+ script = working_directory
624
+ ? `Push-Location -LiteralPath ${pshq(working_directory)}\ntry {\n${body}\n${exitCapture}\n} finally {\nPop-Location\n}\n`
625
+ : `${body}\n${exitCapture}\n`;
626
+ script += `Write-Output ("${this.marker}" + $__c)\n`;
627
+ } else {
628
+ // POSIX dialect, sent ONLY to a shell that passed the POSIX probe
629
+ // (posixSession above) — never to fish/csh/nu. The command runs in a
630
+ // brace group with its stdin redirected from /dev/null: a group (not a
631
+ // subshell) keeps cd/export state persisting, and `</dev/null` stops the
632
+ // command from consuming the control channel. Without this, any
633
+ // stdin-reading command (cat, read, a REPL, ssh, a y/n prompt) swallows
634
+ // the sentinel line that follows it — hanging the whole session until
635
+ // the timeout, and echoing commands (cat) even splice the sentinel into
636
+ // their output and mis-resolve with garbage. working_directory runs in a
637
+ // subshell (parens, not the brace group) so it doesn't move the
638
+ // session's cwd.
639
+ if (working_directory) cmd = `( cd ${shq(working_directory)} && ${cmd} )`;
640
+ const body = cmd.trim() ? cmd : ':';
641
+ script = `{ ${body}\n} </dev/null\nprintf '\\n%s%d\\n' '${this.sentinel}EXIT:' "$?"\n`;
642
+ }
643
+ try {
644
+ this.child.stdin.write(script);
645
+ } catch {
646
+ this.alive = false;
647
+ oneShotShell({ command, timeout, working_directory, shellOptions: this.shellOptions })
648
+ .then((r) => finish(this._noteDegraded(r, 'the session stdin rejected the command')));
649
+ return;
650
+ }
651
+ // Data may already be buffered (fast commands) — scan once now.
652
+ if (this._pending) this._pending();
653
+ });
654
+ }
655
+
656
+ /**
657
+ * Mark a result that came from the one-shot fallback rather than the live
658
+ * session, so the model is TOLD the shell changed and can stop trusting its
659
+ * quoting contract.
660
+ *
661
+ * The 2026-02-14 report's worst finding was precisely that this happened
662
+ * silently: "nothing in the result tells the agent the shell changed" while
663
+ * the agent "degrades to a one-shot cmd.exe — and stays there for the
664
+ * remainder of the turn", so it kept emitting PowerShell quoting, got
665
+ * localized cmd.exe syntax errors, and finally blamed the user's machine.
666
+ * Emitted ONCE per session so a degraded turn stays readable.
667
+ */
668
+ _noteDegraded(result, reason) {
669
+ const r = result && typeof result === 'object' ? result : { content: String(result == null ? '' : result), isError: true };
670
+ if (this._degradedNoted) return r;
671
+ this._degradedNoted = true;
672
+ const via = this.shell && this.shell.cmd ? this.shell.cmd : 'unknown shell';
673
+ const was = this.shell && this.shell.kind ? this.shell.kind : 'none';
674
+ const marker = `[shell_degraded] ran one-shot via ${via} (${reason}); session dialect was ${was} — quoting contracts may differ`;
675
+ return { ...r, content: `${marker}\n${r.content || ''}` };
676
+ }
677
+
678
+ dispose() {
679
+ this.disposed = true;
680
+ this.alive = false;
681
+ if (this.child) {
682
+ try { this.child.stdin.end(); } catch { /* already gone */ }
683
+ try { this.child.kill('SIGKILL'); } catch { /* already gone */ }
684
+ this.child = null;
685
+ }
686
+ }
687
+ }
688
+
689
+ // Minimal single-quote shell-escape for a path.
690
+ function shq(s) {
691
+ return `'${String(s).replace(/'/g, `'\\''`)}'`;
692
+ }
693
+
694
+ // Minimal single-quote escape for a PowerShell -LiteralPath (double up ').
695
+ function pshq(s) {
696
+ return `'${String(s).replace(/'/g, "''")}'`;
697
+ }
698
+
699
+ module.exports = {
700
+ ShellSession,
701
+ oneShotShell,
702
+ IS_WIN32,
703
+ // Phase 30.3: the dialect probe and its verdict, exported so a test can
704
+ // assert on the resolution without spawning a session.
705
+ resolveSessionShell,
706
+ oneShotShellSpec,
707
+ isPosixShellName,
708
+ POSIX_SHELL_NAMES,
709
+ POSIX_PROBE,
710
+ appendBounded,
711
+ OUTPUT_CAP,
712
+ BUFFER_CEILING,
713
+ TAIL_KEEP,
714
+ };