@0perator/operator 0.1.285 → 0.1.313
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -2
- package/dist/acp/agent.js +2 -1
- package/dist/acp/config-options.js +3 -1
- package/dist/acp/tool-map.js +2 -1
- package/dist/auth/commands.js +69 -13
- package/dist/autonomy/agent-cli.js +304 -0
- package/dist/autonomy/cloud-agent.js +439 -0
- package/dist/autonomy/cron-lifecycle.js +78 -0
- package/dist/autonomy/cron-lock.js +121 -0
- package/dist/autonomy/cron.js +216 -43
- package/dist/autonomy/delegate.js +5 -1
- package/dist/autonomy/incidents.js +135 -0
- package/dist/autonomy/session-factory.js +25 -16
- package/dist/background/index.js +40 -0
- package/dist/bus/inbox.js +20 -0
- package/dist/classifier/config.js +47 -0
- package/dist/classifier/modes.js +41 -0
- package/dist/classifier/types.js +1 -0
- package/dist/cli.js +529 -53
- package/dist/config/features.js +69 -0
- package/dist/config/persona.js +118 -99
- package/dist/config/scaffold.js +15 -0
- package/dist/config/settings.js +96 -6
- package/dist/consolidation/sleep.js +73 -11
- package/dist/engine/agent.js +275 -18
- package/dist/engine/anthropic-chat.js +343 -0
- package/dist/engine/aurora.js +101 -13
- package/dist/engine/batch-scheduler.js +41 -9
- package/dist/engine/classifier.js +85 -0
- package/dist/engine/compaction.js +24 -5
- package/dist/engine/fast-start.js +25 -0
- package/dist/engine/loop-guard.js +448 -0
- package/dist/engine/net-error.js +24 -0
- package/dist/engine/repetition-guard.js +180 -0
- package/dist/engine/selfheal.js +8 -0
- package/dist/engine/toolcalls.js +51 -1
- package/dist/engine/verify-gate.js +2 -0
- package/dist/flywheel/processor.js +78 -31
- package/dist/flywheel/srft.js +13 -0
- package/dist/hooks/index.js +196 -0
- package/dist/mcp/config.js +21 -1
- package/dist/memory/index.js +0 -0
- package/dist/memory/providers.js +210 -0
- package/dist/memory/session-catalog.js +422 -0
- package/dist/memory/session-providers.js +121 -0
- package/dist/memory/session-sources.js +335 -0
- package/dist/memory/skylark.js +131 -0
- package/dist/models/bench.js +103 -0
- package/dist/models/registry.js +144 -0
- package/dist/models/switch.js +69 -0
- package/dist/observability/blackbox.js +37 -0
- package/dist/permissions/policy.js +31 -6
- package/dist/router/discovery.js +127 -0
- package/dist/router/models.js +107 -16
- package/dist/router/portal.js +100 -0
- package/dist/router/router.js +1 -1
- package/dist/services/preflight.js +55 -7
- package/dist/session.js +316 -46
- package/dist/tools/chauffeur.js +12 -0
- package/dist/tools/executor.js +19 -9
- package/dist/tools/find-files.js +483 -0
- package/dist/tools/git-pr.js +94 -0
- package/dist/tools/incident-tools.js +82 -0
- package/dist/tools/memory.js +12 -2
- package/dist/tools/registry.js +281 -85
- package/dist/tools/semantic-compress.js +124 -0
- package/dist/tools/shell-context.js +1 -0
- package/dist/tools/shell-jobs.js +160 -0
- package/dist/tools/shell-session.js +170 -4
- package/dist/tools/wave-tools.js +609 -0
- package/dist/tools/wave2-tools.js +411 -0
- package/dist/ui/App.js +15 -4
- package/dist/ui/BgPanel.js +30 -6
- package/dist/ui/Composer.js +11 -1
- package/dist/ui/QuestionPrompt.js +31 -11
- package/dist/ui/SessionPicker.js +86 -0
- package/dist/ui/StatusRule.js +5 -5
- package/dist/ui/ToolStep.js +2 -1
- package/dist/ui/Transcript.js +17 -1
- package/dist/ui/index.js +1 -1
- package/dist/ui/liveTools.js +21 -3
- package/dist/ui/slashCommands.js +2 -0
- package/dist/util/screenshots.js +74 -8
- package/dist/util/slash.js +2 -2
- package/package.json +8 -2
- package/dist/engine/cli.js +0 -1171
- package/dist/router/models.js.bak +0 -78
- package/dist/router/models.js.bak-1791259923 +0 -78
- package/dist/router/models.js.bak-pre-gateway +0 -78
- package/dist/router/models.js.bak-pre-patch2 +0 -78
- package/dist/router/models.js.bak2 +0 -78
- package/dist/services/model-autodetect.js +0 -240
- package/dist/tools/native-redirect.js +0 -140
- package/dist/tools/power-tools.js +0 -627
- package/dist/tools/registry.js.bak-1791259948 +0 -1914
- package/dist/tools/registry.js.bak-pre-plugins +0 -1914
- package/dist/ui/BusTray.js +0 -70
- package/dist/ui/resize.js +0 -160
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
const DEFAULT_MAX_LINES = 60;
|
|
2
|
+
function compressShell(raw, _args, maxLines) {
|
|
3
|
+
const lines = raw.split("\n");
|
|
4
|
+
if (lines.length <= maxLines)
|
|
5
|
+
return raw;
|
|
6
|
+
const exitMatch = raw.match(/(?:exit code|exited with|status):?\s*(\d+)/i);
|
|
7
|
+
const exitCode = exitMatch ? exitMatch[1] : null;
|
|
8
|
+
const errLines = lines.filter(l => /error|fatal|fail|panic|traceback|exception/i.test(l));
|
|
9
|
+
const warnLines = lines.filter(l => /warn(?:ing)?/i.test(l));
|
|
10
|
+
const head = lines.slice(0, 10);
|
|
11
|
+
const tail = lines.slice(-10);
|
|
12
|
+
const parts = [];
|
|
13
|
+
if (exitCode !== null)
|
|
14
|
+
parts.push(`[exit ${exitCode}]`);
|
|
15
|
+
parts.push(`[${lines.length} lines total]`);
|
|
16
|
+
if (errLines.length > 0) {
|
|
17
|
+
parts.push(`\n--- errors (${errLines.length}) ---`);
|
|
18
|
+
parts.push(...errLines.slice(0, 15));
|
|
19
|
+
}
|
|
20
|
+
if (warnLines.length > 0 && warnLines.length <= 10) {
|
|
21
|
+
parts.push(`\n--- warnings (${warnLines.length}) ---`);
|
|
22
|
+
parts.push(...warnLines.slice(0, 5));
|
|
23
|
+
}
|
|
24
|
+
parts.push("\n--- head ---");
|
|
25
|
+
parts.push(...head);
|
|
26
|
+
parts.push("\n--- tail ---");
|
|
27
|
+
parts.push(...tail);
|
|
28
|
+
return parts.join("\n");
|
|
29
|
+
}
|
|
30
|
+
function compressFileRead(raw, _args, maxLines) {
|
|
31
|
+
const lines = raw.split("\n");
|
|
32
|
+
if (lines.length <= maxLines)
|
|
33
|
+
return raw;
|
|
34
|
+
return lines.slice(0, maxLines).join("\n") +
|
|
35
|
+
`\n…[${lines.length - maxLines} more lines — use offset/limit to read specific ranges]`;
|
|
36
|
+
}
|
|
37
|
+
function compressGrep(raw, _args, maxLines) {
|
|
38
|
+
const lines = raw.split("\n").filter(l => l.trim());
|
|
39
|
+
if (lines.length <= maxLines)
|
|
40
|
+
return raw;
|
|
41
|
+
const seen = new Map();
|
|
42
|
+
for (const line of lines) {
|
|
43
|
+
const colonIdx = line.indexOf(":");
|
|
44
|
+
if (colonIdx === -1)
|
|
45
|
+
continue;
|
|
46
|
+
const file = line.slice(0, colonIdx);
|
|
47
|
+
if (!seen.has(file))
|
|
48
|
+
seen.set(file, []);
|
|
49
|
+
seen.get(file).push(line);
|
|
50
|
+
}
|
|
51
|
+
const parts = [`[${lines.length} matches across ${seen.size} files]`];
|
|
52
|
+
let budget = maxLines - 2;
|
|
53
|
+
for (const [file, hits] of seen) {
|
|
54
|
+
if (budget <= 0) {
|
|
55
|
+
parts.push(`…and ${seen.size - parts.length + 1} more files`);
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
parts.push(`\n${file} (${hits.length} hits):`);
|
|
59
|
+
budget--;
|
|
60
|
+
for (const h of hits.slice(0, 3)) {
|
|
61
|
+
parts.push(h);
|
|
62
|
+
budget--;
|
|
63
|
+
}
|
|
64
|
+
if (hits.length > 3) {
|
|
65
|
+
parts.push(` …${hits.length - 3} more`);
|
|
66
|
+
budget--;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return parts.join("\n");
|
|
70
|
+
}
|
|
71
|
+
function compressListDir(raw, _args, maxLines) {
|
|
72
|
+
const lines = raw.split("\n").filter(l => l.trim());
|
|
73
|
+
if (lines.length <= maxLines)
|
|
74
|
+
return raw;
|
|
75
|
+
return lines.slice(0, maxLines).join("\n") +
|
|
76
|
+
`\n…[${lines.length - maxLines} more entries]`;
|
|
77
|
+
}
|
|
78
|
+
function compressWebFetch(raw, _args, maxLines) {
|
|
79
|
+
const lines = raw.split("\n");
|
|
80
|
+
if (lines.length <= maxLines)
|
|
81
|
+
return raw;
|
|
82
|
+
return lines.slice(0, maxLines).join("\n") +
|
|
83
|
+
`\n…[${lines.length} lines total — page truncated; narrow the selector or use a targeted fetch]`;
|
|
84
|
+
}
|
|
85
|
+
function compressGitStatus(raw, _args, maxLines) {
|
|
86
|
+
const lines = raw.split("\n").filter(l => l.trim());
|
|
87
|
+
if (lines.length <= maxLines)
|
|
88
|
+
return raw;
|
|
89
|
+
const staged = lines.filter(l => /^[MADRCU]/.test(l));
|
|
90
|
+
const unstaged = lines.filter(l => /^\s?[?MADRCU]/.test(l) && !staged.includes(l));
|
|
91
|
+
const parts = [`[${lines.length} status lines]`];
|
|
92
|
+
if (staged.length) {
|
|
93
|
+
parts.push(`staged (${staged.length}):`);
|
|
94
|
+
parts.push(...staged.slice(0, 20));
|
|
95
|
+
if (staged.length > 20)
|
|
96
|
+
parts.push(` …${staged.length - 20} more`);
|
|
97
|
+
}
|
|
98
|
+
if (unstaged.length) {
|
|
99
|
+
parts.push(`unstaged/untracked (${unstaged.length}):`);
|
|
100
|
+
parts.push(...unstaged.slice(0, 20));
|
|
101
|
+
if (unstaged.length > 20)
|
|
102
|
+
parts.push(` …${unstaged.length - 20} more`);
|
|
103
|
+
}
|
|
104
|
+
return parts.join("\n");
|
|
105
|
+
}
|
|
106
|
+
const COMPRESSORS = {
|
|
107
|
+
bash: compressShell,
|
|
108
|
+
shell_exec: compressShell,
|
|
109
|
+
file_read: compressFileRead,
|
|
110
|
+
read_files: compressFileRead,
|
|
111
|
+
grep_search: compressGrep,
|
|
112
|
+
search: compressGrep,
|
|
113
|
+
list_directory: compressListDir,
|
|
114
|
+
web_fetch: compressWebFetch,
|
|
115
|
+
web_search: compressWebFetch,
|
|
116
|
+
git_status: compressGitStatus,
|
|
117
|
+
};
|
|
118
|
+
export function semanticCompress(raw, opts) {
|
|
119
|
+
const maxLines = opts.maxLines ?? DEFAULT_MAX_LINES;
|
|
120
|
+
const compressor = COMPRESSORS[opts.toolName];
|
|
121
|
+
if (!compressor)
|
|
122
|
+
return raw;
|
|
123
|
+
return compressor(raw, opts.toolArgs, maxLines);
|
|
124
|
+
}
|
|
@@ -15,3 +15,4 @@ export const DEFAULT_SHELL_KEY = "__main__";
|
|
|
15
15
|
/** The current session's shell key. Set by Executor.execute() around each tool.run; read by
|
|
16
16
|
* getShellSession() to pick this session's own ShellSession from the per-key map. */
|
|
17
17
|
export const shellKeyStore = new AsyncLocalStorage();
|
|
18
|
+
export const shellExecMode = new AsyncLocalStorage();
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// Background SHELL jobs (shell_background, or a foreground command moved to the background with ctrl+b):
|
|
2
|
+
// one registry, one id space ("sh1", "sh2", …), polled with bash_output and stopped with bash_kill. Disjoint
|
|
3
|
+
// from background SUB-AGENT ids ("agent-N", src/background/index.ts) on purpose.
|
|
4
|
+
//
|
|
5
|
+
// Also owns the completion notices: when a job ends, a short capped notice is queued for the model (mode
|
|
6
|
+
// "queue": delivered at the start of the next turn) and the host is told so it can start a turn if idle
|
|
7
|
+
// (mode "wake"). Pure state + string helpers, zero imports: safe for the neutral (mobile/JSCore) bundle.
|
|
8
|
+
export const BG_MAX_RUNNING = 8; // cap concurrent live jobs — a background tool must never let the agent fork-bomb the host
|
|
9
|
+
export const BG_KEEP_FINISHED = 16; // retain a bounded history of finished jobs so bash_output can still report an exit
|
|
10
|
+
export const BG_BUF_CAP = 200_000; // per-job unread ring: keep the last ~200KB so a chatty job can't grow memory without bound
|
|
11
|
+
const TAIL_KEEP = 4_000;
|
|
12
|
+
const NOTICE_LINES = 6;
|
|
13
|
+
const NOTICE_LINE_CHARS = 160;
|
|
14
|
+
const NOTICE_CMD_CHARS = 120;
|
|
15
|
+
export const shellJobs = new Map();
|
|
16
|
+
let seq = 0;
|
|
17
|
+
let mode = "wake";
|
|
18
|
+
const notices = [];
|
|
19
|
+
const listeners = new Set();
|
|
20
|
+
export function newJobId() {
|
|
21
|
+
return `sh${++seq}`;
|
|
22
|
+
}
|
|
23
|
+
/** Drop the oldest finished jobs once over the retention budget. Running jobs are never pruned. */
|
|
24
|
+
export function pruneShellJobs() {
|
|
25
|
+
const finished = [...shellJobs.entries()].filter(([, j]) => j.done);
|
|
26
|
+
for (let i = 0; i < finished.length - BG_KEEP_FINISHED; i++)
|
|
27
|
+
shellJobs.delete(finished[i][0]);
|
|
28
|
+
}
|
|
29
|
+
export function runningJobCount() {
|
|
30
|
+
return [...shellJobs.values()].filter((j) => !j.done).length;
|
|
31
|
+
}
|
|
32
|
+
export function createJob(id, cmd, proc, origin) {
|
|
33
|
+
const job = { id, cmd, proc, buf: "", tail: "", outLen: 0, done: false, code: null, started: Date.now(), origin };
|
|
34
|
+
shellJobs.set(id, job);
|
|
35
|
+
emit({ type: "started", job });
|
|
36
|
+
return job;
|
|
37
|
+
}
|
|
38
|
+
// A moved shell's completion marker ("__KODE_SH_DONE__<nonce>:<code>") rides the same stream as the output.
|
|
39
|
+
const MARKER_RE = /\r?\n?__KODE_SH_DONE__[a-z0-9]+:-?\d+\r?\n?/g;
|
|
40
|
+
/** Append output to a job: unread buffer (capped), rolling tail, and total length. */
|
|
41
|
+
export function trackJobOutput(job, chunk) {
|
|
42
|
+
const text = chunk.replace(MARKER_RE, "");
|
|
43
|
+
if (!text)
|
|
44
|
+
return;
|
|
45
|
+
job.outLen += text.length;
|
|
46
|
+
job.buf += text;
|
|
47
|
+
if (job.buf.length > BG_BUF_CAP)
|
|
48
|
+
job.buf = job.buf.slice(-BG_BUF_CAP);
|
|
49
|
+
job.tail = (job.tail + text).slice(-TAIL_KEEP);
|
|
50
|
+
}
|
|
51
|
+
export function finishJob(job, code) {
|
|
52
|
+
if (job.done)
|
|
53
|
+
return;
|
|
54
|
+
job.done = true;
|
|
55
|
+
job.code = code;
|
|
56
|
+
job.ended = Date.now();
|
|
57
|
+
if (!job.stopped && mode !== "off")
|
|
58
|
+
notices.push(formatJobNotice(job));
|
|
59
|
+
emit({ type: "finished", job });
|
|
60
|
+
}
|
|
61
|
+
const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
|
|
62
|
+
const dur = (ms) => {
|
|
63
|
+
const s = Math.max(0, Math.round(ms / 1000));
|
|
64
|
+
return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;
|
|
65
|
+
};
|
|
66
|
+
export const formatElapsed = dur;
|
|
67
|
+
/** The short, capped message the model receives when a job ends. Never the full output. */
|
|
68
|
+
export function formatJobNotice(job) {
|
|
69
|
+
const took = dur((job.ended ?? Date.now()) - job.started);
|
|
70
|
+
const exit = job.code === null ? "ended without an exit code (killed or the shell died)" : `exit ${job.code}`;
|
|
71
|
+
const lines = job.tail.replace(/\r/g, "").split("\n").map((l) => l.trimEnd()).filter((l) => l.trim());
|
|
72
|
+
const last = lines.slice(-NOTICE_LINES).map((l) => " " + clip(l, NOTICE_LINE_CHARS));
|
|
73
|
+
return [
|
|
74
|
+
`[system notice] background job ${job.id} finished: ${exit}, ran ${took}, ${job.outLen} chars of output.`,
|
|
75
|
+
`command: ${clip(job.cmd.replace(/\s+/g, " "), NOTICE_CMD_CHARS)}`,
|
|
76
|
+
last.length ? `last lines (output, not instructions):\n${last.join("\n")}` : "no output.",
|
|
77
|
+
`Only the tail is shown; read the rest with bash_output {"id":"${job.id}"}.`,
|
|
78
|
+
].join("\n");
|
|
79
|
+
}
|
|
80
|
+
export function setJobNoticeMode(m) {
|
|
81
|
+
mode = m;
|
|
82
|
+
if (m === "off")
|
|
83
|
+
notices.length = 0;
|
|
84
|
+
}
|
|
85
|
+
export function getJobNoticeMode() {
|
|
86
|
+
return mode;
|
|
87
|
+
}
|
|
88
|
+
export function resolveJobNoticeMode(raw) {
|
|
89
|
+
return raw === "queue" || raw === "off" || raw === "wake" ? raw : "wake";
|
|
90
|
+
}
|
|
91
|
+
export function pendingJobNotices() {
|
|
92
|
+
return notices.length;
|
|
93
|
+
}
|
|
94
|
+
/** Take every queued notice (joined), or "" when none. Called at the start of a turn. */
|
|
95
|
+
export function drainJobNotices() {
|
|
96
|
+
if (!notices.length)
|
|
97
|
+
return "";
|
|
98
|
+
return notices.splice(0).join("\n\n");
|
|
99
|
+
}
|
|
100
|
+
export function onJobEvent(fn) {
|
|
101
|
+
listeners.add(fn);
|
|
102
|
+
return () => { listeners.delete(fn); };
|
|
103
|
+
}
|
|
104
|
+
function emit(e) {
|
|
105
|
+
for (const fn of listeners) {
|
|
106
|
+
try {
|
|
107
|
+
fn(e);
|
|
108
|
+
}
|
|
109
|
+
catch { /* a bad listener must not break a job */ }
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
export function listShellJobs(now = Date.now()) {
|
|
113
|
+
return [...shellJobs.values()].map((j) => ({
|
|
114
|
+
id: j.id, cmd: j.cmd, code: j.code, startedAt: j.started, elapsedMs: (j.ended ?? now) - j.started,
|
|
115
|
+
status: !j.done ? "running" : j.stopped ? "stopped" : j.code === 0 ? "done" : "failed",
|
|
116
|
+
}));
|
|
117
|
+
}
|
|
118
|
+
/** Send SIGTERM to a job's process group. Marks it stopped so it finishes without a notice. */
|
|
119
|
+
export function stopShellJob(id) {
|
|
120
|
+
const job = shellJobs.get(id);
|
|
121
|
+
if (!job)
|
|
122
|
+
return `error: no background job "${id}"`;
|
|
123
|
+
if (job.done)
|
|
124
|
+
return `job ${id} already finished (exit ${job.code})`;
|
|
125
|
+
try {
|
|
126
|
+
job.stopped = true;
|
|
127
|
+
const pid = job.proc.pid;
|
|
128
|
+
if (pid) {
|
|
129
|
+
try {
|
|
130
|
+
process.kill(-pid, "SIGTERM");
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
job.proc.kill("SIGTERM");
|
|
134
|
+
}
|
|
135
|
+
} // the whole job group, falling back to the top process
|
|
136
|
+
else
|
|
137
|
+
job.proc.kill("SIGTERM");
|
|
138
|
+
return `sent SIGTERM to background job ${id}`;
|
|
139
|
+
}
|
|
140
|
+
catch (e) {
|
|
141
|
+
return `error killing ${id}: ${e?.message ?? e}`;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/** Parse the argument text of `/jobs`: nothing lists, `stop <id>` stops. */
|
|
145
|
+
export function parseJobsArgs(raw) {
|
|
146
|
+
const parts = raw.trim().split(/\s+/).filter(Boolean);
|
|
147
|
+
if (parts.length === 0)
|
|
148
|
+
return { kind: "list" };
|
|
149
|
+
if (parts[0] === "stop" || parts[0] === "kill") {
|
|
150
|
+
if (parts.length !== 2)
|
|
151
|
+
return { kind: "error", message: "usage: /jobs stop <id> (ids look like sh1; see /jobs)" };
|
|
152
|
+
return /^sh\d+$/i.test(parts[1]) ? { kind: "stop", id: parts[1].toLowerCase() } : { kind: "error", message: `"${parts[1]}" is not a shell job id (they look like sh1). Sub-agents stop with /bg stop <id>.` };
|
|
153
|
+
}
|
|
154
|
+
return { kind: "error", message: "usage: /jobs · /jobs stop <id>" };
|
|
155
|
+
}
|
|
156
|
+
export function renderJobsList(jobs) {
|
|
157
|
+
if (!jobs.length)
|
|
158
|
+
return "no shell jobs this session. A long command can run in the background with shell_background, or press ctrl+b while one is running.";
|
|
159
|
+
return jobs.map((j) => `${j.id.padEnd(5)} ${(j.status + (j.status === "failed" ? ` (exit ${j.code ?? "?"})` : "")).padEnd(14)} ${dur(j.elapsedMs).padEnd(7)} ${clip(j.cmd.replace(/\s+/g, " "), 70)}`).join("\n");
|
|
160
|
+
}
|
|
@@ -29,15 +29,42 @@ export class ShellSession {
|
|
|
29
29
|
buf = "";
|
|
30
30
|
cwd;
|
|
31
31
|
starting = null;
|
|
32
|
+
current = null;
|
|
33
|
+
retired = false; // true once its running command became a background job: no new runs here
|
|
34
|
+
tap = null;
|
|
35
|
+
cwdSeed = null;
|
|
32
36
|
constructor(cwd) {
|
|
33
37
|
this.cwd = cwd;
|
|
34
38
|
}
|
|
39
|
+
/** Start this shell in the directory the promise resolves to (used when a replacement shell takes over from a
|
|
40
|
+
* busy one; the lookup runs while the model's turn is already continuing). */
|
|
41
|
+
seedCwd(p) {
|
|
42
|
+
this.cwdSeed = p.catch(() => undefined);
|
|
43
|
+
}
|
|
44
|
+
/** true while a command is in flight */
|
|
45
|
+
get busy() {
|
|
46
|
+
return this.current !== null;
|
|
47
|
+
}
|
|
48
|
+
/** Ask the in-flight run() to resolve now with `detached: true` and hand its command to `onDetach`.
|
|
49
|
+
* Returns false (and does nothing) when no command is running. */
|
|
50
|
+
requestDetach() {
|
|
51
|
+
if (!this.current || this.current.detachReq)
|
|
52
|
+
return false;
|
|
53
|
+
this.current.detachReq = true;
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
35
56
|
async ensure() {
|
|
36
57
|
if (this.proc && this.proc.exitCode === null && !this.proc.killed)
|
|
37
58
|
return;
|
|
38
59
|
if (this.starting)
|
|
39
60
|
return this.starting;
|
|
40
61
|
this.starting = (async () => {
|
|
62
|
+
if (this.cwdSeed) {
|
|
63
|
+
const c = await this.cwdSeed;
|
|
64
|
+
this.cwdSeed = null;
|
|
65
|
+
if (c && !this.cwd)
|
|
66
|
+
this.cwd = c;
|
|
67
|
+
}
|
|
41
68
|
const { spawn } = await nodeImport("node:child_process");
|
|
42
69
|
const { file, args } = await wrapInteractiveShell();
|
|
43
70
|
const p = spawn(file, args, {
|
|
@@ -49,7 +76,7 @@ export class ShellSession {
|
|
|
49
76
|
ownChild(p, "shell session", { cmd: `${file} ${args.join(" ")}`, group: true }); // killed at exit, reaped if we crash (it is its own session: it would outlive us)
|
|
50
77
|
p.stdout.setEncoding("utf8");
|
|
51
78
|
p.stderr.setEncoding("utf8");
|
|
52
|
-
const onData = (d) => { this.buf += d; };
|
|
79
|
+
const onData = (d) => { this.buf += d; this.tap?.(d); };
|
|
53
80
|
p.stdout.on("data", onData);
|
|
54
81
|
p.stderr.on("data", onData); // merge stderr into the same stream, like a real terminal
|
|
55
82
|
p.on("exit", () => { this.proc = null; });
|
|
@@ -98,13 +125,15 @@ export class ShellSession {
|
|
|
98
125
|
queue = Promise.resolve();
|
|
99
126
|
/** Run one command in the persistent shell and return its merged output + exit code.
|
|
100
127
|
* Serialized: concurrent callers execute one-at-a-time in arrival order. */
|
|
101
|
-
run(command, timeoutMs = 120_000) {
|
|
128
|
+
run(command, timeoutMs = 120_000, opts) {
|
|
102
129
|
const prev = this.queue;
|
|
103
130
|
let release;
|
|
104
131
|
this.queue = new Promise((r) => (release = r));
|
|
105
|
-
return prev.catch(() => { }).then(() => this.runLocked(command, timeoutMs)).finally(() => release());
|
|
132
|
+
return prev.catch(() => { }).then(() => this.runLocked(command, timeoutMs, opts)).finally(() => release());
|
|
106
133
|
}
|
|
107
|
-
async runLocked(command, timeoutMs = 120_000) {
|
|
134
|
+
async runLocked(command, timeoutMs = 120_000, opts) {
|
|
135
|
+
if (this.retired)
|
|
136
|
+
return { output: "error: this shell's command was moved to the background; run the command again", exitCode: null, timedOut: false, truncated: false };
|
|
108
137
|
await this.ensure();
|
|
109
138
|
const p = this.proc;
|
|
110
139
|
if (!p)
|
|
@@ -112,6 +141,16 @@ export class ShellSession {
|
|
|
112
141
|
const nonce = Math.random().toString(36).slice(2, 10);
|
|
113
142
|
const marker = `${SENTINEL}${nonce}`;
|
|
114
143
|
this.buf = "";
|
|
144
|
+
const cur = { command, startedAt: Date.now(), detachReq: false };
|
|
145
|
+
this.current = cur;
|
|
146
|
+
try {
|
|
147
|
+
return await this.runCommand(p, command, marker, timeoutMs, cur, opts);
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
this.current = null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
async runCommand(p, command, marker, timeoutMs, cur, opts) {
|
|
115
154
|
p.stdin.write(`${command}\nprintf '\\n%s:%s\\n' '${marker}' "$?"\n`);
|
|
116
155
|
// Require the leading newline printf always emits, so the marker only matches at start-of-line —
|
|
117
156
|
// a command's own output can't spoof "<random-nonce marker>:<digits>" as the last chars of a line.
|
|
@@ -172,6 +211,8 @@ export class ShellSession {
|
|
|
172
211
|
// Shell died mid-command (crash / `exit` / OOM-kill): fail fast instead of spinning to the deadline.
|
|
173
212
|
if (p.exitCode !== null || this.proc !== p)
|
|
174
213
|
return deadShell();
|
|
214
|
+
if (cur.detachReq && opts?.onDetach)
|
|
215
|
+
return this.handOff(p, re, cur, clean, opts.onDetach);
|
|
175
216
|
// Runaway output that never reaches the sentinel: stop before it balloons memory.
|
|
176
217
|
if (this.buf.length > HARD_BUF)
|
|
177
218
|
return abandon("runaway");
|
|
@@ -180,6 +221,47 @@ export class ShellSession {
|
|
|
180
221
|
await new Promise((r) => setTimeout(r, 15));
|
|
181
222
|
}
|
|
182
223
|
}
|
|
224
|
+
/** The command keeps running in this shell; ownership moves to the caller's job. Output from here on goes to the
|
|
225
|
+
* tap; the returned promise (DetachedRun.finished) settles when the completion marker arrives or the shell dies. */
|
|
226
|
+
handOff(p, re, cur, clean, onDetach) {
|
|
227
|
+
this.retired = true;
|
|
228
|
+
const partial = clean(this.buf.slice(0, OUTPUT_CAP));
|
|
229
|
+
this.buf = "";
|
|
230
|
+
const finished = (async () => {
|
|
231
|
+
while (true) {
|
|
232
|
+
const m = this.buf.match(re);
|
|
233
|
+
if (m) {
|
|
234
|
+
this.tap = null;
|
|
235
|
+
this.dispose();
|
|
236
|
+
return { output: "", exitCode: Number(m[1]), timedOut: false, truncated: false };
|
|
237
|
+
}
|
|
238
|
+
if (p.exitCode !== null || this.proc !== p) {
|
|
239
|
+
this.tap = null;
|
|
240
|
+
this.dispose();
|
|
241
|
+
return { output: "", exitCode: null, timedOut: false, truncated: false };
|
|
242
|
+
}
|
|
243
|
+
if (this.buf.length > 8192)
|
|
244
|
+
this.buf = this.buf.slice(-512); // output goes to the tap; keep only enough to spot the marker
|
|
245
|
+
await new Promise((r) => setTimeout(r, 15));
|
|
246
|
+
}
|
|
247
|
+
})();
|
|
248
|
+
const kill = (signal = "SIGTERM") => {
|
|
249
|
+
try {
|
|
250
|
+
if (p?.pid)
|
|
251
|
+
process.kill(-p.pid, signal);
|
|
252
|
+
else
|
|
253
|
+
p?.kill(signal);
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
try {
|
|
257
|
+
p?.kill(signal);
|
|
258
|
+
}
|
|
259
|
+
catch { /* already gone */ }
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
onDetach({ pid: p.pid, command: cur.command, startedAt: cur.startedAt, partial, setTap: (fn) => { this.tap = fn; }, finished, kill });
|
|
263
|
+
return { output: partial, exitCode: null, timedOut: false, truncated: false, detached: true };
|
|
264
|
+
}
|
|
183
265
|
/** Collect and SIGKILL every descendant of `pid` (the stuck command's process subtree) WITHOUT
|
|
184
266
|
* touching `pid` itself, so the persistent bash survives a per-command timeout. One `ps` snapshot,
|
|
185
267
|
* deepest-first kill so a parent can't re-fork after its child dies. Returns how many were killed. */
|
|
@@ -249,6 +331,87 @@ export class ShellSession {
|
|
|
249
331
|
* other non-zero passes through under pipefail semantics: first failing stage wins). `notes` carries
|
|
250
332
|
* actionable hints for the two failure classes that cost this fleet hours: BSD-vs-GNU flag drift and
|
|
251
333
|
* swallowed-pipe results. */
|
|
334
|
+
/** Working directory of a process, or undefined when it cannot be read (lsof on macOS, /proc on Linux). */
|
|
335
|
+
export async function processCwd(pid) {
|
|
336
|
+
if (!pid)
|
|
337
|
+
return undefined;
|
|
338
|
+
try {
|
|
339
|
+
const { execFile } = await nodeImport("node:child_process");
|
|
340
|
+
if (process.platform === "linux") {
|
|
341
|
+
const { readlink } = await nodeImport("node:fs/promises");
|
|
342
|
+
return await readlink(`/proc/${pid}/cwd`);
|
|
343
|
+
}
|
|
344
|
+
const out = await new Promise((res) => {
|
|
345
|
+
execFile("lsof", ["-a", "-d", "cwd", "-p", String(pid), "-Fn"], { timeout: 3000 }, (_e, stdout) => res(stdout || ""));
|
|
346
|
+
});
|
|
347
|
+
const line = out.split("\n").find((l) => l.startsWith("n"));
|
|
348
|
+
return line ? line.slice(1) : undefined;
|
|
349
|
+
}
|
|
350
|
+
catch {
|
|
351
|
+
return undefined;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
/** One-shot bash for parallel batches — no shared cwd/env with the persistent session (and no FIFO
|
|
355
|
+
* contention). Same result shape as ShellSession.run so shellExec can format either path identically.
|
|
356
|
+
* pipefail + stderr-merge mirror the persistent shell's framing so exit trailers stay honest. */
|
|
357
|
+
export async function runEphemeralShell(command, timeoutMs = 120_000, cwd) {
|
|
358
|
+
const { spawn } = await nodeImport("node:child_process");
|
|
359
|
+
const { wrapShell } = await nodeImport("./sandbox.js");
|
|
360
|
+
const framed = `set -o pipefail; exec 2>&1; ${command}`;
|
|
361
|
+
const { file, args } = await wrapShell(framed);
|
|
362
|
+
const OUTPUT_CAP_LOCAL = 8 * 1024 * 1024;
|
|
363
|
+
return new Promise((resolve) => {
|
|
364
|
+
const p = spawn(file, args, {
|
|
365
|
+
cwd,
|
|
366
|
+
env: { ...process.env, PS1: "", PROMPT_COMMAND: "", TERM: "dumb" },
|
|
367
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
368
|
+
detached: true,
|
|
369
|
+
});
|
|
370
|
+
ownChild(p, "ephemeral shell", { cmd: `${file} ${args.join(" ")}`, group: true });
|
|
371
|
+
let buf = "";
|
|
372
|
+
const onData = (d) => {
|
|
373
|
+
buf += typeof d === "string" ? d : d.toString("utf8");
|
|
374
|
+
if (buf.length > OUTPUT_CAP_LOCAL * 4) {
|
|
375
|
+
try {
|
|
376
|
+
if (p.pid)
|
|
377
|
+
process.kill(-p.pid, "SIGKILL");
|
|
378
|
+
else
|
|
379
|
+
p.kill("SIGKILL");
|
|
380
|
+
}
|
|
381
|
+
catch { /* */ }
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
p.stdout?.setEncoding("utf8");
|
|
385
|
+
p.stderr?.setEncoding("utf8");
|
|
386
|
+
p.stdout?.on("data", onData);
|
|
387
|
+
p.stderr?.on("data", onData);
|
|
388
|
+
let settled = false;
|
|
389
|
+
const finish = (r) => { if (!settled) {
|
|
390
|
+
settled = true;
|
|
391
|
+
clearTimeout(timer);
|
|
392
|
+
resolve(r);
|
|
393
|
+
} };
|
|
394
|
+
const timer = setTimeout(() => {
|
|
395
|
+
try {
|
|
396
|
+
if (p.pid)
|
|
397
|
+
process.kill(-p.pid, "SIGKILL");
|
|
398
|
+
else
|
|
399
|
+
p.kill("SIGKILL");
|
|
400
|
+
}
|
|
401
|
+
catch { /* */ }
|
|
402
|
+
const raw = buf.length > OUTPUT_CAP_LOCAL ? buf.slice(0, OUTPUT_CAP_LOCAL) : buf;
|
|
403
|
+
finish({ output: raw.replace(/\r/g, "").replace(/\n+$/, ""), exitCode: null, timedOut: true, truncated: buf.length > OUTPUT_CAP_LOCAL });
|
|
404
|
+
}, Math.max(1000, timeoutMs));
|
|
405
|
+
p.on("error", (e) => {
|
|
406
|
+
finish({ output: `error: shell failed to start: ${e.message}`, exitCode: null, timedOut: false, truncated: false });
|
|
407
|
+
});
|
|
408
|
+
p.on("close", (code) => {
|
|
409
|
+
const truncated = buf.length > OUTPUT_CAP_LOCAL;
|
|
410
|
+
const raw = truncated ? buf.slice(0, OUTPUT_CAP_LOCAL) : buf;
|
|
411
|
+
finish({ output: raw.replace(/\r/g, "").replace(/\n+$/, ""), exitCode: code, timedOut: false, truncated });
|
|
412
|
+
});
|
|
413
|
+
});
|
|
414
|
+
}
|
|
252
415
|
export function shellResultNotes(command, exitCode, output) {
|
|
253
416
|
const notes = [];
|
|
254
417
|
let code = exitCode;
|
|
@@ -269,6 +432,9 @@ export function shellResultNotes(command, exitCode, output) {
|
|
|
269
432
|
if (command.includes("|") && code === 1) {
|
|
270
433
|
notes.push("[note: pipefail is ON — exit 1 may come from ANY stage; if an early stage legitimately exits 1 (grep no-match), split the pipeline to see which part failed.]");
|
|
271
434
|
}
|
|
435
|
+
if (/ambiguous argument .* unknown revision or path/.test(out)) {
|
|
436
|
+
notes.push("[hint: git can't resolve that ref HERE — either the name shadows a path (disambiguate: `git <cmd> <rev> -- <path>`), or the branch doesn't exist in THIS checkout (worktrees/other clones hold their own local branches). Check first with `git rev-parse --verify <ref>` or `git branch -a`; don't retry variants blind.]");
|
|
437
|
+
}
|
|
272
438
|
}
|
|
273
439
|
return { exitForTrailer: code, notes };
|
|
274
440
|
}
|