@kenkaiiii/ggcoder 5.88.1 → 5.89.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.
@@ -0,0 +1,268 @@
1
+ import { spawn as nodeSpawn } from "node:child_process";
2
+ import path from "node:path";
3
+ import { StringDecoder } from "node:string_decoder";
4
+ import { environmentSecrets, redactText } from "@kenkaiiii/gg-ai";
5
+ import { resolveShell } from "../core/shell.js";
6
+ import { killProcessTree } from "../utils/process.js";
7
+ /**
8
+ * Commands the user runs themselves from the app's input (`!git status`).
9
+ *
10
+ * Not the agent's bash tool: no sandbox, no guards, no timeout. These run with
11
+ * the user's own shell, environment and permissions in the project folder,
12
+ * exactly as if typed in a terminal, and only ever because the user submitted
13
+ * them (see shell-routes.ts for the confirmation gate).
14
+ */
15
+ /**
16
+ * Error output (stderr) is wrapped in these private-use characters in the
17
+ * window's copy of the output, so it can be shown differently while keeping
18
+ * its place among normal output. The agent's copy never contains them. The
19
+ * app (ShellBlock.tsx) uses the same two characters.
20
+ */
21
+ export const STDERR_START = "\uE000";
22
+ export const STDERR_END = "\uE001";
23
+ const STDERR_MARKS = /[\uE000\uE001]/g;
24
+ export function stripStderrMarks(text) {
25
+ return text.replace(STDERR_MARKS, "");
26
+ }
27
+ /** A cut that starts inside error output reopens it, so the first lines keep their look. */
28
+ export function reopenStderr(text) {
29
+ const end = text.indexOf(STDERR_END);
30
+ const start = text.indexOf(STDERR_START);
31
+ return end !== -1 && (start === -1 || end < start) ? STDERR_START + text : text;
32
+ }
33
+ /** Output streamed to the window per command; the rest is summarised. */
34
+ export const SHELL_DISPLAY_MAX_CHARS = 1_000_000;
35
+ /** What the agent (and the saved transcript) gets: the end, where results are. */
36
+ export const SHELL_CONTEXT_MAX_LINES = 200;
37
+ export const SHELL_CONTEXT_MAX_CHARS = 16_000;
38
+ export const SHELL_COMMAND_MAX_CHARS = 8_000;
39
+ /** Batch chunks into one window frame at most this often. */
40
+ const FLUSH_MS = 50;
41
+ /** After the shell exits, how long leftover children may hold its output pipes. */
42
+ const LEFTOVER_GRACE_MS = 1_000;
43
+ const RUN_ID = /^[A-Za-z0-9_-]{1,64}$/;
44
+ export function parseShellRunBody(raw) {
45
+ let body;
46
+ try {
47
+ body = JSON.parse(raw);
48
+ }
49
+ catch {
50
+ return { ok: false, error: "invalid JSON body" };
51
+ }
52
+ if (typeof body !== "object" || body === null)
53
+ return { ok: false, error: "invalid body" };
54
+ const { id, command, confirmed } = body;
55
+ if (typeof id !== "string" || !RUN_ID.test(id))
56
+ return { ok: false, error: "invalid run id" };
57
+ if (typeof command !== "string" || !command.trim())
58
+ return { ok: false, error: "empty command" };
59
+ if (command.length > SHELL_COMMAND_MAX_CHARS)
60
+ return { ok: false, error: "command too long" };
61
+ return { ok: true, runId: id, command: command.trim(), confirmed: confirmed === true };
62
+ }
63
+ /** The user's own environment, minus the app's private daemon variables. */
64
+ export function userShellEnv(env) {
65
+ const out = {};
66
+ for (const [key, value] of Object.entries(env)) {
67
+ if (value === undefined || key.startsWith("GG_APP_"))
68
+ continue;
69
+ out[key] = value;
70
+ }
71
+ // Output goes to a panel, not a terminal: ask tools for plain text.
72
+ out.TERM = "dumb";
73
+ return out;
74
+ }
75
+ /**
76
+ * The user's login shell ($SHELL) where there is one, so their usual shell
77
+ * syntax works; otherwise the same shell the agent uses (Git Bash or cmd on
78
+ * Windows).
79
+ */
80
+ export function userShellLaunch(command, opts = {}) {
81
+ const platform = opts.platform ?? process.platform;
82
+ const env = opts.env ?? process.env;
83
+ const login = env.SHELL?.trim();
84
+ if (platform !== "win32" && login && path.isAbsolute(login)) {
85
+ return { file: login, args: ["-c", command] };
86
+ }
87
+ const shell = resolveShell(command, { platform, env });
88
+ return { file: shell.file, args: shell.args };
89
+ }
90
+ /** The last `maxLines` lines, capped to `maxChars`, and whether anything was cut. */
91
+ export function tailOutput(text, maxLines = SHELL_CONTEXT_MAX_LINES, maxChars = SHELL_CONTEXT_MAX_CHARS) {
92
+ const trimmed = text.replace(/\s+$/, "");
93
+ let start = trimmed.length;
94
+ let lines = 0;
95
+ while (start > 0 && lines < maxLines) {
96
+ const nl = trimmed.lastIndexOf("\n", start - 1);
97
+ start = nl === -1 ? 0 : nl;
98
+ lines++;
99
+ if (nl === -1)
100
+ break;
101
+ }
102
+ let out = trimmed.slice(start === 0 ? 0 : start + 1);
103
+ let truncated = start > 0;
104
+ if (out.length > maxChars) {
105
+ out = out.slice(out.length - maxChars);
106
+ const nl = out.indexOf("\n");
107
+ if (nl !== -1 && nl < out.length - 1)
108
+ out = out.slice(nl + 1);
109
+ truncated = true;
110
+ }
111
+ return { text: out, truncated };
112
+ }
113
+ function seconds(ms) {
114
+ return ms < 10_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.round(ms / 1000)}s`;
115
+ }
116
+ /** One command, as the agent reads it. */
117
+ export function formatShellContext(run) {
118
+ const facts = [
119
+ `in ${run.cwd}`,
120
+ run.error
121
+ ? `failed to start: ${run.error}`
122
+ : run.cancelled
123
+ ? "stopped by the user before it finished"
124
+ : `exit code ${run.exitCode ?? run.signal ?? "unknown"}`,
125
+ seconds(run.durationMs),
126
+ ];
127
+ if (run.tailTruncated)
128
+ facts.push(`showing the last ${SHELL_CONTEXT_MAX_LINES} lines or fewer`);
129
+ const output = run.tail ? run.tail : "(no output)";
130
+ return `$ ${run.command}\n(${facts.join(", ")})\n${output}`;
131
+ }
132
+ /** The user's commands for one window session. */
133
+ export class ShellRunner {
134
+ opts;
135
+ runs = new Map();
136
+ constructor(opts) {
137
+ this.opts = opts;
138
+ }
139
+ isRunning(runId) {
140
+ return this.runs.has(runId);
141
+ }
142
+ start(runId, command, cwd) {
143
+ if (this.runs.has(runId))
144
+ return { ok: false, error: "run id already in use" };
145
+ const env = this.opts.env ?? process.env;
146
+ const now = this.opts.now ?? Date.now;
147
+ const startedAt = now();
148
+ const launch = userShellLaunch(command, { platform: this.opts.platform, env });
149
+ const secrets = environmentSecrets(env);
150
+ let child;
151
+ try {
152
+ child = (this.opts.spawn ?? nodeSpawn)(launch.file, launch.args, {
153
+ cwd,
154
+ env: userShellEnv(env),
155
+ // Own process group, so Stop ends everything the command started.
156
+ detached: process.platform !== "win32",
157
+ stdio: ["ignore", "pipe", "pipe"],
158
+ windowsHide: true,
159
+ });
160
+ }
161
+ catch (err) {
162
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
163
+ }
164
+ const live = { child, cancelled: false };
165
+ this.runs.set(runId, live);
166
+ let shown = 0;
167
+ let displayTruncated = false;
168
+ let pending = "";
169
+ let tail = "";
170
+ let flushTimer = null;
171
+ const flush = () => {
172
+ flushTimer = null;
173
+ if (!pending)
174
+ return;
175
+ this.opts.emit("shell_output", { id: runId, chunk: pending });
176
+ pending = "";
177
+ };
178
+ const decoders = [new StringDecoder("utf8"), new StringDecoder("utf8")];
179
+ const onText = (raw, isError = false) => {
180
+ if (!raw)
181
+ return;
182
+ const clean = stripStderrMarks(raw);
183
+ const text = isError && clean ? STDERR_START + clean + STDERR_END : clean;
184
+ if (!text)
185
+ return;
186
+ tail = (tail + text).slice(-SHELL_CONTEXT_MAX_CHARS * 2);
187
+ if (displayTruncated)
188
+ return;
189
+ const room = SHELL_DISPLAY_MAX_CHARS - shown;
190
+ const part = text.length > room ? text.slice(0, room) : text;
191
+ shown += part.length;
192
+ pending += part;
193
+ if (part.length < text.length)
194
+ displayTruncated = true;
195
+ flushTimer ??= setTimeout(flush, FLUSH_MS);
196
+ };
197
+ child.stdout?.on("data", (data) => onText(decoders[0].write(data)));
198
+ child.stderr?.on("data", (data) => onText(decoders[1].write(data), true));
199
+ let spawnError;
200
+ let ended = false;
201
+ let leftoverTimer = null;
202
+ const finish = (exitCode, signal) => {
203
+ if (ended)
204
+ return;
205
+ ended = true;
206
+ if (leftoverTimer)
207
+ clearTimeout(leftoverTimer);
208
+ onText(decoders[0].end());
209
+ onText(decoders[1].end(), true);
210
+ if (flushTimer)
211
+ clearTimeout(flushTimer);
212
+ flush();
213
+ this.runs.delete(runId);
214
+ const cut = tailOutput(reopenStderr(tail));
215
+ const displayTail = redactText(reopenStderr(cut.text), { secrets });
216
+ this.opts.onEnd({
217
+ runId,
218
+ command,
219
+ cwd,
220
+ exitCode,
221
+ signal,
222
+ durationMs: Math.max(0, now() - startedAt),
223
+ cancelled: live.cancelled,
224
+ tail: stripStderrMarks(displayTail).replace(/\s+$/, ""),
225
+ displayTail,
226
+ tailTruncated: cut.truncated || tail.length >= SHELL_CONTEXT_MAX_CHARS * 2,
227
+ displayTruncated,
228
+ ...(spawnError ? { error: spawnError } : {}),
229
+ });
230
+ };
231
+ child.on("error", (err) => {
232
+ spawnError = err.message;
233
+ finish(null, null);
234
+ });
235
+ child.on("close", (code, signal) => finish(code, signal));
236
+ // `cmd &` leaves children holding the pipes, so "close" would wait on
237
+ // them. Once the shell itself is gone, give output a moment to drain,
238
+ // then stop the leftovers.
239
+ child.on("exit", (code, signal) => {
240
+ leftoverTimer = setTimeout(() => {
241
+ if (child.pid)
242
+ killProcessTree(child.pid);
243
+ child.stdout?.destroy();
244
+ child.stderr?.destroy();
245
+ finish(code, signal);
246
+ }, LEFTOVER_GRACE_MS);
247
+ });
248
+ return { ok: true };
249
+ }
250
+ /** Stop one command and everything it started. False when it isn't running. */
251
+ cancel(runId) {
252
+ const live = this.runs.get(runId);
253
+ if (!live)
254
+ return false;
255
+ live.cancelled = true;
256
+ if (live.child.pid)
257
+ killProcessTree(live.child.pid);
258
+ else
259
+ live.child.kill("SIGKILL");
260
+ return true;
261
+ }
262
+ /** Window closing: stop every command still running. */
263
+ stopAll() {
264
+ for (const runId of [...this.runs.keys()])
265
+ this.cancel(runId);
266
+ }
267
+ }
268
+ //# sourceMappingURL=shell-runs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell-runs.js","sourceRoot":"","sources":["../../src/app-sidecar/shell-runs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,SAAS,EAAwC,MAAM,oBAAoB,CAAC;AAC9F,OA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,CAAC;gBACxB,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;YACvB,CAAC,EAAE,iBAAiB,CAAC,CAAC;QACxB,CAAC,CAAC,CAAC;QACH,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;IACtB,CAAC;IAED,+EAA+E;IAC/E,MAAM,CAAC,KAAa;QAClB,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAClC,IAAI,CAAC,IAAI;YAAE,OAAO,KAAK,CAAC;QACxB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG;YAAE,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;;YAC/C,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,wDAAwD;IACxD,OAAO;QACL,KAAK,MAAM,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAChE,CAAC;CACF"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * What the `!` picker offers: commands the user already ran in this project
3
+ * (most used first) and commands that fit the project (its git repo, package
4
+ * scripts, build tool) for one they haven't run yet.
5
+ */
6
+ export interface ShellSuggestion {
7
+ command: string;
8
+ /** Times the user ran it in this project; 0 for a project suggestion. */
9
+ count: number;
10
+ /** Where a never-run suggestion comes from, e.g. "package.json". */
11
+ source?: string;
12
+ }
13
+ interface HistoryEntry {
14
+ command: string;
15
+ count: number;
16
+ lastUsed: number;
17
+ }
18
+ /** Commands kept per project; the least used fall off. */
19
+ export declare const SHELL_HISTORY_MAX = 100;
20
+ export declare function shellHistoryFile(): string;
21
+ /** Most used first; ties go to the most recent, then alphabetical. */
22
+ export declare function rankHistory(entries: readonly HistoryEntry[]): HistoryEntry[];
23
+ export declare function loadShellHistory(cwd: string): Promise<HistoryEntry[]>;
24
+ /** Count one run of `command` in this project. */
25
+ export declare function recordShellCommand(cwd: string, command: string, now?: number): Promise<void>;
26
+ type PackageManager = "pnpm" | "yarn" | "bun" | "npm";
27
+ export declare function scriptCommands(scripts: Record<string, unknown>, pm: PackageManager): string[];
28
+ /** Commands that fit this project, best first. */
29
+ export declare function projectShellSuggestions(cwd: string): Promise<ShellSuggestion[]>;
30
+ /** History first (most used), then project commands not already in it. */
31
+ export declare function mergeShellSuggestions(history: readonly HistoryEntry[], project: readonly ShellSuggestion[]): ShellSuggestion[];
32
+ export declare function shellSuggestions(cwd: string): Promise<ShellSuggestion[]>;
33
+ export {};
@@ -0,0 +1,152 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { withFileLock } from "@kenkaiiii/gg-core";
5
+ import { atomicWrite } from "../core/session-storage.js";
6
+ import { projectModelKey } from "./app-settings.js";
7
+ /** Commands kept per project; the least used fall off. */
8
+ export const SHELL_HISTORY_MAX = 100;
9
+ const SUGGESTED_COMMAND_MAX = 200;
10
+ export function shellHistoryFile() {
11
+ return path.join(os.homedir(), ".gg", "shell-history.json");
12
+ }
13
+ function readEntries(value) {
14
+ if (!Array.isArray(value))
15
+ return [];
16
+ return value.flatMap((v) => {
17
+ if (typeof v !== "object" || v === null)
18
+ return [];
19
+ const { command, count, lastUsed } = v;
20
+ if (typeof command !== "string" || !command.trim())
21
+ return [];
22
+ return [
23
+ {
24
+ command,
25
+ count: typeof count === "number" && count > 0 ? Math.floor(count) : 1,
26
+ lastUsed: typeof lastUsed === "number" ? lastUsed : 0,
27
+ },
28
+ ];
29
+ });
30
+ }
31
+ async function loadHistoryFile() {
32
+ try {
33
+ const parsed = JSON.parse(await fs.readFile(shellHistoryFile(), "utf-8"));
34
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
35
+ return {};
36
+ return parsed;
37
+ }
38
+ catch {
39
+ return {};
40
+ }
41
+ }
42
+ /** Most used first; ties go to the most recent, then alphabetical. */
43
+ export function rankHistory(entries) {
44
+ return [...entries].sort((a, b) => b.count - a.count || b.lastUsed - a.lastUsed || a.command.localeCompare(b.command));
45
+ }
46
+ export async function loadShellHistory(cwd) {
47
+ const file = await loadHistoryFile();
48
+ return rankHistory(readEntries(file[projectModelKey(cwd)]));
49
+ }
50
+ /** Count one run of `command` in this project. */
51
+ export async function recordShellCommand(cwd, command, now = Date.now()) {
52
+ const key = projectModelKey(cwd);
53
+ const file = shellHistoryFile();
54
+ await fs.mkdir(path.dirname(file), { recursive: true });
55
+ await withFileLock(file, async () => {
56
+ const all = await loadHistoryFile();
57
+ const entries = readEntries(all[key]);
58
+ const existing = entries.find((e) => e.command === command);
59
+ if (existing) {
60
+ existing.count += 1;
61
+ existing.lastUsed = now;
62
+ }
63
+ else {
64
+ entries.push({ command, count: 1, lastUsed: now });
65
+ }
66
+ all[key] = rankHistory(entries).slice(0, SHELL_HISTORY_MAX);
67
+ await atomicWrite(file, JSON.stringify(all, null, 2));
68
+ });
69
+ }
70
+ async function exists(p) {
71
+ return fs.access(p).then(() => true, () => false);
72
+ }
73
+ async function packageManager(cwd) {
74
+ if (await exists(path.join(cwd, "pnpm-lock.yaml")))
75
+ return "pnpm";
76
+ if (await exists(path.join(cwd, "yarn.lock")))
77
+ return "yarn";
78
+ if ((await exists(path.join(cwd, "bun.lockb"))) || (await exists(path.join(cwd, "bun.lock")))) {
79
+ return "bun";
80
+ }
81
+ return "npm";
82
+ }
83
+ /** Scripts people check with most often come first. */
84
+ const SCRIPT_ORDER = ["test", "build", "lint", "check", "typecheck", "format"];
85
+ /** Servers and watchers never finish, so they make poor one-shot suggestions. */
86
+ const LONG_RUNNING = /^(dev|start|serve|preview|watch)(:|$)|:watch$/;
87
+ export function scriptCommands(scripts, pm) {
88
+ const names = Object.keys(scripts).filter((name) => typeof scripts[name] === "string" && !LONG_RUNNING.test(name));
89
+ const rank = (name) => {
90
+ const i = SCRIPT_ORDER.indexOf(name);
91
+ return i === -1 ? SCRIPT_ORDER.length : i;
92
+ };
93
+ names.sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
94
+ return names.slice(0, 6).map((name) => {
95
+ if (pm === "npm")
96
+ return name === "test" ? "npm test" : `npm run ${name}`;
97
+ return `${pm} ${name}`;
98
+ });
99
+ }
100
+ /** Commands that fit this project, best first. */
101
+ export async function projectShellSuggestions(cwd) {
102
+ const out = [];
103
+ const add = (source, commands) => {
104
+ for (const command of commands)
105
+ out.push({ command, count: 0, source });
106
+ };
107
+ if (await exists(path.join(cwd, ".git"))) {
108
+ add("git", ["git status", "git diff", "git log --oneline -10"]);
109
+ }
110
+ try {
111
+ const pkg = JSON.parse(await fs.readFile(path.join(cwd, "package.json"), "utf-8"));
112
+ if (pkg.scripts && typeof pkg.scripts === "object" && !Array.isArray(pkg.scripts)) {
113
+ add("package.json", scriptCommands(pkg.scripts, await packageManager(cwd)));
114
+ }
115
+ }
116
+ catch {
117
+ // No package.json, or one that doesn't parse: nothing to suggest from it.
118
+ }
119
+ if (await exists(path.join(cwd, "Cargo.toml"))) {
120
+ add("Cargo.toml", ["cargo check", "cargo test", "cargo build"]);
121
+ }
122
+ if (await exists(path.join(cwd, "go.mod")))
123
+ add("go.mod", ["go test ./...", "go build ./..."]);
124
+ if (await exists(path.join(cwd, "Makefile")))
125
+ add("Makefile", ["make"]);
126
+ if (out.length === 0)
127
+ add("folder", ["ls -la"]);
128
+ return out;
129
+ }
130
+ /** History first (most used), then project commands not already in it. */
131
+ export function mergeShellSuggestions(history, project) {
132
+ const seen = new Set();
133
+ const out = [];
134
+ for (const item of [
135
+ ...history.map((h) => ({ command: h.command, count: h.count })),
136
+ ...project,
137
+ ]) {
138
+ if (seen.has(item.command) || item.command.length > SUGGESTED_COMMAND_MAX)
139
+ continue;
140
+ seen.add(item.command);
141
+ out.push(item);
142
+ }
143
+ return out;
144
+ }
145
+ export async function shellSuggestions(cwd) {
146
+ const [history, project] = await Promise.all([
147
+ loadShellHistory(cwd).catch(() => []),
148
+ projectShellSuggestions(cwd).catch(() => []),
149
+ ]);
150
+ return mergeShellSuggestions(history, project);
151
+ }
152
+ //# sourceMappingURL=shell-suggestions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell-suggestions.js","sourceRoot":"","sources":["../../src/app-sidecar/shell-suggestions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAwBpD,0DAA0D;AAC1D,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AACrC,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC,MAAM,UAAU,gBAAgB;IAC9B,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,oBAAoB,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,WAAW,CAAC,KAAc;IACjC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACrC,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAkB,EAAE;QACzC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI;YAAE,OAAO,EAAE,CAAC;QACnD,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,GAAG,CAA4B,CAAC;QAClE,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;YAAE,OAAO,EAAE,CAAC;QAC9D,OAAO;YACL;gBACE,OAAO;gB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,CAAC,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;QAC/D,GAAG,OAAO;KACX,EAAE,CAAC;QACF,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,qBAAqB;YAAE,SAAS;QACpF,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,GAAW;IAChD,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QAC3C,gBAAgB,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC;QACrC,uBAAuB,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC;KAC7C,CAAC,CAAC;IACH,OAAO,qBAAqB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AACjD,CAAC"}
@@ -83,6 +83,8 @@ import { handleRunControlRoutes } from "./app-sidecar/run-control-routes.js";
83
83
  import { handleAuthRoutes } from "./app-sidecar/auth-routes.js";
84
84
  import { handleIntegrationRoutes } from "./app-sidecar/integration-routes.js";
85
85
  import { handleMcpRoutes } from "./app-sidecar/mcp-routes.js";
86
+ import { finishShellRun, handleShellRoutes } from "./app-sidecar/shell-routes.js";
87
+ import { ShellRunner } from "./app-sidecar/shell-runs.js";
86
88
  import { createHfPullManager } from "./app-sidecar/hf-pull-manager.js";
87
89
  import { keepAwake } from "./app-sidecar/keep-awake.js";
88
90
  import { createAutopilotRunner } from "./app-sidecar/autopilot-runner.js";
@@ -2140,7 +2142,12 @@ async function createSession(deps, opts) {
2140
2142
  });
2141
2143
  });
2142
2144
  }
2145
+ const shell = new ShellRunner({
2146
+ emit: (type, data) => broadcast(type, data),
2147
+ onEnd: (run) => finishShellRun(routeCtx, run),
2148
+ });
2143
2149
  const routeCtx = {
2150
+ shell,
2144
2151
  get session() {
2145
2152
  return session;
2146
2153
  },
@@ -2382,6 +2389,8 @@ async function createSession(deps, opts) {
2382
2389
  return;
2383
2390
  if (handleMcpRoutes(routeCtx, req, res, url, method))
2384
2391
  return;
2392
+ if (handleShellRoutes(routeCtx, req, res, url, method))
2393
+ return;
2385
2394
  json(res, 404, { error: "not found" });
2386
2395
  }
2387
2396
  async function dispose() {
@@ -2390,6 +2399,7 @@ async function createSession(deps, opts) {
2390
2399
  // started. Otherwise they keep streaming tokens and running tools on a
2391
2400
  // session that is being torn down.
2392
2401
  abortOwnedWork();
2402
+ shell.stopAll();
2393
2403
  idleWake?.dispose();
2394
2404
  cancelHfPull();
2395
2405
  releaseRunAwake?.();
@@ -2415,6 +2425,7 @@ async function createSession(deps, opts) {
2415
2425
  await session.dispose().catch(() => { });
2416
2426
  }
2417
2427
  function stopBackgroundProcesses() {
2428
+ shell.stopAll();
2418
2429
  session.stopBackgroundProcesses();
2419
2430
  kenSession?.stopBackgroundProcesses();
2420
2431
  kenAutoSession?.stopBackgroundProcesses();