@kenkaiiii/ggcoder 5.101.0 → 5.103.0

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.
Files changed (39) hide show
  1. package/assets/skills/gg-guide/references/code-mode.md +11 -0
  2. package/dist/app-sidecar/live-preview/dev-url.d.ts +32 -0
  3. package/dist/app-sidecar/live-preview/dev-url.js +97 -0
  4. package/dist/app-sidecar/live-preview/dev-url.js.map +1 -0
  5. package/dist/app-sidecar/live-preview/frame-server.d.ts +31 -0
  6. package/dist/app-sidecar/live-preview/frame-server.js +193 -0
  7. package/dist/app-sidecar/live-preview/frame-server.js.map +1 -0
  8. package/dist/app-sidecar/live-preview/manager.d.ts +44 -0
  9. package/dist/app-sidecar/live-preview/manager.js +215 -0
  10. package/dist/app-sidecar/live-preview/manager.js.map +1 -0
  11. package/dist/app-sidecar/live-preview/proxy.d.ts +30 -0
  12. package/dist/app-sidecar/live-preview/proxy.js +235 -0
  13. package/dist/app-sidecar/live-preview/proxy.js.map +1 -0
  14. package/dist/app-sidecar/live-preview/routes.d.ts +4 -0
  15. package/dist/app-sidecar/live-preview/routes.js +52 -0
  16. package/dist/app-sidecar/live-preview/routes.js.map +1 -0
  17. package/dist/app-sidecar/live-preview/servers.d.ts +36 -0
  18. package/dist/app-sidecar/live-preview/servers.js +228 -0
  19. package/dist/app-sidecar/live-preview/servers.js.map +1 -0
  20. package/dist/app-sidecar/prompt-routes.js +21 -3
  21. package/dist/app-sidecar/prompt-routes.js.map +1 -1
  22. package/dist/app-sidecar.js +73 -30
  23. package/dist/app-sidecar.js.map +1 -1
  24. package/dist/core/agent-session/verification-tracker.js +2 -10
  25. package/dist/core/agent-session/verification-tracker.js.map +1 -1
  26. package/dist/core/live-preview.d.ts +24 -0
  27. package/dist/core/live-preview.js +76 -0
  28. package/dist/core/live-preview.js.map +1 -0
  29. package/dist/core/prompt-commands.js +14 -5
  30. package/dist/core/prompt-commands.js.map +1 -1
  31. package/dist/core/session-history.js +15 -3
  32. package/dist/core/session-history.js.map +1 -1
  33. package/dist/tools/bash.d.ts +2 -2
  34. package/dist/tools/bash.js +359 -354
  35. package/dist/tools/bash.js.map +1 -1
  36. package/dist/tools/live-preview.d.ts +21 -0
  37. package/dist/tools/live-preview.js +37 -0
  38. package/dist/tools/live-preview.js.map +1 -0
  39. package/package.json +4 -4
@@ -27,8 +27,8 @@ function sandboxAwareEnv(sandboxed, cooldown = {}) {
27
27
  return sandboxed ? { ...env, ...SANDBOX_ENV_PATCH } : env;
28
28
  }
29
29
  const DEFAULT_TIMEOUT = 120_000; // 120 seconds
30
- /** Host-authored rejection: no process started, so this is not a failed check. */
31
- export const REVIEW_REJECTED_BEFORE_START = "Error: review requires a local, non-persistent foreground verification check. Pass only the check in command; do not combine it with edits or diff inspection. Nothing was run.";
30
+ /** Appended when `review` was set on a command that cannot carry one; the command itself still ran. */
31
+ export const REVIEW_SKIPPED_NOTE = "Review skipped: it runs only after a command that is just the final check, in the foreground. The command above ran normally.";
32
32
  const AUTO_BACKGROUND_RE = /^Still running after \d+(?:\.\d+)?s, so it was moved to the background\b/;
33
33
  /**
34
34
  * Background process id when a bash result reports that a foreground command
@@ -159,376 +159,381 @@ getPackageCooldownDays = () => 2) {
159
159
  ? "Run a Windows cmd.exe command (no bash on this system) in the project root. Use cmd " +
160
160
  "syntax (dir, findstr, type); POSIX commands and $(...) fail. Output tail is kept."
161
161
  : "Run a non-interactive bash command (TERM=dumb, pipefail) in the project root.";
162
- return {
163
- name: "bash",
164
- description: description +
165
- " Servers/watchers/REPLs: run_in_background + wake.pattern, then task_output wait_ms; " +
166
- // "Never by name or pattern" moved here from the lean skill, which only
167
- // loads for perf work: a pattern kill took down the host daemon and every
168
- // sibling session.
169
- "never `&`, nohup or sleep. Leave servers running. Kill by exact PID, never by name or pattern (pkill, killall, taskkill /IM): you run inside a host process.",
170
- parameters: BashParams,
171
- executionMode: "sequential",
172
- async execute({ command, timeout: timeoutMs, run_in_background, persist, wake, review }, context) {
173
- if (review &&
174
- (persist ||
175
- run_in_background ||
176
- ops !== localOperations ||
177
- !classifyVerificationCommand(command).accepted)) {
178
- return REVIEW_REJECTED_BEFORE_START;
179
- }
180
- if (wake && !run_in_background) {
181
- return "Error: wake conditions require run_in_background=true — there is nothing to watch on a foreground call.";
182
- }
183
- let wakeRules;
184
- if (wake?.pattern) {
185
- try {
186
- // No flags: lastIndex-free exec/test keeps the watcher's scans pure.
187
- wakeRules = { pattern: new RegExp(wake.pattern) };
188
- }
189
- catch (error) {
190
- return `Error: wake.pattern is not a valid regex (${error.message}). Fix the pattern and retry.`;
191
- }
192
- }
193
- if (wake?.silence_seconds) {
194
- wakeRules = { ...wakeRules, silenceMs: wake.silence_seconds * 1000 };
195
- }
196
- // A long sleep-only foreground call while something runs in the
197
- // background is a guessed wait: too short wastes a turn, too long wastes
198
- // wall-clock. Redirect rather than run it — descriptions alone do not
199
- // reliably beat the habit. Brief sleeps stay allowed, because letting a
200
- // just-started dev server settle before curling it is legitimate and no
201
- // exit is ever coming for it.
202
- const napSeconds = run_in_background ? null : sleepOnlySeconds(command);
203
- if (napSeconds !== null && napSeconds >= GUESSED_WAIT_SECONDS) {
204
- const running = processManager.list().filter((proc) => proc.exitCode === null);
205
- if (running.length > 0) {
206
- const ids = running.map((proc) => proc.id).join(", ");
207
- return (`Error: refusing to sleep ${napSeconds}s while ${running.length} background ` +
208
- `process(es) are running (${ids}). Sleeping guesses at a finish time. Call ` +
209
- `task_output with wait_ms instead \u2014 it returns on exit or a declared wake. ` +
210
- `For something that never exits, such as a dev server, run it with a wake ` +
211
- `pattern and wait for that line.`);
212
- }
213
- }
214
- if (isPlanModeActive(planModeRef) && !isReadOnlyCommand(command)) {
215
- return planModeRestriction("bash");
216
- }
217
- // Catastrophic-command guard — enforced in code, before every execution
218
- // path (persistent shell, background, and normal spawn).
219
- const catastrophic = isCatastrophicCommand(command, cwd);
220
- if (catastrophic) {
221
- return `Error: ${catastrophic}`;
222
- }
223
- // Destructive-git guard — refuses reset --hard / checkout -- / restore /
224
- // clean -f / stash drop / branch -D / force push when work would be lost.
225
- // A persist:true call runs wherever the session shell last cd'd to.
226
- const liveShell = persist && process.platform !== "win32" ? sessionShell : null;
227
- const gitBlocked = await checkDestructiveGit(command, {
228
- cwd,
229
- resolveCwd: liveShell && !liveShell.isBusy
230
- ? async () => (await liveShell.run("pwd", 2_000, context.signal)).output.trim() || null
231
- : undefined,
232
- });
233
- if (gitBlocked) {
234
- return `Error: ${gitBlocked}`;
235
- }
236
- // Shell-threat guard — pipe-to-shell, reverse shells, secret exfiltration,
237
- // lookalike hosts and terminal-escape tricks (core/shell-threats.ts).
238
- const threatBlocked = shellThreatBlockMessage(command);
239
- if (threatBlocked) {
240
- return `Error: ${threatBlocked}`;
162
+ const runBash = async ({ command, timeout: timeoutMs, run_in_background, persist, wake, review }, context) => {
163
+ if (wake && !run_in_background) {
164
+ return "Error: wake conditions require run_in_background=true — there is nothing to watch on a foreground call.";
165
+ }
166
+ let wakeRules;
167
+ if (wake?.pattern) {
168
+ try {
169
+ // No flags: lastIndex-free exec/test keeps the watcher's scans pure.
170
+ wakeRules = { pattern: new RegExp(wake.pattern) };
241
171
  }
242
- // Package-install guard: known malware (local feed + version-aware OSV),
243
- // lockfile contents, provenance downgrade, release age and precise
244
- // typosquats. A catch is a block; network only for installs, fail-open.
245
- const cooldownDays = getPackageCooldownDays();
246
- // Version detection starts now, in parallel with the check (shared, once per process).
247
- const install = mayInstall(command);
248
- const versionsReady = install
249
- ? detectMentionedVersions(command, cwd)
250
- : Promise.resolve({});
251
- const packageThreats = install
252
- ? await checkPackageInstall(command, { signal: context.signal, cwd, cooldownDays })
253
- : [];
254
- const packageBlocked = packageBlockMessage(packageThreats);
255
- if (packageBlocked) {
256
- // `details` carries the refused packages to the session, which records
257
- // them in the project's "don't install" list (core/blocked-packages-file.ts).
258
- const blocked = packageThreats.flatMap((t) => t.blocked ?? []);
259
- return {
260
- content: `Error: ${packageBlocked}`,
261
- ...(blocked.length > 0 ? { details: { safetyBlock: { packages: blocked } } } : {}),
262
- };
172
+ catch (error) {
173
+ return `Error: wake.pattern is not a valid regex (${error.message}). Fix the pattern and retry.`;
263
174
  }
264
- // Native release-age cooldown for every install (transitive deps too).
265
- const versions = await versionsReady;
266
- const cooldownEnv = install
267
- ? packageCooldownEnv(command, { days: cooldownDays, now: Date.now(), cwd, versions })
268
- : {};
269
- // bun has no env setting: the cooldown goes in as a flag.
270
- const runCommand = install
271
- ? bunCooldownCommand(command, cooldownDays, versions.bun ?? null)
272
- : command;
273
- // Network allowlist — defence in depth only. Recognises the common egress
274
- // command shapes; an unrecognised command is never blocked (see
275
- // core/network-guard.ts for why this is not a sandbox).
276
- const networkBlocked = checkCommandPolicy(command, getNetworkPolicy);
277
- if (networkBlocked) {
278
- return `Error: ${networkBlocked}`;
175
+ }
176
+ if (wake?.silence_seconds) {
177
+ wakeRules = { ...wakeRules, silenceMs: wake.silence_seconds * 1000 };
178
+ }
179
+ // A long sleep-only foreground call while something runs in the
180
+ // background is a guessed wait: too short wastes a turn, too long wastes
181
+ // wall-clock. Redirect rather than run it — descriptions alone do not
182
+ // reliably beat the habit. Brief sleeps stay allowed, because letting a
183
+ // just-started dev server settle before curling it is legitimate and no
184
+ // exit is ever coming for it.
185
+ const napSeconds = run_in_background ? null : sleepOnlySeconds(command);
186
+ if (napSeconds !== null && napSeconds >= GUESSED_WAIT_SECONDS) {
187
+ const running = processManager.list().filter((proc) => proc.exitCode === null);
188
+ if (running.length > 0) {
189
+ const ids = running.map((proc) => proc.id).join(", ");
190
+ return (`Error: refusing to sleep ${napSeconds}s while ${running.length} background ` +
191
+ `process(es) are running (${ids}). Sleeping guesses at a finish time. Call ` +
192
+ `task_output with wait_ms instead \u2014 it returns on exit or a declared wake. ` +
193
+ `For something that never exits, such as a dev server, run it with a wake ` +
194
+ `pattern and wait for that line.`);
279
195
  }
280
- const sandboxPolicy = getSandboxPolicy?.() ?? { mode: "off", allowedDomains: [] };
281
- const prepareLaunch = async (shell) => prepareSandboxLaunch(shell, cwd, sandboxPolicy);
282
- // Persistent session mode — POSIX only; Windows-without-bash falls through
283
- // to the normal spawn path (cmd.exe fallback) below.
284
- if (persist && !run_in_background && !resolveShell(command, shellOpts).isCmdFallback) {
285
- const sandboxKey = JSON.stringify(sandboxPolicy);
286
- if (sessionShell && sessionSandboxKey !== sandboxKey) {
287
- sessionShell.kill();
288
- sessionShell = null;
289
- }
290
- if (!sessionShell) {
291
- try {
292
- const shell = resolveShell("", shellOpts);
293
- const launch = await prepareLaunch({
294
- ...shell,
295
- args: ["--norc", "--noprofile", "-o", "pipefail"],
296
- });
297
- sessionShell = new PersistentShell(cwd,
298
- // Env is fixed at shell start: only pip's (always safe) here;
299
- // the others are scoped per command below.
300
- sandboxAwareEnv(launch.sandboxed, cooldownDays > 0 ? { PIP_UPLOADED_PRIOR_TO: `P${cooldownDays}D` } : {}), MAX_OUTPUT_BYTES, shellOpts, launch);
301
- sessionSandboxKey = sandboxKey;
302
- sessionSandboxed = launch.sandboxed;
303
- }
304
- catch (error) {
305
- return `Error: OS sandbox unavailable; command was not run: ${error.message}`;
306
- }
307
- }
308
- if (context.signal.aborted)
309
- return CANCELLED_BEFORE_START;
310
- const res = await sessionShell.run(scopeCooldown(runCommand, cooldownEnv), timeoutMs ?? DEFAULT_TIMEOUT, context.signal, context.onUpdate
311
- ? (text) => context.onUpdate?.({ type: "bash_progress", output: text, totalBytes: 0 })
312
- : undefined);
313
- const hint = install && res.exitCode !== 0 ? cooldownFailureHint(res.output, cooldownDays) : null;
314
- const output = (hint ? `[${hint}]\n` : "") + (await renderBashOutput(res.output));
315
- const exitCode = res.exitCode === "TIMEOUT"
316
- ? `TIMEOUT (${timeoutMs ?? DEFAULT_TIMEOUT}ms)` +
317
- (res.shellKept
318
- ? " — the command was stopped; the session shell kept its cwd/env"
319
- : "")
320
- : String(res.exitCode);
321
- // The restart note sits right under the exit code so output truncation
322
- // can never drop it.
323
- const restartNote = sessionShell.takeRestartNote();
324
- const note = restartNote ? `${restartNote}\n` : "";
325
- return annotateSandboxDenial(`Exit code: ${exitCode}\n${note}${output}`, sessionSandboxed);
196
+ }
197
+ if (isPlanModeActive(planModeRef) && !isReadOnlyCommand(command)) {
198
+ return planModeRestriction("bash");
199
+ }
200
+ // Catastrophic-command guard — enforced in code, before every execution
201
+ // path (persistent shell, background, and normal spawn).
202
+ const catastrophic = isCatastrophicCommand(command, cwd);
203
+ if (catastrophic) {
204
+ return `Error: ${catastrophic}`;
205
+ }
206
+ // Destructive-git guard — refuses reset --hard / checkout -- / restore /
207
+ // clean -f / stash drop / branch -D / force push when work would be lost.
208
+ // A persist:true call runs wherever the session shell last cd'd to.
209
+ const liveShell = persist && process.platform !== "win32" ? sessionShell : null;
210
+ const gitBlocked = await checkDestructiveGit(command, {
211
+ cwd,
212
+ resolveCwd: liveShell && !liveShell.isBusy
213
+ ? async () => (await liveShell.run("pwd", 2_000, context.signal)).output.trim() || null
214
+ : undefined,
215
+ });
216
+ if (gitBlocked) {
217
+ return `Error: ${gitBlocked}`;
218
+ }
219
+ // Shell-threat guard — pipe-to-shell, reverse shells, secret exfiltration,
220
+ // lookalike hosts and terminal-escape tricks (core/shell-threats.ts).
221
+ const threatBlocked = shellThreatBlockMessage(command);
222
+ if (threatBlocked) {
223
+ return `Error: ${threatBlocked}`;
224
+ }
225
+ // Package-install guard: known malware (local feed + version-aware OSV),
226
+ // lockfile contents, provenance downgrade, release age and precise
227
+ // typosquats. A catch is a block; network only for installs, fail-open.
228
+ const cooldownDays = getPackageCooldownDays();
229
+ // Version detection starts now, in parallel with the check (shared, once per process).
230
+ const install = mayInstall(command);
231
+ const versionsReady = install
232
+ ? detectMentionedVersions(command, cwd)
233
+ : Promise.resolve({});
234
+ const packageThreats = install
235
+ ? await checkPackageInstall(command, { signal: context.signal, cwd, cooldownDays })
236
+ : [];
237
+ const packageBlocked = packageBlockMessage(packageThreats);
238
+ if (packageBlocked) {
239
+ // `details` carries the refused packages to the session, which records
240
+ // them in the project's "don't install" list (core/blocked-packages-file.ts).
241
+ const blocked = packageThreats.flatMap((t) => t.blocked ?? []);
242
+ return {
243
+ content: `Error: ${packageBlocked}`,
244
+ ...(blocked.length > 0 ? { details: { safetyBlock: { packages: blocked } } } : {}),
245
+ };
246
+ }
247
+ // Native release-age cooldown for every install (transitive deps too).
248
+ const versions = await versionsReady;
249
+ const cooldownEnv = install
250
+ ? packageCooldownEnv(command, { days: cooldownDays, now: Date.now(), cwd, versions })
251
+ : {};
252
+ // bun has no env setting: the cooldown goes in as a flag.
253
+ const runCommand = install
254
+ ? bunCooldownCommand(command, cooldownDays, versions.bun ?? null)
255
+ : command;
256
+ // Network allowlist — defence in depth only. Recognises the common egress
257
+ // command shapes; an unrecognised command is never blocked (see
258
+ // core/network-guard.ts for why this is not a sandbox).
259
+ const networkBlocked = checkCommandPolicy(command, getNetworkPolicy);
260
+ if (networkBlocked) {
261
+ return `Error: ${networkBlocked}`;
262
+ }
263
+ const sandboxPolicy = getSandboxPolicy?.() ?? { mode: "off", allowedDomains: [] };
264
+ const prepareLaunch = async (shell) => prepareSandboxLaunch(shell, cwd, sandboxPolicy);
265
+ // Persistent session mode — POSIX only; Windows-without-bash falls through
266
+ // to the normal spawn path (cmd.exe fallback) below.
267
+ if (persist && !run_in_background && !resolveShell(command, shellOpts).isCmdFallback) {
268
+ const sandboxKey = JSON.stringify(sandboxPolicy);
269
+ if (sessionShell && sessionSandboxKey !== sandboxKey) {
270
+ sessionShell.kill();
271
+ sessionShell = null;
326
272
  }
327
- if (run_in_background) {
328
- let launch;
273
+ if (!sessionShell) {
329
274
  try {
330
- launch = await prepareLaunch(resolveShell(runCommand, shellOpts));
275
+ const shell = resolveShell("", shellOpts);
276
+ const launch = await prepareLaunch({
277
+ ...shell,
278
+ args: ["--norc", "--noprofile", "-o", "pipefail"],
279
+ });
280
+ sessionShell = new PersistentShell(cwd,
281
+ // Env is fixed at shell start: only pip's (always safe) here;
282
+ // the others are scoped per command below.
283
+ sandboxAwareEnv(launch.sandboxed, cooldownDays > 0 ? { PIP_UPLOADED_PRIOR_TO: `P${cooldownDays}D` } : {}), MAX_OUTPUT_BYTES, shellOpts, launch);
284
+ sessionSandboxKey = sandboxKey;
285
+ sessionSandboxed = launch.sandboxed;
331
286
  }
332
287
  catch (error) {
333
288
  return `Error: OS sandbox unavailable; command was not run: ${error.message}`;
334
289
  }
335
- if (context.signal.aborted)
336
- return CANCELLED_BEFORE_START;
337
- const result = await processManager.start(runCommand, cwd, launch, wakeRules, cooldownEnv);
338
- const watchWarnings = backgroundWatchWarnings(command);
339
- return (`Background process started.\n` +
340
- `ID: ${result.id}\n` +
341
- `PID: ${result.pid}\n` +
342
- `Log: ${result.logFile}\n` +
343
- (wakeRules
344
- ? result.wakeArmed
345
- ? `Wake rules armed: ${[
346
- wakeRules.pattern ? `pattern /${wakeRules.pattern.source}/` : null,
347
- wakeRules.silenceMs ? `silence ${wakeRules.silenceMs / 1000}s` : null,
348
- ]
349
- .filter(Boolean)
350
- .join(" + ")}. You will be notified automatically when one fires or the process exits.\n`
351
- : `Wake conditions were NOT armed: this session has no notification path, so nothing will wake you automatically. Poll task_output periodically instead.\n`
352
- : "") +
353
- `Use task_output with id="${result.id}" to read output, ` +
354
- `task_send to type input/answer prompts, task_stop to stop it.` +
355
- watchWarnings.map((warning) => `\nWarning: ${warning}`).join(""));
356
290
  }
357
- const effectiveTimeout = timeoutMs ?? defaultTimeoutMs;
358
- // Cross-platform shell: bash on macOS/Linux, Git Bash on Windows (or
359
- // cmd.exe fallback), wrapped by the OS sandbox before any child starts.
360
- const shell = resolveShell(runCommand, shellOpts);
291
+ if (context.signal.aborted)
292
+ return CANCELLED_BEFORE_START;
293
+ const res = await sessionShell.run(scopeCooldown(runCommand, cooldownEnv), timeoutMs ?? DEFAULT_TIMEOUT, context.signal, context.onUpdate
294
+ ? (text) => context.onUpdate?.({ type: "bash_progress", output: text, totalBytes: 0 })
295
+ : undefined);
296
+ const hint = install && res.exitCode !== 0 ? cooldownFailureHint(res.output, cooldownDays) : null;
297
+ const output = (hint ? `[${hint}]\n` : "") + (await renderBashOutput(res.output));
298
+ const exitCode = res.exitCode === "TIMEOUT"
299
+ ? `TIMEOUT (${timeoutMs ?? DEFAULT_TIMEOUT}ms)` +
300
+ (res.shellKept ? " — the command was stopped; the session shell kept its cwd/env" : "")
301
+ : String(res.exitCode);
302
+ // The restart note sits right under the exit code so output truncation
303
+ // can never drop it.
304
+ const restartNote = sessionShell.takeRestartNote();
305
+ const note = restartNote ? `${restartNote}\n` : "";
306
+ return annotateSandboxDenial(`Exit code: ${exitCode}\n${note}${output}`, sessionSandboxed);
307
+ }
308
+ if (run_in_background) {
361
309
  let launch;
362
310
  try {
363
- launch = await prepareLaunch(shell);
311
+ launch = await prepareLaunch(resolveShell(runCommand, shellOpts));
364
312
  }
365
313
  catch (error) {
366
- return `Exit code: 1\nOS sandbox unavailable; command was not run: ${error.message}`;
314
+ return `Error: OS sandbox unavailable; command was not run: ${error.message}`;
367
315
  }
368
- // Stop may have landed while the launch was being prepared. The abort
369
- // listener below would never fire for an already-aborted signal.
370
316
  if (context.signal.aborted)
371
317
  return CANCELLED_BEFORE_START;
372
- const result = await new Promise((resolve, reject) => {
373
- const child = ops.spawn(launch.file, launch.args, {
374
- cwd,
375
- detached: true,
376
- stdio: ["ignore", "pipe", "pipe"],
377
- env: sandboxAwareEnv(launch.sandboxed, cooldownEnv),
378
- });
379
- const chunks = [];
380
- let totalBytes = 0;
381
- let outputCapped = false;
382
- const onData = (data) => {
383
- if (outputCapped)
384
- return;
385
- totalBytes += data.length;
386
- if (totalBytes > MAX_OUTPUT_BYTES) {
387
- outputCapped = true;
388
- return;
389
- }
390
- chunks.push(data);
391
- // Stream progress to UI for live output display
392
- if (context.onUpdate) {
393
- context.onUpdate({
394
- type: "bash_progress",
395
- output: data.toString("utf-8"),
396
- totalBytes,
397
- });
398
- }
399
- };
400
- child.stdout?.on("data", onData);
401
- child.stderr?.on("data", onData);
402
- let killed = false;
403
- let timedOut = false;
404
- let backgrounded = false;
405
- const startedAt = Date.now();
406
- /**
407
- * Hand a still-running command to the process manager instead of
408
- * killing it, so a slow build or test run keeps going (same process,
409
- * same cwd) while the agent moves on. Only for the default budget: an
410
- * explicit `timeout` is the model saying when to give up. Returns
411
- * false when adoption is not possible, leaving the kill path to run.
412
- */
413
- const moveToBackground = () => {
414
- // The shell already exited and only leftovers hold the pipes; the
415
- // drain path owns that case.
416
- if (timeoutMs !== undefined || child.exitCode !== null || !child.pid)
417
- return false;
418
- child.stdout?.off("data", onData);
419
- child.stderr?.off("data", onData);
420
- let adopted;
421
- try {
422
- adopted = processManager.adopt(child, command, startedAt, Buffer.concat(chunks));
423
- }
424
- catch {
425
- child.stdout?.on("data", onData);
426
- child.stderr?.on("data", onData);
427
- return false;
428
- }
429
- backgrounded = true;
430
- context.signal.removeEventListener("abort", onAbort);
431
- void (async () => {
432
- const soFar = await renderBashOutput(Buffer.concat(chunks).toString("utf-8"));
433
- resolve(`Still running after ${effectiveTimeout / 1000}s, so it was moved to the background ` +
434
- `instead of being stopped. It keeps its working directory and output.\n` +
435
- `ID: ${adopted.id}\n` +
436
- `PID: ${adopted.pid}\n` +
437
- `Log: ${adopted.logFile}\n` +
438
- `You will be notified when it exits or prints a failure. Use task_output with id="${adopted.id}" ` +
439
- `(wait_ms to block until it exits) to read output, task_stop to stop it. ` +
440
- `Pass an explicit timeout to have a command stopped instead.\n` +
441
- (soFar ? `Output so far:\n${soFar}` : "No output so far."));
442
- })();
443
- return true;
444
- };
445
- // Timeout handling
446
- const timer = setTimeout(() => {
447
- if (moveToBackground())
448
- return;
449
- timedOut = true;
450
- killed = true;
451
- if (child.pid)
452
- killProcessTree(child.pid);
453
- }, effectiveTimeout);
454
- // Abort signal handling
455
- const onAbort = () => {
456
- killed = true;
457
- if (child.pid)
458
- killProcessTree(child.pid);
459
- };
460
- context.signal.addEventListener("abort", onAbort, { once: true });
461
- // "close" waits for every holder of the stdout/stderr pipes, and a
462
- // process the command left running (`cmd &`, `nohup cmd`) inherits them,
463
- // so without this the call hangs until the timeout. Once the shell
464
- // itself exits, let late output drain briefly, then stop the leftovers
465
- // and release the pipes so "close" fires.
466
- let leftover;
467
- let drainTimer;
468
- child.on("exit", () => {
469
- drainTimer = setTimeout(() => {
470
- leftover = child.pid && killLeftoverGroup(child.pid) ? "stopped" : "detached";
471
- child.stdout?.destroy();
472
- child.stderr?.destroy();
473
- }, LEFTOVER_DRAIN_MS);
474
- });
475
- child.on("close", async (code) => {
476
- clearTimeout(timer);
477
- clearTimeout(drainTimer);
478
- context.signal.removeEventListener("abort", onAbort);
479
- // The process manager owns an adopted command's exit.
480
- if (backgrounded)
481
- return;
482
- const rawOutput = Buffer.concat(chunks).toString("utf-8");
483
- let output = await renderBashOutput(rawOutput);
484
- if (outputCapped) {
485
- output =
486
- `[Output capped at ${MAX_OUTPUT_BYTES / 1024 / 1024} MB to prevent memory exhaustion]\n` +
487
- output;
488
- }
489
- // Windows without Git Bash: commands ran under cmd.exe, NOT bash. Tell
490
- // the model so it uses cmd syntax (no `ls`/`grep`/pipes/single-quotes)
491
- // and doesn't misread failures as a wrong directory / environment.
492
- if (shell.isCmdFallback) {
493
- output =
494
- "[Ran under Windows cmd.exe — bash is unavailable. Use cmd syntax " +
495
- "(dir, findstr, type); POSIX commands and quoting will fail. " +
496
- "Install Git for Windows to get bash.]\n" +
497
- output;
498
- }
499
- const hint = install && code !== 0 && !killed ? cooldownFailureHint(rawOutput, cooldownDays) : null;
500
- if (hint)
501
- output = `[${hint}]\n` + output;
502
- if (leftover && !killed) {
503
- const fate = leftover === "stopped"
504
- ? "so it was stopped"
505
- : "so its later output was not captured; it may still be running";
506
- output =
507
- `[The command exited, but a process it left running in the background ` +
508
- `(& or nohup) still held its output ${LEFTOVER_DRAIN_MS / 1000}s later, ${fate}. ` +
509
- `Use run_in_background=true for anything that should keep running.]\n` +
510
- output;
511
- }
512
- const exitCode = timedOut
513
- ? `TIMEOUT (${effectiveTimeout}ms)`
514
- : killed
515
- ? "KILLED"
516
- : String(code ?? 1);
517
- resolve(annotateSandboxDenial(`Exit code: ${exitCode}\n${output}`, launch.sandboxed));
518
- });
519
- child.on("error", (err) => {
520
- if (backgrounded)
521
- return;
522
- clearTimeout(timer);
523
- clearTimeout(drainTimer);
524
- context.signal.removeEventListener("abort", onAbort);
525
- reject(new Error(`Exit code: 1\nFailed to spawn: ${err.message}`));
526
- });
318
+ const result = await processManager.start(runCommand, cwd, launch, wakeRules, cooldownEnv);
319
+ const watchWarnings = backgroundWatchWarnings(command);
320
+ return (`Background process started.\n` +
321
+ `ID: ${result.id}\n` +
322
+ `PID: ${result.pid}\n` +
323
+ `Log: ${result.logFile}\n` +
324
+ (wakeRules
325
+ ? result.wakeArmed
326
+ ? `Wake rules armed: ${[
327
+ wakeRules.pattern ? `pattern /${wakeRules.pattern.source}/` : null,
328
+ wakeRules.silenceMs ? `silence ${wakeRules.silenceMs / 1000}s` : null,
329
+ ]
330
+ .filter(Boolean)
331
+ .join(" + ")}. You will be notified automatically when one fires or the process exits.\n`
332
+ : `Wake conditions were NOT armed: this session has no notification path, so nothing will wake you automatically. Poll task_output periodically instead.\n`
333
+ : "") +
334
+ `Use task_output with id="${result.id}" to read output, ` +
335
+ `task_send to type input/answer prompts, task_stop to stop it.` +
336
+ watchWarnings.map((warning) => `\nWarning: ${warning}`).join(""));
337
+ }
338
+ const effectiveTimeout = timeoutMs ?? defaultTimeoutMs;
339
+ // Cross-platform shell: bash on macOS/Linux, Git Bash on Windows (or
340
+ // cmd.exe fallback), wrapped by the OS sandbox before any child starts.
341
+ const shell = resolveShell(runCommand, shellOpts);
342
+ let launch;
343
+ try {
344
+ launch = await prepareLaunch(shell);
345
+ }
346
+ catch (error) {
347
+ return `Exit code: 1\nOS sandbox unavailable; command was not run: ${error.message}`;
348
+ }
349
+ // Stop may have landed while the launch was being prepared. The abort
350
+ // listener below would never fire for an already-aborted signal.
351
+ if (context.signal.aborted)
352
+ return CANCELLED_BEFORE_START;
353
+ const result = await new Promise((resolve, reject) => {
354
+ const child = ops.spawn(launch.file, launch.args, {
355
+ cwd,
356
+ detached: true,
357
+ stdio: ["ignore", "pipe", "pipe"],
358
+ env: sandboxAwareEnv(launch.sandboxed, cooldownEnv),
359
+ });
360
+ const chunks = [];
361
+ let totalBytes = 0;
362
+ let outputCapped = false;
363
+ const onData = (data) => {
364
+ if (outputCapped)
365
+ return;
366
+ totalBytes += data.length;
367
+ if (totalBytes > MAX_OUTPUT_BYTES) {
368
+ outputCapped = true;
369
+ return;
370
+ }
371
+ chunks.push(data);
372
+ // Stream progress to UI for live output display
373
+ if (context.onUpdate) {
374
+ context.onUpdate({
375
+ type: "bash_progress",
376
+ output: data.toString("utf-8"),
377
+ totalBytes,
378
+ });
379
+ }
380
+ };
381
+ child.stdout?.on("data", onData);
382
+ child.stderr?.on("data", onData);
383
+ let killed = false;
384
+ let timedOut = false;
385
+ let backgrounded = false;
386
+ const startedAt = Date.now();
387
+ /**
388
+ * Hand a still-running command to the process manager instead of
389
+ * killing it, so a slow build or test run keeps going (same process,
390
+ * same cwd) while the agent moves on. Only for the default budget: an
391
+ * explicit `timeout` is the model saying when to give up. Returns
392
+ * false when adoption is not possible, leaving the kill path to run.
393
+ */
394
+ const moveToBackground = () => {
395
+ // The shell already exited and only leftovers hold the pipes; the
396
+ // drain path owns that case.
397
+ if (timeoutMs !== undefined || child.exitCode !== null || !child.pid)
398
+ return false;
399
+ child.stdout?.off("data", onData);
400
+ child.stderr?.off("data", onData);
401
+ let adopted;
402
+ try {
403
+ adopted = processManager.adopt(child, command, startedAt, Buffer.concat(chunks));
404
+ }
405
+ catch {
406
+ child.stdout?.on("data", onData);
407
+ child.stderr?.on("data", onData);
408
+ return false;
409
+ }
410
+ backgrounded = true;
411
+ context.signal.removeEventListener("abort", onAbort);
412
+ void (async () => {
413
+ const soFar = await renderBashOutput(Buffer.concat(chunks).toString("utf-8"));
414
+ resolve(`Still running after ${effectiveTimeout / 1000}s, so it was moved to the background ` +
415
+ `instead of being stopped. It keeps its working directory and output.\n` +
416
+ `ID: ${adopted.id}\n` +
417
+ `PID: ${adopted.pid}\n` +
418
+ `Log: ${adopted.logFile}\n` +
419
+ `You will be notified when it exits or prints a failure. Use task_output with id="${adopted.id}" ` +
420
+ `(wait_ms to block until it exits) to read output, task_stop to stop it. ` +
421
+ `Pass an explicit timeout to have a command stopped instead.\n` +
422
+ (soFar ? `Output so far:\n${soFar}` : "No output so far."));
423
+ })();
424
+ return true;
425
+ };
426
+ // Timeout handling
427
+ const timer = setTimeout(() => {
428
+ if (moveToBackground())
429
+ return;
430
+ timedOut = true;
431
+ killed = true;
432
+ if (child.pid)
433
+ killProcessTree(child.pid);
434
+ }, effectiveTimeout);
435
+ // Abort signal handling
436
+ const onAbort = () => {
437
+ killed = true;
438
+ if (child.pid)
439
+ killProcessTree(child.pid);
440
+ };
441
+ context.signal.addEventListener("abort", onAbort, { once: true });
442
+ // "close" waits for every holder of the stdout/stderr pipes, and a
443
+ // process the command left running (`cmd &`, `nohup cmd`) inherits them,
444
+ // so without this the call hangs until the timeout. Once the shell
445
+ // itself exits, let late output drain briefly, then stop the leftovers
446
+ // and release the pipes so "close" fires.
447
+ let leftover;
448
+ let drainTimer;
449
+ child.on("exit", () => {
450
+ drainTimer = setTimeout(() => {
451
+ leftover = child.pid && killLeftoverGroup(child.pid) ? "stopped" : "detached";
452
+ child.stdout?.destroy();
453
+ child.stderr?.destroy();
454
+ }, LEFTOVER_DRAIN_MS);
455
+ });
456
+ child.on("close", async (code) => {
457
+ clearTimeout(timer);
458
+ clearTimeout(drainTimer);
459
+ context.signal.removeEventListener("abort", onAbort);
460
+ // The process manager owns an adopted command's exit.
461
+ if (backgrounded)
462
+ return;
463
+ const rawOutput = Buffer.concat(chunks).toString("utf-8");
464
+ let output = await renderBashOutput(rawOutput);
465
+ if (outputCapped) {
466
+ output =
467
+ `[Output capped at ${MAX_OUTPUT_BYTES / 1024 / 1024} MB to prevent memory exhaustion]\n` +
468
+ output;
469
+ }
470
+ // Windows without Git Bash: commands ran under cmd.exe, NOT bash. Tell
471
+ // the model so it uses cmd syntax (no `ls`/`grep`/pipes/single-quotes)
472
+ // and doesn't misread failures as a wrong directory / environment.
473
+ if (shell.isCmdFallback) {
474
+ output =
475
+ "[Ran under Windows cmd.exe — bash is unavailable. Use cmd syntax " +
476
+ "(dir, findstr, type); POSIX commands and quoting will fail. " +
477
+ "Install Git for Windows to get bash.]\n" +
478
+ output;
479
+ }
480
+ const hint = install && code !== 0 && !killed ? cooldownFailureHint(rawOutput, cooldownDays) : null;
481
+ if (hint)
482
+ output = `[${hint}]\n` + output;
483
+ if (leftover && !killed) {
484
+ const fate = leftover === "stopped"
485
+ ? "so it was stopped"
486
+ : "so its later output was not captured; it may still be running";
487
+ output =
488
+ `[The command exited, but a process it left running in the background ` +
489
+ `(& or nohup) still held its output ${LEFTOVER_DRAIN_MS / 1000}s later, ${fate}. ` +
490
+ `Use run_in_background=true for anything that should keep running.]\n` +
491
+ output;
492
+ }
493
+ const exitCode = timedOut
494
+ ? `TIMEOUT (${effectiveTimeout}ms)`
495
+ : killed
496
+ ? "KILLED"
497
+ : String(code ?? 1);
498
+ resolve(annotateSandboxDenial(`Exit code: ${exitCode}\n${output}`, launch.sandboxed));
499
+ });
500
+ child.on("error", (err) => {
501
+ if (backgrounded)
502
+ return;
503
+ clearTimeout(timer);
504
+ clearTimeout(drainTimer);
505
+ context.signal.removeEventListener("abort", onAbort);
506
+ reject(new Error(`Exit code: 1\nFailed to spawn: ${err.message}`));
527
507
  });
528
- if (!review || context.signal.aborted || !/^Exit code: 0(?:\s|$)/.test(result))
529
- return result;
530
- const inspection = await collectVerificationReview(cwd, context.signal);
531
- return `${result}\n\n--- Independent read-only review ---\n${await renderBashOutput(inspection)}`;
508
+ });
509
+ if (!review || context.signal.aborted || !/^Exit code: 0(?:\s|$)/.test(result))
510
+ return result;
511
+ const inspection = await collectVerificationReview(cwd, context.signal);
512
+ return `${result}\n\n--- Independent read-only review ---\n${await renderBashOutput(inspection)}`;
513
+ };
514
+ return {
515
+ name: "bash",
516
+ description: description +
517
+ " Servers/watchers/REPLs: run_in_background + wake.pattern, then task_output wait_ms; " +
518
+ // "Never by name or pattern" moved here from the lean skill, which only
519
+ // loads for perf work: a pattern kill took down the host daemon and every
520
+ // sibling session.
521
+ "never `&`, nohup or sleep. Leave servers running. Kill by exact PID, never by name or pattern (pkill, killall, taskkill /IM): you run inside a host process.",
522
+ parameters: BashParams,
523
+ executionMode: "sequential",
524
+ async execute(args, context) {
525
+ // Rejecting a review-flagged edit+test command threw the edits away, and the
526
+ // model re-sent them without review every time (24/24 bench cases), so run
527
+ // the command as asked and skip only the review.
528
+ const skipReview = args.review === true &&
529
+ (args.persist === true ||
530
+ args.run_in_background === true ||
531
+ ops !== localOperations ||
532
+ !classifyVerificationCommand(args.command).accepted);
533
+ if (!skipReview)
534
+ return runBash(args, context);
535
+ const result = await runBash({ ...args, review: false }, context);
536
+ return typeof result === "string" ? `${result}\n\n${REVIEW_SKIPPED_NOTE}` : result;
532
537
  },
533
538
  };
534
539
  }