@0perator/operator 0.1.58 → 0.1.60

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 CHANGED
@@ -4,6 +4,49 @@ 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.60 — 2026-09-22
8
+ - **`http_request` tool (capability #5).** A real HTTP client beyond `web_fetch`'s GET-and-scrape: any method
9
+ (GET/POST/PUT/PATCH/DELETE/HEAD), custom headers, a JSON (`json`) or raw (`body`) payload, bearer/basic auth,
10
+ redirects, timeout. Returns status + response headers + the capped body verbatim (no HTML stripping) — for
11
+ authenticated REST/GraphQL/webhook calls. safe:false (can mutate → gated when the policy is on).
12
+ - **`file_upload` tool (capability #7).** The push side Operator lacked: POST multipart/form-data (default,
13
+ `field` names the part) or PUT raw bytes (S3 presigned-PUT style), same bearer/basic auth as http_request.
14
+ safe:false (exfiltrates a file → gated; confirm the destination). btoa (not node Buffer) keeps both tools
15
+ neutral-bundle-safe; resolved auth secrets are never echoed into the result.
16
+ - **Drivable operating mode across host + web** (folds in the landed remote-control commit): `/mode
17
+ [plan|manual|auto]` (autonomous→auto, gated→manual); single `applyMode()` path for Shift+Tab / /mode / /plan
18
+ / follower frame keeps policy + plan flag + badge + capabilities in lockstep; `RemoteCapabilities.mode` is the
19
+ live 3-state ("gated" back-compat alias); "mode" in REMOTE_SAFE_COMMANDS. Web (0perator.co/remote) drives it.
20
+ - Capability roadmap (`docs/capabilities/`): #5 and #7 now SHIPPED; cloud/docker/ssh/monitoring/media-processing
21
+ are reachable via the fleet MCP gateway (`mcp:true`); webhook receiver (#8) + super daemon (#9) remain to build.
22
+ - Tests: 379/379 (5 new: http_request GET/POST-json/basic-auth, file_upload multipart + raw PUT).
23
+
24
+ ## 0.1.59 — 2026-09-22
25
+ Efficiency fixes for the failure the live screenshot caught: a filesystem-hunt task ran ~40 rounds of
26
+ `find ~/ | grep | grep`, hit the per-command timeout, killed + reset the persistent shell (losing cwd/env)
27
+ → "shell failed to start" cascade → "[stopped after 40 tool rounds]" → "[turn error: fetch failed]". Three
28
+ blunt limits stacked and killed a task that WAS making progress. Four fixes remove them at the source:
29
+ - **Subshell-scoped timeout (`tools/shell-session.ts`).** A per-command timeout now SIGKILLs only the stuck
30
+ command's process subtree (bash's descendants) and leaves the persistent shell alive — bash reaps the job
31
+ and prints its pending sentinel, so `cd`/exported env SURVIVE a timeout. The shell is only respawned when
32
+ it's genuinely wedged (no sentinel returns AND nothing was killable / stdin no longer accepts writes). Kills
33
+ the "shell failed to start" cascade.
34
+ - **Progress-aware round cap (`engine/agent.ts`).** The loop no longer hard-stops at a fixed 40 rounds while
35
+ it's making progress. A `noProgressStreak` (reset by any tool batch that returns new results, via the
36
+ existing `batchProgressed`) ends the turn only on a genuine stall — N consecutive empty batches past the
37
+ soft budget — or an absolute 200-round safety ceiling. A turn that keeps finding results runs to completion.
38
+ - **`search` tool (ripgrep) + prompt steer (`tools/registry.ts`, `cli.tsx`).** New fast, scoped, .gitignore-aware
39
+ `search` tool (falls back to grep when rg is absent; `files_with_matches` for locate-before-read). The
40
+ "Finding things" system-prompt section now leads with it and forbids `find ~/ | grep` over the whole home
41
+ dir, with narrow-first + batch guidance. `grep_search` defers to `search`. Removes most timeouts at the source.
42
+ - **Transport-level fetch retry (`engine/aurora.ts`).** A transient pre-response network drop ("fetch failed")
43
+ is retried a couple times with short backoff at the fetch layer — before any SSE bytes stream, so a resend
44
+ can't duplicate output — instead of aborting the turn. Reuses `selfheal.ts` classify/backoff; aborts and
45
+ real HTTP errors are never retried here (the agent loop still owns those).
46
+ - Tests: 374/374 (9 new: shell timeout cwd/env survival, progress-cap extend + stall, fetch-retry + abort,
47
+ search tool content/glob/files-only/no-match). Live-verified end-to-end against Aurora :8097 — scoped
48
+ search (no whole-home sweep), no shell cascade, no 40-round hard-stop.
49
+
7
50
  ## 0.1.58 — 2026-09-22
8
51
  - **`/login` runs the device-grant flow inline.** Typing `/login` (no arg) now requests a device code,
9
52
  opens the browser to the AuthGate approval page with the 6-char code, polls until you approve, then
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.58";
27
+ const VERSION = "0.1.60";
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\nWhen asked to find files, work, a project, or past output NOT in the current ` +
239
- `working directory, do NOT give up after a workspace grep/memory_search. Actually find it: (1) run ` +
240
- `ls ~ first to see the REAL top-level folders — projects often live in non-obvious ones (e.g. ~/Axwell), ` +
241
- `not just ~/Projects; (2) then search with a BOUNDED, fast command and a GENEROUS timeout so it is ` +
242
- `never killed mid-search — shell_exec {"command":"find ~ -maxdepth 4 -iname \\"*name*\\" 2>/dev/null | ` +
243
- `head -80","timeout_ms":60000}. Do NOT use an unbounded find / (too slow, it times out). Also check ` +
244
- `~/.axe/repos and any folder ls ~ revealed, and widen the pattern (a repo may be named slightly ` +
245
- `differently). Only report not-found after this real search, and say exactly where you looked.` +
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 ` +
@@ -258,6 +262,7 @@ const HELP = [
258
262
  " /audit [n] recent tool + control-plane events from the audit trail (default 15)",
259
263
  " /dashboard launch the live swarm console (watches every Operator session)",
260
264
  " /plan plan mode: read-only research + propose a plan (/plan again to execute)",
265
+ " /mode [plan|manual|auto] set operating mode (plan · manual · autonomous); also Shift+Tab to cycle",
261
266
  " /think extended reasoning: Aurora thinks before answering (/think again = off)",
262
267
  " /ultrathink deep, exhaustive reasoning for hard problems (/ultrathink again = off)",
263
268
  " /compact force-compact the conversation now",
@@ -289,6 +294,7 @@ const REMOTE_SAFE_COMMANDS = [
289
294
  { name: "audit", description: "recent tool + control-plane events from the audit trail", args: "[n]" },
290
295
  { name: "dashboard", description: "launch the live swarm console" },
291
296
  { name: "plan", description: "toggle plan mode (read-only research + propose a plan)" },
297
+ { name: "mode", description: "set operating mode: plan · manual · autonomous", args: "[plan|manual|auto]" },
292
298
  { name: "think", description: "toggle extended reasoning" },
293
299
  { name: "ultrathink", description: "toggle deep, exhaustive reasoning" },
294
300
  { name: "compact", description: "force-compact the conversation now" },
@@ -332,6 +338,9 @@ function Root() {
332
338
  // Operating mode, cycled with Shift+Tab (like Claude Code): auto (no gate) → manual (approve mutations)
333
339
  // → plan (read-only + propose) → auto. Auto=bypass policy, Manual=gated policy, Plan=session plan mode.
334
340
  const [opMode, setOpMode] = useState(settings.permissions.mode === "gated" ? "manual" : "auto");
341
+ // Ref mirror of opMode so buildCapabilities() reflects the LIVE mode synchronously (a follower's mode
342
+ // selector must light up the instant it changes, before React flushes the setOpMode state update).
343
+ const opModeRef = useRef(opMode);
335
344
  const [thinkMode, setThinkMode] = useState("off"); // /think, /ultrathink badge
336
345
  const [elapsed, setElapsed] = useState(0); // live seconds since the current turn started (ticked by a
337
346
  const turnStartRef = useRef(0); // timer, so the clock advances even during a long reasoning
@@ -474,7 +483,7 @@ function Root() {
474
483
  skills: [...skillsRef.current.entries()].map(([name, description]) => ({ name, description })),
475
484
  mcpServers: session.mcpServers().map((s) => ({ name: s.name, toolCount: s.tools.length, tools: s.tools })),
476
485
  models: session.modelRegistry().map((m) => ({ id: m.id, label: m.label, ctx: m.ctx ?? 0, kind: m.kind })),
477
- mode: settings.permissions.mode === "gated" ? "gated" : "auto", // "bypass"/"audit" both drive with no approval gate from a follower's POV
486
+ mode: opModeRef.current, // live operating mode (Plan/Manual/Autonomous) — a follower can read + drive it via /mode
478
487
  cwd: process.cwd(),
479
488
  model: session.currentModel(),
480
489
  });
@@ -699,6 +708,29 @@ function Root() {
699
708
  push({ kind: "message", message: { id: nextId(), role: "system", content: text } });
700
709
  remoteRef.current?.system(text);
701
710
  }, []);
711
+ // Single code path for a mode change — Shift+Tab (onCycleMode), the /mode slash command (local or
712
+ // driven by a remote follower), and /plan all funnel here so the policy, the plan flag, the status
713
+ // badge, and the follower-facing capabilities stay in lockstep. auto=Autonomous (bypass policy, no
714
+ // approvals), manual=gated (mutations ask), plan=read-only research (session plan mode).
715
+ const applyMode = useCallback((next, quiet) => {
716
+ if (next === "plan") {
717
+ session.setPlanMode(true);
718
+ }
719
+ else {
720
+ session.setPlanMode(false);
721
+ session.setPermissionMode(next === "auto" ? "bypass" : "gated");
722
+ }
723
+ opModeRef.current = next;
724
+ setPlanMode(next === "plan");
725
+ setOpMode(next);
726
+ if (!quiet)
727
+ sys(next === "auto"
728
+ ? "◆ mode → AUTONOMOUS — I execute without asking (shift+tab to cycle)"
729
+ : next === "manual"
730
+ ? "◈ mode → MANUAL — I ask before mutating (writes/edits/shell) (shift+tab to cycle)"
731
+ : "◔ mode → PLAN — read-only research + a proposed plan; nothing runs (shift+tab to cycle)");
732
+ remoteRef.current?.setCapabilities(buildCapabilities()); // re-sync attached followers' mode selector
733
+ }, [sys]);
702
734
  const handleSlash = useCallback(async (cmd) => {
703
735
  const [name, ...rest] = cmd.slice(1).split(/\s+/);
704
736
  const arg = rest.join(" ").trim();
@@ -845,13 +877,27 @@ function Root() {
845
877
  }
846
878
  case "plan": {
847
879
  const on = !s.inPlanMode();
848
- s.setPlanMode(on);
849
- setPlanMode(on);
880
+ applyMode(on ? "plan" : "auto", true); // policy + follower caps sync; custom message below
850
881
  sys(on
851
882
  ? "◔ plan mode ON — I'll research read-only and propose a plan; writes/edits/shell mutations are blocked. /plan again to approve + execute."
852
883
  : "plan mode OFF — back to normal execution.");
853
884
  break;
854
885
  }
886
+ case "mode": {
887
+ // Set the operating mode by name (owner OR a remote follower via a `command` frame). Mirrors
888
+ // Shift+Tab's cycle but addressable: /mode plan | manual | autonomous. No arg → report current.
889
+ const a = arg.toLowerCase();
890
+ const target = a === "plan" ? "plan"
891
+ : (a === "manual" || a === "gated") ? "manual"
892
+ : (a === "auto" || a === "autonomous" || a === "bypass") ? "auto"
893
+ : null;
894
+ if (!target) {
895
+ sys(`mode is ${opModeRef.current === "auto" ? "AUTONOMOUS" : opModeRef.current.toUpperCase()} — usage: /mode plan | manual | autonomous`);
896
+ break;
897
+ }
898
+ applyMode(target);
899
+ break;
900
+ }
855
901
  case "think": {
856
902
  const on = s.currentThinkMode() !== "think";
857
903
  s.setThinkMode(on ? "think" : "off");
@@ -1030,7 +1076,7 @@ function Root() {
1030
1076
  }
1031
1077
  default: sys(`unknown command /${name} — try /help`);
1032
1078
  }
1033
- }, [exit, sys, bg, authUser, approval, settleApproval, settleQuestion]);
1079
+ }, [exit, sys, bg, authUser, approval, settleApproval, settleQuestion, applyMode]);
1034
1080
  const onSubmit = useCallback((text) => {
1035
1081
  const t = text.trim();
1036
1082
  if (t.startsWith("/")) {
@@ -1044,22 +1090,10 @@ function Root() {
1044
1090
  // Shift+Tab cycles the operating mode (Claude-Code parity). auto→manual→plan→auto. Auto drives with
1045
1091
  // no approval gate; Manual gates mutating tools through the approve() bridge; Plan is read-only research.
1046
1092
  const onCycleMode = useCallback(() => {
1047
- setOpMode((cur) => {
1048
- const next = cur === "auto" ? "manual" : cur === "manual" ? "plan" : "auto";
1049
- if (next === "plan") {
1050
- session.setPlanMode(true);
1051
- }
1052
- else {
1053
- session.setPlanMode(false);
1054
- session.setPermissionMode(next === "auto" ? "bypass" : "gated");
1055
- }
1056
- setPlanMode(next === "plan");
1057
- sys(next === "auto" ? "◆ mode → AUTO — I execute without asking (shift+tab to cycle)"
1058
- : next === "manual" ? "◈ mode → MANUAL — I ask before mutating (writes/edits/shell) (shift+tab to cycle)"
1059
- : "◔ mode → PLAN — read-only research + a proposed plan; nothing runs (shift+tab to cycle)");
1060
- return next;
1061
- });
1062
- }, [sys]);
1093
+ const cur = opModeRef.current;
1094
+ const next = cur === "auto" ? "manual" : cur === "manual" ? "plan" : "auto";
1095
+ applyMode(next);
1096
+ }, [applyMode]);
1063
1097
  const onInterrupt = useCallback(() => {
1064
1098
  if (statusRef.current === "idle") {
1065
1099
  bg.dispose();
@@ -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 hardCap = opts.maxRoundsHard ?? Math.max(40, softRounds * 4);
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 < hardCap; 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 to hardCap
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 ${hardCap} tool rounds — the task may be unfinished; ask me to continue and I'll pick up where I left off]`;
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
  }
@@ -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 fetch(`${o.base}/v1/chat/completions`, {
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 {
@@ -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) {
@@ -416,6 +469,116 @@ async function webFetch(args) {
416
469
  clearTimeout(timer);
417
470
  }
418
471
  }
472
+ // Shared auth-header builder for the HTTP tools. `bearer` → Authorization: Bearer; `basic` {user,pass} →
473
+ // Authorization: Basic base64. btoa (not node Buffer) keeps this neutral-bundle-safe. The resolved secret
474
+ // is set on the outgoing request only — never returned in the tool result.
475
+ function authHeaders(args) {
476
+ const h = {};
477
+ if (args.bearer)
478
+ h["Authorization"] = `Bearer ${str(args.bearer)}`;
479
+ else if (args.basic && typeof args.basic === "object") {
480
+ const b = args.basic;
481
+ h["Authorization"] = "Basic " + btoa(`${str(b.user)}:${str(b.pass)}`);
482
+ }
483
+ return h;
484
+ }
485
+ const HTTP_BODY_CAP = 200_000; // cap a response body so one huge payload can't balloon the model's context
486
+ // Real HTTP client — the capability gap beyond web_fetch's dumb GET-and-scrape. Any method, custom
487
+ // headers, JSON or raw body, bearer/basic auth, follow redirects, timeout. Returns status + headers +
488
+ // (capped) body verbatim (no HTML-stripping — this is for APIs, not pages). safe:false: it can POST/PUT/
489
+ // DELETE (mutation), so it's gated when the permission policy is on.
490
+ async function httpRequest(args) {
491
+ const url = str(args.url);
492
+ if (!/^https?:\/\//i.test(url))
493
+ return "error: http_request needs an http(s) URL";
494
+ const method = str(args.method, "GET").toUpperCase();
495
+ const headers = { "User-Agent": "operator/kode-tsi", ...authHeaders(args) };
496
+ if (args.headers && typeof args.headers === "object") {
497
+ for (const [k, v] of Object.entries(args.headers))
498
+ headers[k] = String(v);
499
+ }
500
+ let body;
501
+ if (args.json !== undefined) {
502
+ body = JSON.stringify(args.json);
503
+ if (!Object.keys(headers).some((k) => k.toLowerCase() === "content-type"))
504
+ headers["Content-Type"] = "application/json";
505
+ }
506
+ else if (args.body !== undefined) {
507
+ body = str(args.body);
508
+ }
509
+ const noBody = method === "GET" || method === "HEAD";
510
+ const timeoutMs = Number(args.timeout_ms ?? 30_000);
511
+ const ctrl = new AbortController();
512
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
513
+ try {
514
+ const res = await fetch(url, { method, headers, body: noBody ? undefined : body, signal: ctrl.signal, redirect: "follow" });
515
+ const text = await res.text().catch(() => "");
516
+ const hdrs = [...res.headers.entries()].map(([k, v]) => `${k}: ${v}`).slice(0, 50).join("\n");
517
+ const capped = text.length > HTTP_BODY_CAP ? `${text.slice(0, HTTP_BODY_CAP)}\n…[body truncated, ${text.length - HTTP_BODY_CAP} more chars]` : text;
518
+ return `HTTP ${res.status} ${res.statusText}\n${hdrs}\n\n${capped}`.trim();
519
+ }
520
+ catch (e) {
521
+ const m = e instanceof Error ? e.message : String(e);
522
+ return `error: http_request ${method} ${url}: ${/abort/i.test(m) ? `timed out after ${timeoutMs}ms` : m}`;
523
+ }
524
+ finally {
525
+ clearTimeout(timer);
526
+ }
527
+ }
528
+ // Upload a local file to a URL — the missing push side (Operator could download, never upload). POST
529
+ // multipart/form-data (default, the common upload contract) or PUT raw bytes. Supports the same
530
+ // bearer/basic auth + custom headers as http_request. safe:false: it exfiltrates a file to an external
531
+ // service, so it's gated when the policy is on and should confirm the destination.
532
+ async function fileUpload(args) {
533
+ const path = expandPath(str(args.path));
534
+ const url = str(args.url);
535
+ if (!path)
536
+ return "error: file_upload needs a path";
537
+ if (!/^https?:\/\//i.test(url))
538
+ return "error: file_upload needs an http(s) url";
539
+ const method = str(args.method, "POST").toUpperCase();
540
+ const field = str(args.field, "file");
541
+ const headers = { ...authHeaders(args) };
542
+ if (args.headers && typeof args.headers === "object") {
543
+ for (const [k, v] of Object.entries(args.headers))
544
+ headers[k] = String(v);
545
+ }
546
+ const { readFile } = await nodeImport("node:fs/promises");
547
+ const { basename } = await nodeImport("node:path");
548
+ let data;
549
+ try {
550
+ data = await readFile(path);
551
+ }
552
+ catch (e) {
553
+ return `error: cannot read ${path}: ${e.message}`;
554
+ }
555
+ const timeoutMs = Number(args.timeout_ms ?? 120_000); // uploads can be large — generous default
556
+ const ctrl = new AbortController();
557
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
558
+ try {
559
+ let bodyInit;
560
+ if (method === "PUT") {
561
+ bodyInit = data; // raw bytes (S3 presigned-PUT style); node accepts Uint8Array
562
+ if (!Object.keys(headers).some((k) => k.toLowerCase() === "content-type"))
563
+ headers["Content-Type"] = "application/octet-stream";
564
+ }
565
+ else {
566
+ const form = new FormData();
567
+ form.append(field, new Blob([data]), basename(path));
568
+ bodyInit = form; // multipart; fetch sets the Content-Type boundary itself
569
+ }
570
+ const res = await fetch(url, { method, headers, body: bodyInit, signal: ctrl.signal, redirect: "follow" });
571
+ const text = (await res.text().catch(() => "")).slice(0, HTTP_BODY_CAP);
572
+ return `HTTP ${res.status} ${res.statusText} — uploaded ${basename(path)} (${data.byteLength} bytes)${text ? `\n\n${text}` : ""}`.trim();
573
+ }
574
+ catch (e) {
575
+ const m = e instanceof Error ? e.message : String(e);
576
+ return `error: file_upload ${method} ${url}: ${/abort/i.test(m) ? `timed out after ${timeoutMs}ms` : m}`;
577
+ }
578
+ finally {
579
+ clearTimeout(timer);
580
+ }
581
+ }
419
582
  const bgJobs = new Map();
420
583
  let bgSeq = 0;
421
584
  const BG_MAX_RUNNING = 8; // cap concurrent live jobs — a background tool must never let the agent fork-bomb the host
@@ -609,12 +772,23 @@ const TOOLS = [
609
772
  },
610
773
  {
611
774
  name: "grep_search", safe: true,
612
- description: "Recursively grep for a regex pattern under a path.",
775
+ 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
776
  parameters: { type: "object", properties: {
614
777
  pattern: { type: "string" }, path: { type: "string" }, glob: { type: "string" },
615
778
  }, required: ["pattern"] },
616
779
  run: grepSearch,
617
780
  },
781
+ {
782
+ name: "search", safe: true,
783
+ 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).",
784
+ parameters: { type: "object", properties: {
785
+ pattern: { type: "string", description: "regex to search for" },
786
+ path: { type: "string", description: "directory to scope the search to; default is the current dir" },
787
+ glob: { type: "string", description: "filename glob filter, e.g. \"*.ts\"" },
788
+ files_with_matches: { type: "boolean", description: "return only the paths of files that match" },
789
+ }, required: ["pattern"] },
790
+ run: ripgrepSearch,
791
+ },
618
792
  {
619
793
  name: "list_directory", safe: true,
620
794
  description: "List entries in a directory.",
@@ -663,6 +837,34 @@ const TOOLS = [
663
837
  }, required: ["url"] },
664
838
  run: webFetch,
665
839
  },
840
+ {
841
+ name: "http_request", safe: false,
842
+ description: "Make a real HTTP request to any API — full control beyond web_fetch's dumb GET. Any method (GET/POST/PUT/PATCH/DELETE/HEAD), custom headers, a JSON body (`json`) or raw `body`, and bearer/basic auth. Returns status + response headers + the (capped) body verbatim (no HTML stripping). Use for authenticated REST/GraphQL calls, webhooks, and service integrations.",
843
+ parameters: { type: "object", properties: {
844
+ url: { type: "string", description: "the http(s) URL" },
845
+ method: { type: "string", description: "HTTP method (default GET)" },
846
+ headers: { type: "object", description: "request headers as a flat object" },
847
+ json: { description: "a JSON-serializable body (sets Content-Type: application/json)" },
848
+ body: { type: "string", description: "raw request body (ignored if `json` is set)" },
849
+ bearer: { type: "string", description: "convenience: sets Authorization: Bearer <token>" },
850
+ basic: { type: "object", description: "convenience: {user, pass} → Authorization: Basic" },
851
+ timeout_ms: { type: "number", description: "default 30000" },
852
+ }, required: ["url"] },
853
+ run: httpRequest,
854
+ },
855
+ {
856
+ name: "file_upload", safe: false,
857
+ description: "Upload a local file to a URL — the push side web_fetch/download lacks. POST multipart/form-data (default; set `field` for the form field name) or PUT raw bytes (S3 presigned-PUT style). Supports the same bearer/basic auth + custom headers as http_request. Confirm the destination — this sends your file to an external service.",
858
+ parameters: { type: "object", properties: {
859
+ path: { type: "string", description: "local file path to upload" },
860
+ url: { type: "string", description: "destination http(s) URL" },
861
+ method: { type: "string", enum: ["POST", "PUT"], description: "POST=multipart (default), PUT=raw bytes" },
862
+ field: { type: "string", description: "multipart form field name (default \"file\")" },
863
+ headers: { type: "object" }, bearer: { type: "string" }, basic: { type: "object" },
864
+ timeout_ms: { type: "number", description: "default 120000" },
865
+ }, required: ["path", "url"] },
866
+ run: fileUpload,
867
+ },
666
868
  {
667
869
  name: "web_search", safe: true,
668
870
  description: "Search the web (via the AXE autopilot SERP service, or a self-hosted SearXNG) and return ranked title/url/snippet results. Read-only. Follow up with web_fetch to read a result.",
@@ -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 kill and transparently respawn the shell (cwd/env are
11
- // lost only in that exceptional case), so a runaway command can never wedge the session.
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 finish = (out, exitCode, timedOut, truncated) => {
112
- if (timedOut || exitCode === null) {
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: out.replace(/\r/g, "").replace(/\n+$/, ""), exitCode, timedOut, truncated };
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
- return finish(raw.length > OUTPUT_CAP ? raw.slice(0, OUTPUT_CAP) : raw, Number(m[1]), false, raw.length > OUTPUT_CAP);
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 finish(this.buf.slice(0, OUTPUT_CAP), null, false, false);
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 finish(this.buf.slice(0, OUTPUT_CAP), null, false, true);
169
+ return abandon("runaway");
131
170
  if (Date.now() > deadline)
132
- return finish(this.buf.slice(0, OUTPUT_CAP), null, true, false);
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.58",
3
+ "version": "0.1.60",
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": {