@0perator/operator 0.1.57 → 0.1.59
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/CHANGELOG.md +34 -0
- package/dist/auth/commands.js +1 -1
- package/dist/cli.js +39 -12
- package/dist/engine/agent.js +12 -4
- package/dist/engine/aurora.js +37 -6
- package/dist/tools/registry.js +65 -1
- package/dist/tools/shell-session.js +90 -10
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,40 @@ Operator is AXE's terminal coding agent (npm `@0perator/operator`), running on t
|
|
|
4
4
|
Newest first. Every release bumps `src/cli.tsx` VERSION + `package.json`, adds an entry here, and ships to
|
|
5
5
|
npm + both git remotes (memjar/kode, axetechnologies/kode). Test counts are the full suite at that release.
|
|
6
6
|
|
|
7
|
+
## 0.1.59 — 2026-09-22
|
|
8
|
+
Efficiency fixes for the failure the live screenshot caught: a filesystem-hunt task ran ~40 rounds of
|
|
9
|
+
`find ~/ | grep | grep`, hit the per-command timeout, killed + reset the persistent shell (losing cwd/env)
|
|
10
|
+
→ "shell failed to start" cascade → "[stopped after 40 tool rounds]" → "[turn error: fetch failed]". Three
|
|
11
|
+
blunt limits stacked and killed a task that WAS making progress. Four fixes remove them at the source:
|
|
12
|
+
- **Subshell-scoped timeout (`tools/shell-session.ts`).** A per-command timeout now SIGKILLs only the stuck
|
|
13
|
+
command's process subtree (bash's descendants) and leaves the persistent shell alive — bash reaps the job
|
|
14
|
+
and prints its pending sentinel, so `cd`/exported env SURVIVE a timeout. The shell is only respawned when
|
|
15
|
+
it's genuinely wedged (no sentinel returns AND nothing was killable / stdin no longer accepts writes). Kills
|
|
16
|
+
the "shell failed to start" cascade.
|
|
17
|
+
- **Progress-aware round cap (`engine/agent.ts`).** The loop no longer hard-stops at a fixed 40 rounds while
|
|
18
|
+
it's making progress. A `noProgressStreak` (reset by any tool batch that returns new results, via the
|
|
19
|
+
existing `batchProgressed`) ends the turn only on a genuine stall — N consecutive empty batches past the
|
|
20
|
+
soft budget — or an absolute 200-round safety ceiling. A turn that keeps finding results runs to completion.
|
|
21
|
+
- **`search` tool (ripgrep) + prompt steer (`tools/registry.ts`, `cli.tsx`).** New fast, scoped, .gitignore-aware
|
|
22
|
+
`search` tool (falls back to grep when rg is absent; `files_with_matches` for locate-before-read). The
|
|
23
|
+
"Finding things" system-prompt section now leads with it and forbids `find ~/ | grep` over the whole home
|
|
24
|
+
dir, with narrow-first + batch guidance. `grep_search` defers to `search`. Removes most timeouts at the source.
|
|
25
|
+
- **Transport-level fetch retry (`engine/aurora.ts`).** A transient pre-response network drop ("fetch failed")
|
|
26
|
+
is retried a couple times with short backoff at the fetch layer — before any SSE bytes stream, so a resend
|
|
27
|
+
can't duplicate output — instead of aborting the turn. Reuses `selfheal.ts` classify/backoff; aborts and
|
|
28
|
+
real HTTP errors are never retried here (the agent loop still owns those).
|
|
29
|
+
- Tests: 374/374 (9 new: shell timeout cwd/env survival, progress-cap extend + stall, fetch-retry + abort,
|
|
30
|
+
search tool content/glob/files-only/no-match). Live-verified end-to-end against Aurora :8097 — scoped
|
|
31
|
+
search (no whole-home sweep), no shell cascade, no 40-round hard-stop.
|
|
32
|
+
|
|
33
|
+
## 0.1.58 — 2026-09-22
|
|
34
|
+
- **`/login` runs the device-grant flow inline.** Typing `/login` (no arg) now requests a device code,
|
|
35
|
+
opens the browser to the AuthGate approval page with the 6-char code, polls until you approve, then
|
|
36
|
+
stores the token, sets it for immediate remote-engine use, and shows "✓ Authenticated as <you>" — no
|
|
37
|
+
dropping to the shell. `/login <token>` still pastes a PAT for headless sign-in. (Approval-page domain
|
|
38
|
+
is AuthGate-configured — OPERATOR_AUTH_VERIFICATION_URI.)
|
|
39
|
+
- Tests: 365/365.
|
|
40
|
+
|
|
7
41
|
## 0.1.57 — 2026-09-22
|
|
8
42
|
- **ReportLab PDF tools ship STANDARD.** report-mcp (build_pdf_report, build_pdf_from_markdown) is now
|
|
9
43
|
always injected — Operator can generate PDFs out of the box without opting into the full MCP fleet
|
package/dist/auth/commands.js
CHANGED
|
@@ -30,7 +30,7 @@ async function ask(question) {
|
|
|
30
30
|
// window actually appeared — the printed URL is always the real fallback). Crucially, a child-process
|
|
31
31
|
// spawn failure (e.g. ENOENT for a missing opener) surfaces ASYNCHRONOUSLY as an 'error' event, not as a
|
|
32
32
|
// throw — left unhandled it can crash the process, so we attach a no-op handler.
|
|
33
|
-
function openBrowser(url) {
|
|
33
|
+
export function openBrowser(url) {
|
|
34
34
|
const os = platform();
|
|
35
35
|
const cmd = os === "darwin" ? "open" : os === "win32" ? "cmd" : "xdg-open";
|
|
36
36
|
const args = os === "win32" ? ["/c", "start", "", url] : [url];
|
package/dist/cli.js
CHANGED
|
@@ -24,7 +24,7 @@ import { homedir, hostname } from "node:os";
|
|
|
24
24
|
import { createHash } from "node:crypto";
|
|
25
25
|
// RELEASE CHECKLIST (every bump): update this + package.json "version", ADD A CHANGELOG.md ENTRY
|
|
26
26
|
// (improvements / fixes / tests), run the suite, then publish to npm + push both remotes.
|
|
27
|
-
const VERSION = "0.1.
|
|
27
|
+
const VERSION = "0.1.59";
|
|
28
28
|
// operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
|
|
29
29
|
const settings = loadSettings();
|
|
30
30
|
// Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
|
|
@@ -235,14 +235,18 @@ const SYSTEM_PROMPT = (settings.systemPrompt ??
|
|
|
235
235
|
`in parallel and posts its result back here; keep working meanwhile. The user watches each sub-agent's ` +
|
|
236
236
|
`live tokens + time in the background panel. Don't delegate trivial work you can do inline, and don't ` +
|
|
237
237
|
`spawn many at once — they all share this one model.` +
|
|
238
|
-
`\n## Finding things\
|
|
239
|
-
`
|
|
240
|
-
`
|
|
241
|
-
|
|
242
|
-
`
|
|
243
|
-
`
|
|
244
|
-
|
|
245
|
-
`
|
|
238
|
+
`\n## Finding things\nTo search file CONTENTS (a symbol, a string, a config key), use the search tool ` +
|
|
239
|
+
`(ripgrep — fast, parallel, .gitignore-aware) scoped to a directory: search {"pattern":"…","path":"src"}, ` +
|
|
240
|
+
`and set files_with_matches to just locate the files before reading them. NEVER run ` +
|
|
241
|
+
`\`find ~/ -maxdepth N | grep | grep\` over the whole home directory — it is slow, hits the command ` +
|
|
242
|
+
`timeout, and can wedge the shell. Narrow FIRST: check the 2-3 most likely directories before any broad ` +
|
|
243
|
+
`sweep, and batch independent searches in ONE message so they run in parallel.\nWhen asked to find a ` +
|
|
244
|
+
`project or file by NAME that is NOT in the working directory: (1) run ls ~ to see the REAL top-level ` +
|
|
245
|
+
`folders (projects live in non-obvious ones — e.g. ~/Axwell, ~/.axe/repos, ~/Desktop — not just ` +
|
|
246
|
+
`~/Projects); (2) then a BOUNDED find scoped to a SPECIFIC directory with a generous timeout — ` +
|
|
247
|
+
`shell_exec {"command":"find ~/.axe/repos -maxdepth 3 -iname \\"*name*\\" 2>/dev/null | head -80",` +
|
|
248
|
+
`"timeout_ms":60000} — never an unbounded find over all of ~ or /. Widen the pattern if a repo may be ` +
|
|
249
|
+
`named differently. Only report not-found after this real search, and say exactly where you looked.` +
|
|
246
250
|
`\n## Scratchpad & handoff\nUse the scratchpad tool for private working notes, plans, and intermediate ` +
|
|
247
251
|
`results — think there, not in the workspace or your reply. Before you finish a substantial task, or ` +
|
|
248
252
|
`when you're running low on context, call session_handoff to record what you did, the state, and the ` +
|
|
@@ -792,10 +796,33 @@ function Root() {
|
|
|
792
796
|
break;
|
|
793
797
|
}
|
|
794
798
|
case "login": {
|
|
795
|
-
//
|
|
796
|
-
//
|
|
799
|
+
// No arg → run the device-grant flow inline (RFC 8628): request a code, open the browser to the
|
|
800
|
+
// approval page, poll until the human approves, then store the token + verify. A PAT can still be
|
|
801
|
+
// pasted (`/login <token>`) for a quick headless sign-in (handled below).
|
|
797
802
|
if (!arg) {
|
|
798
|
-
|
|
803
|
+
const { requestDeviceCode, awaitApproval } = await import("./auth/client.js");
|
|
804
|
+
const { openBrowser } = await import("./auth/commands.js");
|
|
805
|
+
const { saveCredentials } = await import("./auth/store.js");
|
|
806
|
+
const { setOperatorToken } = await import("./engine/aurora.js");
|
|
807
|
+
try {
|
|
808
|
+
const dc = await requestDeviceCode();
|
|
809
|
+
const url = dc.verification_uri_complete ?? dc.verification_uri;
|
|
810
|
+
const opened = openBrowser(url);
|
|
811
|
+
sys(`◔ sign-in: ${opened ? "opened" : "open"} ${dc.verification_uri} and approve with code \x1b[1m${dc.user_code}\x1b[0m — waiting…`);
|
|
812
|
+
const r = await awaitApproval(dc);
|
|
813
|
+
if (r.state === "approved") {
|
|
814
|
+
await saveCredentials({ token: r.token, user: r.account.external_id, issuedAt: Date.now() });
|
|
815
|
+
setOperatorToken(r.token); // so a remote engine call carries the fresh bearer immediately
|
|
816
|
+
setAuthUser(r.account.email ?? r.account.external_id);
|
|
817
|
+
sys(`✓ Authenticated as ${r.account.email ?? r.account.external_id}`);
|
|
818
|
+
}
|
|
819
|
+
else {
|
|
820
|
+
sys(`sign-in ${r.state} — /login to retry`);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
catch (e) {
|
|
824
|
+
sys(`sign-in failed: ${e instanceof Error ? e.message : String(e)} — /login to retry`);
|
|
825
|
+
}
|
|
799
826
|
break;
|
|
800
827
|
}
|
|
801
828
|
const { verifyToken } = await import("./auth/client.js");
|
package/dist/engine/agent.js
CHANGED
|
@@ -11,6 +11,7 @@ const MAX_SELF_HEAL_PER_TURN = 3;
|
|
|
11
11
|
const LOOP_GUARD_LIMIT = 3;
|
|
12
12
|
const CONTENT_LOOP_LIMIT = 3; // same substantial assistant narration this many rounds ⇒ stuck, even if tool args vary
|
|
13
13
|
const MAX_EMPTY_RETRIES = 1; // one nudge on an empty "dud" round before finalizing
|
|
14
|
+
const NO_PROGRESS_LIMIT = 6; // consecutive tool batches that return NOTHING new (past the soft budget) ⇒ genuine stall
|
|
14
15
|
/** Fingerprint of an assistant round's PROSE, for catching a model narrating in circles while its
|
|
15
16
|
* tools make no progress (the "12× Empty outputs" burn). Strips embedded tool-call JSON / code fences
|
|
16
17
|
* so the fingerprint is the PROSE, stable even when the (varying) call args live inside the content
|
|
@@ -133,10 +134,11 @@ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolSta
|
|
|
133
134
|
/** Runs one user turn to completion: compacts, loops model↔tools ≤maxRounds, self-heals, finalizes. */
|
|
134
135
|
export async function runTurn(userInput, conversation, opts) {
|
|
135
136
|
const softRounds = opts.maxRounds ?? 10;
|
|
136
|
-
const
|
|
137
|
+
const absCeiling = Math.max(softRounds + 1, opts.maxRoundsHard ?? 200); // absolute safety stop; progress-aware below
|
|
137
138
|
const callCounts = new Map();
|
|
138
139
|
const contentSigs = new Map(); // per-round prose fingerprints → the narration loop guard
|
|
139
140
|
let progressed = true; // did the PREVIOUS tool batch advance? gates the guard (progress clears it)
|
|
141
|
+
let noProgressStreak = 0; // consecutive tool batches that returned nothing new; reset by any real progress
|
|
140
142
|
let selfHealBudget = MAX_SELF_HEAL_PER_TURN;
|
|
141
143
|
conversation.user(userInput);
|
|
142
144
|
let rounds = 0;
|
|
@@ -146,10 +148,14 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
146
148
|
let promptTokensTotal = 0; // prompt tokens PREFILLED, summed across rounds
|
|
147
149
|
let promptMsTotal = 0; // prefill ms summed across rounds
|
|
148
150
|
let emptyRetries = 0; // reasoning models sometimes return a "dud" round (no content, no tool calls)
|
|
149
|
-
for (; rounds <
|
|
151
|
+
for (; rounds < absCeiling; rounds++) {
|
|
150
152
|
throwIfAborted(opts.signal); // stop before spending another round (covers compaction below too)
|
|
151
153
|
if (rounds === softRounds)
|
|
152
|
-
opts.onAutoContinue?.(rounds); // crossed the soft budget, still working — keep going
|
|
154
|
+
opts.onAutoContinue?.(rounds); // crossed the soft budget, still working — keep going while progressing
|
|
155
|
+
// Progress-aware stop: past the soft budget, end the turn only on a GENUINE stall (N consecutive
|
|
156
|
+
// tool batches that returned nothing new). A turn that keeps finding results runs to absCeiling.
|
|
157
|
+
if (rounds > softRounds && noProgressStreak >= NO_PROGRESS_LIMIT)
|
|
158
|
+
break;
|
|
153
159
|
let endpoint = opts.router.select(buildMessages(opts.systemPrompt, conversation.all), opts.toolSchemas);
|
|
154
160
|
opts.onRoute?.(endpoint);
|
|
155
161
|
// Endpoint-aware (SPEC §5): rebuild against whichever endpoint is current, since self-heal
|
|
@@ -260,6 +266,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
260
266
|
conversation.tool(tm.tool_call_id, tm.content);
|
|
261
267
|
toolCallTotal += response.toolCalls.length;
|
|
262
268
|
progressed = batchProgressed(toolMsgs);
|
|
269
|
+
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
263
270
|
continue;
|
|
264
271
|
}
|
|
265
272
|
// No structured tool_calls — check for text-encoded ones before treating this as final.
|
|
@@ -272,6 +279,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
272
279
|
conversation.tool(tm.tool_call_id, tm.content);
|
|
273
280
|
toolCallTotal += recovered.calls.length;
|
|
274
281
|
progressed = batchProgressed(toolMsgs);
|
|
282
|
+
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
275
283
|
continue;
|
|
276
284
|
}
|
|
277
285
|
const final = stripScratchpad(recovered.cleanedContent);
|
|
@@ -304,7 +312,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
304
312
|
conversation.assistant(answer);
|
|
305
313
|
return { content: answer, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
306
314
|
}
|
|
307
|
-
const timeoutMsg = `[stopped after ${
|
|
315
|
+
const timeoutMsg = `[stopped after ${rounds} tool rounds — the task may be unfinished; ask me to continue and I'll pick up where I left off]`;
|
|
308
316
|
conversation.assistant(timeoutMsg);
|
|
309
317
|
return { content: timeoutMsg, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
310
318
|
}
|
package/dist/engine/aurora.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
// selfheal.js only type-imports from here (erased at runtime), so importing its values back is not a
|
|
2
|
+
// runtime cycle. Reused to retry a transient transport drop at the fetch layer (see fetchChat).
|
|
3
|
+
import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
|
|
1
4
|
// A remote engine (api.axe.onl) fronts the model with gateway auth; a local :8097 does not. Only a
|
|
2
5
|
// non-loopback base needs (and should ever receive) the operator bearer, so a token is never sent to
|
|
3
6
|
// a local llama-server and the header is omitted entirely when there is nothing to send.
|
|
@@ -82,14 +85,42 @@ function requestBody(messages, o, stream) {
|
|
|
82
85
|
// NO repeat/presence/frequency penalty knobs — SPEC §1: they break tool-calling.
|
|
83
86
|
});
|
|
84
87
|
}
|
|
88
|
+
const FETCH_TRIES = 3; // a transient network drop ("fetch failed") gets a couple transport retries before
|
|
89
|
+
// it surfaces to the turn; the agent loop then does its own HTTP-level failover.
|
|
90
|
+
/** POST the chat request, retrying ONLY a pre-response transport failure (connection reset / DNS /
|
|
91
|
+
* "fetch failed") — no SSE bytes have streamed yet, so a resend is safe and can't duplicate output.
|
|
92
|
+
* An HTTP response (even 4xx/5xx) RESOLVES the fetch and is returned as-is for the caller to classify;
|
|
93
|
+
* an abort (signal fired) is never retried. */
|
|
94
|
+
async function fetchChat(o, body) {
|
|
95
|
+
let lastErr;
|
|
96
|
+
for (let attempt = 0; attempt < FETCH_TRIES; attempt++) {
|
|
97
|
+
try {
|
|
98
|
+
return await fetch(`${o.base}/v1/chat/completions`, {
|
|
99
|
+
method: "POST",
|
|
100
|
+
headers: { "Content-Type": "application/json", ...authHeaders(o) },
|
|
101
|
+
body,
|
|
102
|
+
signal: o.signal, // SPEC §9 interrupt parity: tears down the in-flight stream on abort, not at the next loop boundary
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
// Interrupt (AbortError / signal fired) is intentional — never retry it.
|
|
107
|
+
if (o.signal?.aborted || (e instanceof Error && (e.name === "AbortError" || e.name === "TimeoutError")))
|
|
108
|
+
throw e;
|
|
109
|
+
// Only a transient transport error is retryable; a thrown fetch never carries an HTTP status, so
|
|
110
|
+
// classifyFailure returns "transient" here — but gate on it so any non-transient throw fails fast.
|
|
111
|
+
if (classifyFailure(e) !== "transient" || attempt >= FETCH_TRIES - 1) {
|
|
112
|
+
lastErr = e;
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
lastErr = e;
|
|
116
|
+
await sleep(backoffMs(attempt, e), o.signal, () => (e instanceof Error ? e : new Error(String(e))));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
throw lastErr;
|
|
120
|
+
}
|
|
85
121
|
/** Shared SSE parse loop. Yields each `data:` line's `choices[0].delta`, raw. */
|
|
86
122
|
async function* streamDeltas(messages, o) {
|
|
87
|
-
const res = await
|
|
88
|
-
method: "POST",
|
|
89
|
-
headers: { "Content-Type": "application/json", ...authHeaders(o) },
|
|
90
|
-
body: requestBody(messages, o, true),
|
|
91
|
-
signal: o.signal, // SPEC §9 interrupt parity: tears down the in-flight stream on abort, not at the next loop boundary
|
|
92
|
-
});
|
|
123
|
+
const res = await fetchChat(o, requestBody(messages, o, true));
|
|
93
124
|
if (!res.ok || !res.body) {
|
|
94
125
|
let detail = "";
|
|
95
126
|
try {
|
package/dist/tools/registry.js
CHANGED
|
@@ -243,6 +243,59 @@ function capMatches(stdout) {
|
|
|
243
243
|
out += `\n…[${lines.length - GREP_MAXLINES} more matching lines — narrow the pattern or pass a path/glob]`;
|
|
244
244
|
return out;
|
|
245
245
|
}
|
|
246
|
+
// Fast search backed by ripgrep — parallel, .gitignore-aware, skips binaries/hidden files, so it stays
|
|
247
|
+
// scoped and quick instead of `find ~/ | grep | grep` over the whole home tree. Falls back to grep with
|
|
248
|
+
// the SAME scoping + caps when rg isn't installed, so the tool always works. `files_with_matches` returns
|
|
249
|
+
// just the matching file paths (rg -l) — the cheap way to locate before reading.
|
|
250
|
+
async function ripgrepSearch(args) {
|
|
251
|
+
const pattern = str(args.pattern);
|
|
252
|
+
const path = expandPath(str(args.path, "."));
|
|
253
|
+
if (!pattern)
|
|
254
|
+
return "error: no pattern given";
|
|
255
|
+
const filesOnly = !!args.files_with_matches;
|
|
256
|
+
const glob = args.glob ? str(args.glob) : "";
|
|
257
|
+
const grepFallback = async () => {
|
|
258
|
+
// rg absent — same intent via grep: recursive, skip .git/node_modules, honor glob + files-only.
|
|
259
|
+
const gflags = ["-rns", "-I", "--exclude-dir=.git", "--exclude-dir=node_modules", "--exclude=.operator-session.json"];
|
|
260
|
+
if (filesOnly)
|
|
261
|
+
gflags.push("-l");
|
|
262
|
+
if (glob)
|
|
263
|
+
gflags.push(`--include=${glob}`);
|
|
264
|
+
try {
|
|
265
|
+
const { stdout } = await pexecFile("grep", [...gflags, "-E", pattern, path], { maxBuffer: 10 * 1024 * 1024, timeout: 20_000, killSignal: "SIGKILL" });
|
|
266
|
+
return capMatches(stdout);
|
|
267
|
+
}
|
|
268
|
+
catch (ge) {
|
|
269
|
+
if (ge.stdout && String(ge.stdout).trim())
|
|
270
|
+
return capMatches(String(ge.stdout));
|
|
271
|
+
if (ge.code === 1)
|
|
272
|
+
return "(no matches)";
|
|
273
|
+
if (ge.killed)
|
|
274
|
+
return "(search timed out — narrow the path)";
|
|
275
|
+
return `error: ${ge.stderr || ge.message}`;
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
const rgArgs = ["--color=never", "--no-messages", "--max-columns=500", "--max-filesize=5M"];
|
|
279
|
+
rgArgs.push(filesOnly ? "-l" : "-n");
|
|
280
|
+
if (glob)
|
|
281
|
+
rgArgs.push("-g", glob);
|
|
282
|
+
rgArgs.push("-e", pattern, path);
|
|
283
|
+
try {
|
|
284
|
+
const { stdout } = await pexecFile("rg", rgArgs, { maxBuffer: 10 * 1024 * 1024, timeout: 20_000, killSignal: "SIGKILL" });
|
|
285
|
+
return capMatches(stdout);
|
|
286
|
+
}
|
|
287
|
+
catch (e) {
|
|
288
|
+
if (e.code === "ENOENT")
|
|
289
|
+
return grepFallback(); // ripgrep not installed → grep
|
|
290
|
+
if (e.stdout && String(e.stdout).trim())
|
|
291
|
+
return capMatches(String(e.stdout));
|
|
292
|
+
if (e.code === 1)
|
|
293
|
+
return "(no matches)";
|
|
294
|
+
if (e.killed)
|
|
295
|
+
return "(search timed out — narrow the path)";
|
|
296
|
+
return `error: ${e.stderr || e.message}`;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
246
299
|
const LIST_DIR_MAX_ENTRIES = 1000; // a directory with 100k entries (node_modules, a data dump) should
|
|
247
300
|
// not dump one line each into context — this is a fan-out cap, independent of the executor's byte cap.
|
|
248
301
|
async function listDirectory(args) {
|
|
@@ -609,12 +662,23 @@ const TOOLS = [
|
|
|
609
662
|
},
|
|
610
663
|
{
|
|
611
664
|
name: "grep_search", safe: true,
|
|
612
|
-
description: "Recursively grep for a regex pattern under a path.",
|
|
665
|
+
description: "Recursively grep for a regex pattern under a path. Prefer the `search` tool for most searches — it is faster (ripgrep, parallel) and .gitignore-aware; use grep_search only when you specifically need plain grep semantics.",
|
|
613
666
|
parameters: { type: "object", properties: {
|
|
614
667
|
pattern: { type: "string" }, path: { type: "string" }, glob: { type: "string" },
|
|
615
668
|
}, required: ["pattern"] },
|
|
616
669
|
run: grepSearch,
|
|
617
670
|
},
|
|
671
|
+
{
|
|
672
|
+
name: "search", safe: true,
|
|
673
|
+
description: "Fast code/text search (ripgrep: parallel, .gitignore-aware, skips binaries). ALWAYS prefer this over `find … | grep` for locating things. Scope it to a directory with `path` (default: current dir) — never search the whole home directory. `glob` filters filenames (e.g. \"*.ts\"). Set `files_with_matches` to get just the matching file paths (cheap — locate before you read).",
|
|
674
|
+
parameters: { type: "object", properties: {
|
|
675
|
+
pattern: { type: "string", description: "regex to search for" },
|
|
676
|
+
path: { type: "string", description: "directory to scope the search to; default is the current dir" },
|
|
677
|
+
glob: { type: "string", description: "filename glob filter, e.g. \"*.ts\"" },
|
|
678
|
+
files_with_matches: { type: "boolean", description: "return only the paths of files that match" },
|
|
679
|
+
}, required: ["pattern"] },
|
|
680
|
+
run: ripgrepSearch,
|
|
681
|
+
},
|
|
618
682
|
{
|
|
619
683
|
name: "list_directory", safe: true,
|
|
620
684
|
description: "List entries in a directory.",
|
|
@@ -7,8 +7,10 @@
|
|
|
7
7
|
// Framing: each command is written to the shell's stdin followed by a sentinel that prints a
|
|
8
8
|
// unique nonce and `$?`. We read stdout+stderr (merged, like a terminal) until the sentinel
|
|
9
9
|
// line appears; everything before it is the command's output, and the nonce line carries the
|
|
10
|
-
// exit code. On a per-command timeout we
|
|
11
|
-
//
|
|
10
|
+
// exit code. On a per-command timeout we SIGKILL only the stuck command (bash's descendant
|
|
11
|
+
// processes) and leave the persistent bash itself alive, so `cd`/exported env survive a timeout;
|
|
12
|
+
// bash then reaps the killed job and prints the pending sentinel. Only if the sentinel never
|
|
13
|
+
// returns AND bash is genuinely wedged do we respawn the shell (the rare cwd/env-loss case).
|
|
12
14
|
//
|
|
13
15
|
// node-only; imported lazily from the tool layer so the neutral (mobile) bundle never pulls it.
|
|
14
16
|
import { wrapInteractiveShell } from "./sandbox.js";
|
|
@@ -108,31 +110,109 @@ export class ShellSession {
|
|
|
108
110
|
const re = new RegExp(`\\n${marker}:(-?\\d+)\\r?\\n`);
|
|
109
111
|
const HARD_BUF = OUTPUT_CAP * 4; // bound memory even if the sentinel never arrives (e.g. `yes`)
|
|
110
112
|
const deadline = Date.now() + Math.max(1000, timeoutMs);
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
+
const clean = (out) => out.replace(/\r/g, "").replace(/\n+$/, "");
|
|
114
|
+
const cap = (raw) => (raw.length > OUTPUT_CAP ? raw.slice(0, OUTPUT_CAP) : raw);
|
|
115
|
+
// Dead-shell exit: bash crashed / `exit` / OOM-kill. It's already gone; drop the handle so the
|
|
116
|
+
// next call respawns. cwd/env are lost here, but that's an actual shell death, not a timeout.
|
|
117
|
+
const deadShell = () => {
|
|
118
|
+
this.proc = null;
|
|
119
|
+
const raw = this.buf.slice(0, OUTPUT_CAP);
|
|
120
|
+
this.buf = "";
|
|
121
|
+
return { output: clean(raw), exitCode: null, timedOut: false, truncated: false };
|
|
122
|
+
};
|
|
123
|
+
// Per-command timeout / runaway: abandon ONLY the stuck command by SIGKILLing bash's descendants,
|
|
124
|
+
// then let bash reap them and print the pending sentinel — bash (and its cwd/env) survives. Only
|
|
125
|
+
// if the sentinel never comes back AND bash is genuinely wedged do we respawn (cwd/env-loss case).
|
|
126
|
+
const abandon = async (reason) => {
|
|
127
|
+
const killed = await this.killDescendants(p.pid);
|
|
128
|
+
const grace = Date.now() + 2000;
|
|
129
|
+
while (Date.now() < grace) {
|
|
130
|
+
const m = this.buf.match(re);
|
|
131
|
+
if (m) { // bash recovered on its own — shell (cwd/env) preserved
|
|
132
|
+
const raw = cap(this.buf.slice(0, m.index));
|
|
133
|
+
this.buf = "";
|
|
134
|
+
return { output: clean(raw), exitCode: Number(m[1]), timedOut: reason === "timeout", truncated: reason === "runaway" || raw.length >= OUTPUT_CAP };
|
|
135
|
+
}
|
|
136
|
+
if (p.exitCode !== null || this.proc !== p)
|
|
137
|
+
break; // bash itself died
|
|
138
|
+
await new Promise((r) => setTimeout(r, 15));
|
|
139
|
+
}
|
|
140
|
+
// No sentinel within grace. Wedged if bash died, or its stdin no longer accepts writes, or
|
|
141
|
+
// there was no external child to kill (the hang is inside bash itself, e.g. a builtin spin).
|
|
142
|
+
let wedged = p.exitCode !== null || this.proc !== p || killed === 0;
|
|
143
|
+
try {
|
|
144
|
+
p.stdin.write("\n");
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
wedged = true;
|
|
148
|
+
}
|
|
149
|
+
if (wedged) {
|
|
113
150
|
this.killShell(p);
|
|
114
151
|
this.proc = null;
|
|
115
152
|
}
|
|
153
|
+
const raw = this.buf.slice(0, OUTPUT_CAP);
|
|
116
154
|
this.buf = "";
|
|
117
|
-
return { output:
|
|
155
|
+
return { output: clean(raw), exitCode: null, timedOut: reason === "timeout", truncated: reason === "runaway" };
|
|
118
156
|
};
|
|
119
157
|
while (true) {
|
|
120
158
|
const m = this.buf.match(re);
|
|
121
159
|
if (m) {
|
|
122
|
-
const raw = this.buf.slice(0, m.index);
|
|
123
|
-
|
|
160
|
+
const raw = cap(this.buf.slice(0, m.index));
|
|
161
|
+
this.buf = "";
|
|
162
|
+
return { output: clean(raw), exitCode: Number(m[1]), timedOut: false, truncated: raw.length >= OUTPUT_CAP };
|
|
124
163
|
}
|
|
125
164
|
// Shell died mid-command (crash / `exit` / OOM-kill): fail fast instead of spinning to the deadline.
|
|
126
165
|
if (p.exitCode !== null || this.proc !== p)
|
|
127
|
-
return
|
|
166
|
+
return deadShell();
|
|
128
167
|
// Runaway output that never reaches the sentinel: stop before it balloons memory.
|
|
129
168
|
if (this.buf.length > HARD_BUF)
|
|
130
|
-
return
|
|
169
|
+
return abandon("runaway");
|
|
131
170
|
if (Date.now() > deadline)
|
|
132
|
-
return
|
|
171
|
+
return abandon("timeout");
|
|
133
172
|
await new Promise((r) => setTimeout(r, 15));
|
|
134
173
|
}
|
|
135
174
|
}
|
|
175
|
+
/** Collect and SIGKILL every descendant of `pid` (the stuck command's process subtree) WITHOUT
|
|
176
|
+
* touching `pid` itself, so the persistent bash survives a per-command timeout. One `ps` snapshot,
|
|
177
|
+
* deepest-first kill so a parent can't re-fork after its child dies. Returns how many were killed. */
|
|
178
|
+
async killDescendants(pid) {
|
|
179
|
+
try {
|
|
180
|
+
const { execFile } = await nodeImport("node:child_process");
|
|
181
|
+
const out = await new Promise((res) => {
|
|
182
|
+
execFile("ps", ["-Ao", "pid=,ppid="], { maxBuffer: 8 * 1024 * 1024 }, (_e, stdout) => res(stdout || ""));
|
|
183
|
+
});
|
|
184
|
+
const kids = new Map();
|
|
185
|
+
for (const line of out.split("\n")) {
|
|
186
|
+
const mm = line.trim().match(/^(\d+)\s+(\d+)$/);
|
|
187
|
+
if (!mm)
|
|
188
|
+
continue;
|
|
189
|
+
const child = Number(mm[1]), parent = Number(mm[2]);
|
|
190
|
+
const arr = kids.get(parent);
|
|
191
|
+
if (arr)
|
|
192
|
+
arr.push(child);
|
|
193
|
+
else
|
|
194
|
+
kids.set(parent, [child]);
|
|
195
|
+
}
|
|
196
|
+
const victims = [];
|
|
197
|
+
const stack = [pid];
|
|
198
|
+
while (stack.length) {
|
|
199
|
+
for (const c of kids.get(stack.pop()) ?? []) {
|
|
200
|
+
victims.push(c);
|
|
201
|
+
stack.push(c);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
for (const v of victims.reverse()) {
|
|
205
|
+
try {
|
|
206
|
+
process.kill(v, "SIGKILL");
|
|
207
|
+
}
|
|
208
|
+
catch { /* already gone */ }
|
|
209
|
+
}
|
|
210
|
+
return victims.length;
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
return 0;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
136
216
|
/** SIGKILL the shell AND its process group (spawned detached), so backgrounded grandchildren (`&` jobs)
|
|
137
217
|
* don't survive as orphans. Falls back to a plain kill if the group signal fails. */
|
|
138
218
|
killShell(p) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0perator/operator",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.59",
|
|
4
4
|
"description": "Operator (KODE) — TypeScript + Ink terminal coding agent. Full-frame render, single-engine core shared across CLI/web/mobile; runs against a local Aurora model.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|