@0perator/operator 0.1.284 → 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.
Files changed (99) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +3 -2
  3. package/dist/acp/config-options.js +15 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +304 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +216 -43
  11. package/dist/autonomy/delegate.js +5 -1
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/session-factory.js +25 -16
  14. package/dist/background/index.js +40 -0
  15. package/dist/bus/inbox.js +20 -0
  16. package/dist/classifier/config.js +47 -0
  17. package/dist/classifier/modes.js +41 -0
  18. package/dist/classifier/types.js +1 -0
  19. package/dist/cli.js +529 -53
  20. package/dist/config/features.js +69 -0
  21. package/dist/config/persona.js +118 -99
  22. package/dist/config/scaffold.js +15 -0
  23. package/dist/config/settings.js +96 -6
  24. package/dist/consolidation/sleep.js +73 -11
  25. package/dist/engine/agent.js +275 -18
  26. package/dist/engine/anthropic-chat.js +343 -0
  27. package/dist/engine/aurora.js +101 -13
  28. package/dist/engine/batch-scheduler.js +41 -9
  29. package/dist/engine/classifier.js +85 -0
  30. package/dist/engine/compaction.js +24 -5
  31. package/dist/engine/fast-start.js +25 -0
  32. package/dist/engine/loop-guard.js +448 -0
  33. package/dist/engine/moa.js +5 -1
  34. package/dist/engine/net-error.js +24 -0
  35. package/dist/engine/repetition-guard.js +180 -0
  36. package/dist/engine/selfheal.js +8 -0
  37. package/dist/engine/toolcalls.js +51 -1
  38. package/dist/engine/verify-gate.js +2 -0
  39. package/dist/flywheel/processor.js +78 -31
  40. package/dist/flywheel/srft.js +13 -0
  41. package/dist/hooks/index.js +196 -0
  42. package/dist/mcp/config.js +21 -1
  43. package/dist/memory/index.js +0 -0
  44. package/dist/memory/providers.js +210 -0
  45. package/dist/memory/session-catalog.js +422 -0
  46. package/dist/memory/session-providers.js +121 -0
  47. package/dist/memory/session-sources.js +335 -0
  48. package/dist/memory/skylark.js +131 -0
  49. package/dist/models/bench.js +103 -0
  50. package/dist/models/registry.js +144 -0
  51. package/dist/models/switch.js +69 -0
  52. package/dist/observability/blackbox.js +37 -0
  53. package/dist/permissions/policy.js +31 -6
  54. package/dist/router/discovery.js +127 -0
  55. package/dist/router/models.js +117 -24
  56. package/dist/router/portal.js +100 -0
  57. package/dist/router/router.js +1 -1
  58. package/dist/services/preflight.js +55 -7
  59. package/dist/session.js +316 -46
  60. package/dist/tools/chauffeur.js +12 -0
  61. package/dist/tools/executor.js +19 -9
  62. package/dist/tools/find-files.js +483 -0
  63. package/dist/tools/git-pr.js +94 -0
  64. package/dist/tools/incident-tools.js +82 -0
  65. package/dist/tools/memory.js +12 -2
  66. package/dist/tools/registry.js +281 -85
  67. package/dist/tools/semantic-compress.js +124 -0
  68. package/dist/tools/shell-context.js +1 -0
  69. package/dist/tools/shell-jobs.js +160 -0
  70. package/dist/tools/shell-session.js +170 -4
  71. package/dist/tools/wave-tools.js +609 -0
  72. package/dist/tools/wave2-tools.js +411 -0
  73. package/dist/ui/App.js +15 -4
  74. package/dist/ui/BgPanel.js +30 -6
  75. package/dist/ui/Composer.js +11 -1
  76. package/dist/ui/QuestionPrompt.js +31 -11
  77. package/dist/ui/SessionPicker.js +86 -0
  78. package/dist/ui/StatusRule.js +5 -5
  79. package/dist/ui/ToolStep.js +2 -1
  80. package/dist/ui/Transcript.js +17 -1
  81. package/dist/ui/index.js +1 -1
  82. package/dist/ui/liveTools.js +21 -3
  83. package/dist/ui/slashCommands.js +2 -0
  84. package/dist/util/screenshots.js +74 -8
  85. package/dist/util/slash.js +2 -2
  86. package/package.json +8 -2
  87. package/dist/engine/cli.js +0 -1171
  88. package/dist/router/models.js.bak +0 -78
  89. package/dist/router/models.js.bak-1791259923 +0 -78
  90. package/dist/router/models.js.bak-pre-gateway +0 -78
  91. package/dist/router/models.js.bak-pre-patch2 +0 -78
  92. package/dist/router/models.js.bak2 +0 -78
  93. package/dist/services/model-autodetect.js +0 -240
  94. package/dist/tools/native-redirect.js +0 -140
  95. package/dist/tools/power-tools.js +0 -627
  96. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  97. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  98. package/dist/ui/BusTray.js +0 -70
  99. package/dist/ui/resize.js +0 -160
@@ -0,0 +1,85 @@
1
+ // axe-classifier client (GLiClass zero-shot service, v2.2.0) + the options-vs-act gate decision. Mirrors the
2
+ // deterministic classify* contract of auth/login-intent.ts and meridian's graceful degradation: on ANY
3
+ // error / timeout / unreachable / non-200 it returns {decision:"act", degraded:true}, so the gate NEVER blocks
4
+ // a turn — today's model-reasons-the-EXCEPTION behavior is always the safe fallback. Speaks the CURRENT
5
+ // contract only (POST /classify {text, labels[], min_score} → {scores:[{label,score}], latency_ms,
6
+ // fallback_used}), never the superseded v1 {text}→{label} shape.
7
+ /** The single "proceed" label; every OTHER candidate label is an ASK signal. */
8
+ export const ACT_LABEL = "act now";
9
+ /** The ASK signals — any of these at/above threshold means hand the owner options instead of auto-executing. */
10
+ export const ASK_LABELS = [
11
+ "needs user options or confirmation",
12
+ "ambiguous scope",
13
+ "heavy or irreversible work",
14
+ ];
15
+ const DEFAULT_ENDPOINT = "http://127.0.0.1:8400";
16
+ const DEFAULT_MIN_SCORE = 0.5;
17
+ const DEFAULT_TIMEOUT_MS = 2000;
18
+ function degraded(t0) {
19
+ return { decision: "act", degraded: true, latencyMs: Math.round(performance.now() - t0) };
20
+ }
21
+ /** Classify a user turn into act-vs-ask against axe-classifier. CONSERVATIVE: "ask" only when a non-"act"
22
+ * label is at/above the threshold; otherwise "act". Any failure degrades to {decision:"act", degraded:true}. */
23
+ export async function classifyActVsAsk(text, opts = {}) {
24
+ const endpoint = (opts.endpoint ?? DEFAULT_ENDPOINT).replace(/\/$/, "");
25
+ const minScore = typeof opts.minScore === "number" ? opts.minScore : DEFAULT_MIN_SCORE;
26
+ const labels = opts.labels ?? [ACT_LABEL, ...ASK_LABELS];
27
+ const t0 = performance.now();
28
+ const ctrl = new AbortController();
29
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
30
+ const onAbort = () => ctrl.abort();
31
+ if (opts.signal) {
32
+ if (opts.signal.aborted)
33
+ ctrl.abort();
34
+ else
35
+ opts.signal.addEventListener("abort", onAbort, { once: true });
36
+ }
37
+ try {
38
+ const headers = { "content-type": "application/json" };
39
+ if (opts.apiKey)
40
+ headers["X-AXE-Key"] = opts.apiKey; // soft auth — only when configured
41
+ const res = await fetch(`${endpoint}/classify`, {
42
+ method: "POST",
43
+ headers,
44
+ body: JSON.stringify({ text, labels, min_score: minScore }),
45
+ signal: ctrl.signal,
46
+ });
47
+ if (!res.ok)
48
+ return degraded(t0);
49
+ const json = await res.json();
50
+ const scores = Array.isArray(json?.scores) ? json.scores : [];
51
+ const latencyMs = typeof json?.latency_ms === "number" ? json.latency_ms : Math.round(performance.now() - t0);
52
+ const askHit = scores
53
+ .filter((s) => s && s.label !== ACT_LABEL && typeof s.score === "number" && s.score >= minScore)
54
+ .sort((a, b) => b.score - a.score)[0];
55
+ if (askHit)
56
+ return { decision: "ask", label: askHit.label, score: askHit.score, latencyMs, degraded: false };
57
+ const top = scores.slice().sort((a, b) => b.score - a.score)[0];
58
+ return { decision: "act", label: top?.label, score: top?.score, latencyMs, degraded: false };
59
+ }
60
+ catch {
61
+ return degraded(t0); // timeout / unreachable / non-JSON — fall back to today's behavior
62
+ }
63
+ finally {
64
+ clearTimeout(timer);
65
+ if (opts.signal)
66
+ opts.signal.removeEventListener("abort", onAbort);
67
+ }
68
+ }
69
+ /** The strong, high-priority per-turn directive that enforces the memories.md EXCEPTION when the gate says
70
+ * "ask". Advisory-strong and reversible — v1 injects guidance into the turn's system prompt only; it never
71
+ * hard-blocks a tool. */
72
+ export const ACT_ASK_GATE_DIRECTIVE = `\n\n## OPTIONS FIRST (this turn)\nThis request was classified as one that needs the owner's decision before ` +
73
+ `heavy or irreversible action. Apply the EXCEPTION rule now: do NOT auto-execute heavy, destructive, or ` +
74
+ `irreversible work this turn. Instead, present a concise NUMBERED list of the concrete options, each with its ` +
75
+ `tradeoff, and ask the owner to choose. Read-only investigation to inform those options is fine; any mutating ` +
76
+ `action waits for the owner's pick.`;
77
+ /** The gate's per-turn verdict: the directive to inject, or null for none. Pure + total so the three cases
78
+ * (flag off, "ask", degraded/"act") are unit-testable without touching the network. */
79
+ export function actAskGateDirective(enabled, result) {
80
+ if (!enabled)
81
+ return null; // feature OFF → byte-identical to today
82
+ if (result.degraded)
83
+ return null; // classifier unreachable → today's behavior, no injection
84
+ return result.decision === "ask" ? ACT_ASK_GATE_DIRECTIVE : null;
85
+ }
@@ -118,8 +118,9 @@ export function shouldProactivelyCompact(conversation, opts) {
118
118
  * Returns a new array; the input is never mutated. If eliding every tool output still won't fit (huge
119
119
  * user/assistant prose), it returns the maximally-elided array so the caller still sends the SMALLEST
120
120
  * possible request rather than a guaranteed-fatal one. */
121
- export function fitToWindow(conversation, opts) {
122
- if (usageRatio(conversation, opts) < (opts.threshold ?? 0.7))
121
+ export function fitToWindow(conversation, opts, targetRatio) {
122
+ const target = targetRatio ?? opts.threshold ?? 0.7;
123
+ if (usageRatio(conversation, opts) < target)
123
124
  return [...conversation];
124
125
  const out = conversation.map((m) => ({ ...m }));
125
126
  // Tool messages, largest content first — shed the worst offenders until it fits. GW-10-COMPLETE:
@@ -130,7 +131,7 @@ export function fitToWindow(conversation, opts) {
130
131
  .filter((x) => x.len > 0)
131
132
  .sort((a, b) => (a.err === b.err ? b.len - a.len : a.err ? 1 : -1));
132
133
  for (const { i } of byLargest) {
133
- if (usageRatio(out, opts) < (opts.threshold ?? 0.7))
134
+ if (usageRatio(out, opts) < target)
134
135
  break;
135
136
  const was = out[i].content.length;
136
137
  const p = opts.spill ? opts.spill(out[i].content) : null;
@@ -148,9 +149,27 @@ export function fitToWindow(conversation, opts) {
148
149
  * cut-off call is unparseable (see selfheal's truncated_tool_call). If even the floor won't fit, the
149
150
  * prompt is over budget and the caller's compaction handles it. */
150
151
  export function clampMaxTokens(built, opts, want, min = 1024) {
152
+ return Math.max(min, Math.min(want, outputRoom(built, opts)));
153
+ }
154
+ /** The generation room a request leaves: window − prompt estimate − the 256-token chat-template/role margin.
155
+ * The SAME basis clampMaxTokens clamps to (factored out so the turn loop's headroom guard and the clamp can
156
+ * never drift apart). `built` already includes the system message, so systemPrompt is excluded from the
157
+ * estimate; tool-schema tokens still come from opts.tools. Negative when the prompt alone overflows. */
158
+ export function outputRoom(built, opts) {
151
159
  const promptEst = fullRequestEstimate(built, { ...opts, systemPrompt: undefined });
152
- const room = opts.ctxWindow - promptEst - 256; // margin for chat-template/role tokens the estimate omits
153
- return Math.max(min, Math.min(want, room));
160
+ return opts.ctxWindow - promptEst - 256; // margin for chat-template/role tokens the estimate omits
161
+ }
162
+ /** Tool-safe output floor: a round must keep at least this much generation room, or a large tool call's
163
+ * arguments JSON gets cut off mid-stream (the unparseable "arguments were CUT OFF" dead end). ~4096 tokens
164
+ * covers the chunk-write ceiling the truncation nudges steer toward (~4KB args) with margin. */
165
+ export const TOOL_CALL_HEADROOM_TOKENS = 4096;
166
+ /** The tighter fitToWindow target that reserves `minOutputTokens` (+ the 256 margin) of the window for
167
+ * generation: shed the prompt to this ratio and a full tool call has room to land. Clamped to [0,1] — a
168
+ * window smaller than the headroom sheds as hard as possible (0), and a zero/unknown window never divides. */
169
+ export function headroomTargetRatio(opts, minOutputTokens) {
170
+ if (opts.ctxWindow <= 0)
171
+ return 0;
172
+ return Math.min(1, Math.max(0, (opts.ctxWindow - minOutputTokens - 256) / opts.ctxWindow));
154
173
  }
155
174
  /** The summary content picker (SPEC §5 failure handling). Aurora's always-on thinking frequently
156
175
  * spends the whole budget on reasoning_content and returns EMPTY content — the facts still live in
@@ -0,0 +1,25 @@
1
+ // Fast-start — PURE half (zero imports, node-free by construction, same split as srft.ts).
2
+ // A fast, cheap, freely-swappable model (settings.fastStart — any OpenAI-compatible small model;
3
+ // "scout" is just today's default, not a hardcoded dependency) races the real turn: if the request is
4
+ // simple enough to answer without tools, its own answer short-circuits the turn entirely (real
5
+ // speedup — Aurora's round is aborted before it does any work). If it can't, or decides it needs
6
+ // tools, its reply is discarded and the normal turn proceeds exactly as it would without this feature
7
+ // — never slower, only sometimes faster.
8
+ export const NEEDS_TOOLS_SENTINEL = "NEEDS_TOOLS";
9
+ export const FAST_START_INSTRUCTION = `You are a fast first-pass responder racing a slower, more capable model that has tool access. ` +
10
+ `If you can fully and correctly answer the user's message RIGHT NOW, from general knowledge alone, ` +
11
+ `with no files, commands, searches, or other tools — answer it directly and completely. ` +
12
+ `If you need any tool, file, command, or current/external information to answer well, reply with ` +
13
+ `EXACTLY this and nothing else: ${NEEDS_TOOLS_SENTINEL}`;
14
+ /** Parse scout's raw reply. Fails closed to "needs-tools" on anything ambiguous (empty, whitespace-only,
15
+ * or the sentinel in any casing/wrapping) — a wrong "needs-tools" costs nothing (the real turn was
16
+ * always going to run anyway); a wrong "answered" would wrongly skip the real turn, which is the one
17
+ * mistake this must never make. */
18
+ export function parseFastStartReply(raw) {
19
+ const text = raw.trim();
20
+ if (!text)
21
+ return { kind: "needs-tools" };
22
+ if (text.toUpperCase() === NEEDS_TOOLS_SENTINEL)
23
+ return { kind: "needs-tools" };
24
+ return { kind: "answered", text };
25
+ }
@@ -0,0 +1,448 @@
1
+ // Tool-call loop guard — a side-effect-free controller. The engine feeds it every call and result of a turn;
2
+ // it answers with decisions (allow / warn / halt) and, for a duplicate result, a short stub. It never
3
+ // executes, blocks or stops anything itself: agent.ts decides how a decision becomes a note on the tool result
4
+ // or a clean end of the turn. It EXTENDS the engine's older guards (identical-args counter, repeated-action
5
+ // fingerprint, content-loop and converge stops) and does not replace them: those key on the CALL, this keys
6
+ // on what the call RETURNED, so the same call returning something new is never a loop.
7
+ //
8
+ // Detectors: consecutive identical (tool, args, result) calls; repeating cycles A,B,A,B… of up to four calls
9
+ // with identical args and results; exact-args failure replays; failure runs on one tool; read-only calls that
10
+ // keep returning the same result; per-turn caps on web searches and sub-agent spawns. Warnings never block.
11
+ // A hard stop is on by default for unattended runs and opt-in for an interactive owner.
12
+ export const LOOP_GUARD_DEFAULTS = {
13
+ warnIdentical: 3, warnExactFailure: 2, warnSameToolFailure: 3, warnNoProgress: 2, warnInvestigateLoop: 8,
14
+ stopIdentical: 5, stopExactFailure: 5, stopSameToolFailure: 8, stopNoProgress: 5, stopInvestigateLoop: 15,
15
+ maxWebSearches: 50, maxSubagents: 50,
16
+ };
17
+ const intAtLeast = (v, dflt, min) => typeof v === "number" && Number.isFinite(v) && Math.floor(v) >= min ? Math.floor(v) : dflt;
18
+ /** Fold user settings over the defaults. `unattended` = no owner watching (headless run/loop/board/routine):
19
+ * the hard stop defaults ON there and OFF for an interactive session unless `hardStop` says otherwise. */
20
+ export function resolveLoopGuardConfig(raw, ctx) {
21
+ const s = raw ?? {};
22
+ const d = LOOP_GUARD_DEFAULTS;
23
+ return {
24
+ enabled: s.enabled !== false,
25
+ hardStop: typeof s.hardStop === "boolean" ? s.hardStop : ctx.unattended,
26
+ repetition: s.repetition !== false,
27
+ warnIdentical: intAtLeast(s.warnAfter?.identicalCall, d.warnIdentical, 2),
28
+ warnExactFailure: intAtLeast(s.warnAfter?.exactFailure, d.warnExactFailure, 1),
29
+ warnSameToolFailure: intAtLeast(s.warnAfter?.sameToolFailure, d.warnSameToolFailure, 1),
30
+ warnNoProgress: intAtLeast(s.warnAfter?.noProgress, d.warnNoProgress, 1),
31
+ warnInvestigateLoop: intAtLeast(s.warnAfter?.investigateLoop, d.warnInvestigateLoop, 1),
32
+ stopIdentical: intAtLeast(s.hardStopAfter?.identicalCall, d.stopIdentical, 2),
33
+ stopExactFailure: intAtLeast(s.hardStopAfter?.exactFailure, d.stopExactFailure, 1),
34
+ stopSameToolFailure: intAtLeast(s.hardStopAfter?.sameToolFailure, d.stopSameToolFailure, 1),
35
+ stopNoProgress: intAtLeast(s.hardStopAfter?.noProgress, d.stopNoProgress, 1),
36
+ stopInvestigateLoop: intAtLeast(s.hardStopAfter?.investigateLoop, d.stopInvestigateLoop, 1),
37
+ maxWebSearches: intAtLeast(s.caps?.webSearches, d.maxWebSearches, 0),
38
+ maxSubagents: intAtLeast(s.caps?.subagents, d.maxSubagents, 0),
39
+ };
40
+ }
41
+ /** Read-only tools: the same call returning the same result again is no new information. */
42
+ export const IDEMPOTENT_TOOLS = new Set([
43
+ "file_read", "read_files", "search", "grep_search", "list_directory", "find_files", "locate", "web_search",
44
+ "web_fetch", "git_status", "memory_search", "session_search", "session_read", "skill_catalog", "skill_fetch",
45
+ "skill_list",
46
+ ]);
47
+ /** A successful call to one of these is progress: every failing call still counted this turn is retried as a
48
+ * new experiment (edit -> re-run), not a replay. */
49
+ export const PROGRESS_TOOLS = new Set([
50
+ "file_write", "file_edit", "bash", "shell_exec", "shell_background", "git_command", "delegate_task",
51
+ "spawn_agent", "email_send", "cronjob", "task_add", "task_update", "task_clear", "memory_store", "checkpoint",
52
+ "http_request", "browser", "chauffeur",
53
+ ]);
54
+ /** Tools whose "failure" is normal work output (a red test run, an empty page): a run of DIFFERENT failing
55
+ * calls is diagnosis, so the same-tool failure run only warns for them and never stops the turn. */
56
+ export const FAILURE_TOLERANT_TOOLS = new Set([
57
+ "bash", "shell_exec", "shell_background", "bash_output", "browser", "web_fetch", "http_request", "chauffeur",
58
+ ]);
59
+ /** Pollers: re-invoked with identical args while waiting on async work. Never flagged as a loop. */
60
+ export const POLLER_TOOLS = new Set(["agent_status", "bash_output"]);
61
+ // A shell command that waits on or inspects a running job: sleeps/waits, process checks, following or tailing a
62
+ // log, reading a job's log/pid/status file. An unchanged answer there means "not done yet", which is progress.
63
+ const POLL_COMMAND_RE = /(?:^|[;&|(]\s*)(?:sleep|wait|until|watch|pgrep|pidof|jobs|tail)\b|\bkill\s+-0\b|\bps\s+(?:-|aux)|\.(?:log|out|pid|status)\b/i;
64
+ const SHELL_TOOLS = new Set(["bash", "shell_exec"]);
65
+ const SPAWN_TOOLS = new Set(["delegate_task", "spawn_agent"]);
66
+ const MAX_CYCLE_PERIOD = 4;
67
+ const CYCLE_HISTORY = 64;
68
+ /** From the 2nd byte-identical repeat a duplicate result of at least this size becomes a reference stub. */
69
+ export const STUB_MIN_CHARS = 512;
70
+ const STUB_ARGS_PREVIEW = 120;
71
+ const FAILURE_PREFIX_RE = /^(?:error|permission denied|cancelled)\b/i;
72
+ const EXIT_TRAILER_RE = /(?:\[exit (\d+)\]|^\(no output; exit (\d+|\?)\))\s*$/;
73
+ /** True when a poll-style call is legitimately repeated while waiting (never a loop). */
74
+ export function isRepeatable(name, args) {
75
+ if (POLLER_TOOLS.has(name))
76
+ return true;
77
+ // Hermes parity: generated/MCP poller naming conventions are legitimately re-invoked with identical args.
78
+ if (name.endsWith("_poll") || name.endsWith("_get_result"))
79
+ return true;
80
+ return SHELL_TOOLS.has(name) && POLL_COMMAND_RE.test(String(args.command ?? ""));
81
+ }
82
+ /** Whether a tool result reports failure. A refusal by the engine's own guards is not the tool failing. */
83
+ export function resultFailed(name, result) {
84
+ const t = result.trimStart();
85
+ if (/^(?:loop guard|repeated action)/i.test(t))
86
+ return false;
87
+ if (FAILURE_PREFIX_RE.test(t))
88
+ return true;
89
+ if (SHELL_TOOLS.has(name) || name === "shell_background") {
90
+ const m = EXIT_TRAILER_RE.exec(result);
91
+ if (m)
92
+ return (m[1] ?? m[2]) !== "0";
93
+ }
94
+ return false;
95
+ }
96
+ /** A landed workspace edit: file_write / file_edit that did not come back as an error. */
97
+ function mutationOk(name, result) {
98
+ return (name === "file_write" || name === "file_edit") && !FAILURE_PREFIX_RE.test(result.trimStart()) && !/^(?:loop guard|repeated action)/i.test(result.trimStart());
99
+ }
100
+ /** Tools that constitute genuine write-progress for the investigate-loop detector.
101
+ * Deliberately narrower than PROGRESS_TOOLS: bash/git_command are excluded because
102
+ * grep/search/ls inside bash are the exact pattern that motivated this detector.
103
+ * Trade: one cheap nudge vs a 3-hour marathon of bash-based investigation. */
104
+ export const WRITE_PROGRESS_TOOLS = new Set([
105
+ "file_write", "file_edit", "file_create", "checkpoint",
106
+ "task_add", "task_update", "task_clear", "memory_store",
107
+ "delegate_task", "delegate_to_agent", "spawn_agent",
108
+ "cronjob",
109
+ ]);
110
+ function canonical(v) {
111
+ if (Array.isArray(v))
112
+ return "[" + v.map(canonical).join(",") + "]";
113
+ if (v && typeof v === "object") {
114
+ const o = v;
115
+ return "{" + Object.keys(o).sort().map((k) => JSON.stringify(k) + ":" + canonical(o[k])).join(",") + "}";
116
+ }
117
+ return JSON.stringify(v) ?? "null";
118
+ }
119
+ /** Non-cryptographic 53-bit string hash (cyrb53). The engine bundle also runs where node:crypto is absent, and
120
+ * the hash only has to tell two tool results apart within one turn. */
121
+ function hash(str) {
122
+ let h1 = 0xdeadbeef, h2 = 0x41c6ce57;
123
+ for (let i = 0; i < str.length; i++) {
124
+ const ch = str.charCodeAt(i);
125
+ h1 = Math.imul(h1 ^ ch, 2654435761);
126
+ h2 = Math.imul(h2 ^ ch, 1597334677);
127
+ }
128
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
129
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
130
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36) + ":" + str.length;
131
+ }
132
+ const ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : (["th", "st", "nd", "rd"][n % 10] ?? "th")}`;
133
+ const ALLOW = (tool, count = 0) => ({ action: "allow", message: "", tool, count });
134
+ export class LoopGuard {
135
+ config;
136
+ exactFailures = new Map();
137
+ sameToolFailures = new Map();
138
+ progressSinceFailure = new Set();
139
+ noProgress = new Map();
140
+ streak = { sig: "", hash: "", count: 0, firstId: "" };
141
+ history = [];
142
+ webSearches = 0;
143
+ spawns = 0;
144
+ lastHash = new Map(); // sig -> hash of its latest executed result (a refused repeat is "the same result again")
145
+ haltDecision = null;
146
+ constructor(config) {
147
+ this.config = config;
148
+ }
149
+ /** The decision that ended the turn, if any. The engine stops cleanly at the next batch boundary. */
150
+ get halt() { return this.haltDecision; }
151
+ stop(code, tool, count, message) {
152
+ const d = { action: "halt", code, message, tool, count };
153
+ this.haltDecision ??= d;
154
+ return d;
155
+ }
156
+ /** Before a call runs: per-turn caps (always), then, with the hard stop on, a replay of a call that already
157
+ * failed with no change since, or a read-only call that keeps returning the same thing. */
158
+ beforeCall(name, args) {
159
+ const c = this.config;
160
+ if (!c.enabled)
161
+ return ALLOW(name);
162
+ if (name === "web_search" && c.maxWebSearches > 0) {
163
+ if (this.webSearches >= c.maxWebSearches) {
164
+ return this.stop("web_search_cap", name, this.webSearches, `this turn already made ${c.maxWebSearches} web searches, the per-turn limit — that looks like a runaway search loop`);
165
+ }
166
+ this.webSearches++;
167
+ }
168
+ if (SPAWN_TOOLS.has(name) && c.maxSubagents > 0) {
169
+ if (this.spawns >= c.maxSubagents) {
170
+ return this.stop("subagent_cap", name, this.spawns, `this turn already started ${this.spawns} sub-agents (limit ${c.maxSubagents}) — that looks like a runaway delegation loop`);
171
+ }
172
+ this.spawns++;
173
+ }
174
+ if (!c.hardStop)
175
+ return ALLOW(name);
176
+ const sig = name + "\0" + canonical(args);
177
+ const exact = this.progressSinceFailure.has(sig) ? 0 : (this.exactFailures.get(sig) ?? 0);
178
+ if (exact >= c.stopExactFailure) {
179
+ return this.stop("exact_failure", name, exact, `the same ${name} call failed ${exact} times with identical arguments and nothing changed in between`);
180
+ }
181
+ const rec = IDEMPOTENT_TOOLS.has(name) ? this.noProgress.get(sig) : undefined;
182
+ if (rec && rec.count >= c.stopNoProgress) {
183
+ return this.stop("no_progress", name, rec.count, `${name} returned the same result ${rec.count} times`);
184
+ }
185
+ return ALLOW(name);
186
+ }
187
+ /** After a call settled. Returns the text to record as the tool result (the original, a duplicate-result
188
+ * stub, and/or short plain notes) and the decision. `shortCircuited` marks a call another guard refused
189
+ * without running it: it counts as one more identical repeat but changes nothing else. */
190
+ afterCall(name, args, result, opts = {}) {
191
+ const c = this.config;
192
+ if (!c.enabled)
193
+ return { result, decision: ALLOW(name) };
194
+ const sig = name + "\0" + canonical(args);
195
+ if (opts.shortCircuited) {
196
+ const last = this.lastHash.get(sig);
197
+ if (last === undefined)
198
+ return { result, decision: ALLOW(name) };
199
+ return { result, decision: this.observe(name, args, sig, last, false, "").decision };
200
+ }
201
+ const failed = resultFailed(name, result);
202
+ const notes = [];
203
+ let decision = ALLOW(name);
204
+ let stale; // read-only call repeating itself; yields to the sharper streak/cycle note
205
+ const warn = (code, count, message) => {
206
+ notes.push(message);
207
+ if (decision.action === "allow")
208
+ decision = { action: "warn", code, message, tool: name, count };
209
+ };
210
+ if (failed) {
211
+ if (this.progressSinceFailure.delete(sig))
212
+ this.exactFailures.delete(sig); // a change landed since: not a replay
213
+ const exact = (this.exactFailures.get(sig) ?? 0) + 1;
214
+ this.exactFailures.set(sig, exact);
215
+ const same = (this.sameToolFailures.get(name) ?? 0) + 1;
216
+ this.sameToolFailures.set(name, same);
217
+ this.noProgress.delete(sig);
218
+ if (c.hardStop && !FAILURE_TOLERANT_TOOLS.has(name) && same >= c.stopSameToolFailure) {
219
+ decision = this.stop("same_tool_failure", name, same, `${name} failed ${same} times this turn`);
220
+ }
221
+ else if (exact >= c.warnExactFailure) {
222
+ warn("exact_failure", exact, `${name} has failed ${exact} times with identical arguments. This looks like a loop: read the error and change strategy instead of retrying it unchanged.`);
223
+ }
224
+ else if (same >= c.warnSameToolFailure) {
225
+ warn("same_tool_failure", same, `${name} has failed ${same} times this turn. Diagnose before retrying: check the latest error, then try different arguments, a narrower path or query, or another tool.`);
226
+ }
227
+ }
228
+ else {
229
+ this.exactFailures.delete(sig);
230
+ this.sameToolFailures.delete(name);
231
+ const landed = mutationOk(name, result);
232
+ if (landed) {
233
+ // The workspace changed: every earlier observation is stale, so a re-run is a new experiment.
234
+ for (const k of this.exactFailures.keys())
235
+ this.progressSinceFailure.add(k);
236
+ this.sameToolFailures.clear();
237
+ this.noProgress.clear();
238
+ this.history = [];
239
+ this.streak = { sig: "", hash: "", count: 0, firstId: "" };
240
+ }
241
+ else if (PROGRESS_TOOLS.has(name)) {
242
+ for (const k of this.exactFailures.keys())
243
+ this.progressSinceFailure.add(k);
244
+ this.sameToolFailures.clear();
245
+ }
246
+ if (IDEMPOTENT_TOOLS.has(name)) {
247
+ const h = hash(result);
248
+ const prev = this.noProgress.get(sig);
249
+ const count = prev && prev.hash === h ? prev.count + 1 : 1;
250
+ this.noProgress.set(sig, { hash: h, count });
251
+ if (count >= c.warnNoProgress) {
252
+ stale = { count, message: `${name} returned the same result ${count} times. Use the result already provided or change the query instead of repeating it unchanged.` };
253
+ }
254
+ }
255
+ else {
256
+ this.noProgress.delete(sig);
257
+ }
258
+ }
259
+ const verdict = this.observe(name, args, sig, hash(result), failed, opts.id ?? "", result);
260
+ // One note per result: a failure warning already says it; the streak/cycle note says it better than "same result".
261
+ if (verdict.note && notes.length === 0)
262
+ notes.push(verdict.note);
263
+ else if (stale && notes.length === 0) {
264
+ notes.push(stale.message);
265
+ decision = { action: "warn", code: "no_progress", message: stale.message, tool: name, count: stale.count };
266
+ }
267
+ if (verdict.decision.action !== "allow" && decision.action !== "halt")
268
+ decision = verdict.decision;
269
+ const body = verdict.stub ?? result;
270
+ return { result: notes.length ? `${body}\n\n${notes.map((n) => `[note: ${n}]`).join("\n")}` : body, decision };
271
+ }
272
+ /** Streak + cycle bookkeeping for one settled call. */
273
+ observe(name, args, sig, h, failed, id, result = "") {
274
+ const c = this.config;
275
+ this.lastHash.set(sig, h);
276
+ const repeatable = isRepeatable(name, args);
277
+ if (sig === this.streak.sig && h === this.streak.hash)
278
+ this.streak.count++;
279
+ else
280
+ this.streak = { sig, hash: h, count: 1, firstId: id };
281
+ this.history.push({ sig, hash: h, repeatable });
282
+ if (this.history.length > CYCLE_HISTORY)
283
+ this.history.shift();
284
+ let note;
285
+ let decision = ALLOW(name, this.streak.count);
286
+ if (!repeatable && this.streak.count >= c.warnIdentical) {
287
+ note = `this is the ${ordinal(this.streak.count)} consecutive identical call to ${name} with identical arguments returning the same result. Do not repeat it — change arguments, use a different tool, or proceed with what you have.`;
288
+ decision = { action: "warn", code: "identical_call", message: note, tool: name, count: this.streak.count };
289
+ if (c.hardStop && this.streak.count >= c.stopIdentical)
290
+ decision = this.stop("identical_call", name, this.streak.count, `the same ${name} call returned the same result ${this.streak.count} times in a row`);
291
+ }
292
+ else {
293
+ const cycle = this.detectCycle();
294
+ if (cycle) {
295
+ note = `the last ${cycle.laps} rounds repeated the same cycle of ${cycle.period} tool calls (ending with ${name}) with identical arguments and identical results. Do not repeat the batch — change arguments, use a different tool, or proceed with what you have.`;
296
+ decision = { action: "warn", code: "identical_cycle", message: note, tool: name, count: cycle.laps };
297
+ if (c.hardStop && cycle.laps >= c.stopIdentical)
298
+ decision = this.stop("identical_cycle", name, cycle.laps, `the same cycle of ${cycle.period} tool calls repeated ${cycle.laps} times with identical results`);
299
+ }
300
+ }
301
+ // Duplicate payload: the tool still ran, only its context representation is deduplicated.
302
+ const stub = this.streak.count >= 2 && !failed && result.length >= STUB_MIN_CHARS ? this.stubFor(name, args) : undefined;
303
+ return { note, stub, decision };
304
+ }
305
+ /** Smallest period 2..MAX whose trailing laps (identical signature AND result per position) reach the
306
+ * notice threshold. A cycle made only of pollers is legitimate waiting. Period 1 is the streak's job. */
307
+ detectCycle() {
308
+ const h = this.history;
309
+ const need = this.config.warnIdentical;
310
+ for (let period = 2; period <= MAX_CYCLE_PERIOD; period++) {
311
+ if (h.length < period * need)
312
+ continue;
313
+ let laps = 1;
314
+ for (;;) {
315
+ const base = h.length - period * (laps + 1);
316
+ if (base < 0)
317
+ break;
318
+ let equal = true;
319
+ for (let i = 0; i < period && equal; i++) {
320
+ const a = h[base + i], b = h[h.length - period + i];
321
+ equal = a.sig === b.sig && a.hash === b.hash;
322
+ }
323
+ if (!equal)
324
+ break;
325
+ laps++;
326
+ }
327
+ if (laps >= need && !h.slice(h.length - period).every((e) => e.repeatable))
328
+ return { period, laps };
329
+ }
330
+ return null;
331
+ }
332
+ stubFor(name, args) {
333
+ let preview = canonical(args);
334
+ if (preview.length > STUB_ARGS_PREVIEW)
335
+ preview = preview.slice(0, STUB_ARGS_PREVIEW) + "…";
336
+ const ref = this.streak.firstId ? ` (tool_call_id ${this.streak.firstId})` : "";
337
+ return `[note: this result is byte-identical to the ${name} result earlier this turn${ref}. Refer to that result; it has not changed. Args: ${preview}]`;
338
+ }
339
+ }
340
+ // ── Poll-spin guard ──────────────────────────────────────────────────────────
341
+ // A DIFFERENT failure from the loop guard above. agent_status is in POLLER_TOOLS (legitimately re-callable
342
+ // while waiting), so it is EXEMPT from the identical-call guard — nothing caps it. But a sub-agent's result
343
+ // AUTO-POSTS to the conversation when it finishes, so there is never a reason to poll agent_status in a loop:
344
+ // seen live, the main loop called agent_status round after round ("still working, I'll check again") for 24
345
+ // min / 4k tokens while the auto-post sat waiting. This guard catches exactly that: consecutive rounds whose
346
+ // ONLY tool work is an auto-posting poller (agent_status) returning the SAME result, with no other action in
347
+ // between. bash_output is NOT here — polling a still-running foreground command the user is waiting on is
348
+ // legitimate (an unchanged result there means "not done yet"), and a round containing any non-poller tool
349
+ // resets the streak. The distinction is intrinsic: auto-posting pollers never need a wait loop; everything
350
+ // else might.
351
+ export const AUTOPOST_POLLERS = new Set(["agent_status"]);
352
+ export const POLL_SPIN_DEFAULTS = { nudgeAfter: 2, stopAfter: 3 };
353
+ export const POLL_SPIN_NUDGE = "Sub-agent results auto-post to this conversation the moment they finish — you do not need to poll " +
354
+ "agent_status to learn that. Stop checking status: either do independent work now, or end your turn and the " +
355
+ "auto-posted results will resume it when they land. Do NOT call agent_status again without doing real work first.";
356
+ export const POLL_SPIN_STOP = "[stopped — agent_status was polled repeatedly with no other work and no change in status. Sub-agent results " +
357
+ "auto-post when they finish and will resume this turn, so polling only burns time and tokens. Nothing was " +
358
+ "lost — the results arrive on their own.]";
359
+ /** Watches settled tool rounds for an auto-post-poller spin. Fed one round at a time via observe(); a
360
+ * productive (non-poller) tool OR a changed poll result resets the streak. Side-effect-free: the engine acts
361
+ * on the returned action (inject the nudge once, then end the turn). */
362
+ export class PollSpinGuard {
363
+ nudgeAfter;
364
+ stopAfter;
365
+ streak = 0;
366
+ lastHash = "";
367
+ nudged = false;
368
+ constructor(nudgeAfter = POLL_SPIN_DEFAULTS.nudgeAfter, stopAfter = POLL_SPIN_DEFAULTS.stopAfter) {
369
+ this.nudgeAfter = nudgeAfter;
370
+ this.stopAfter = stopAfter;
371
+ }
372
+ reset() { this.streak = 0; this.nudged = false; this.lastHash = ""; }
373
+ /** One settled round: the tools it ran (names) and their results, index-aligned. */
374
+ observe(names, results) {
375
+ const pollers = names.filter((n) => AUTOPOST_POLLERS.has(n));
376
+ const hasOther = names.some((n) => !AUTOPOST_POLLERS.has(n));
377
+ // No auto-post poller, or any real work alongside it ⇒ progress, never a spin.
378
+ if (pollers.length === 0 || hasOther) {
379
+ this.reset();
380
+ return { action: "allow", streak: 0 };
381
+ }
382
+ // A pure poll round. A changed poll result means a sub-agent's state moved (one finished / was added) —
383
+ // that IS new information, so the streak resets.
384
+ const h = hash(names.filter((n) => AUTOPOST_POLLERS.has(n)).join("\0") + "\u0001" + results.join("\0"));
385
+ if (this.streak > 0 && h !== this.lastHash) {
386
+ this.reset();
387
+ this.lastHash = h;
388
+ return { action: "allow", streak: 0 };
389
+ }
390
+ this.lastHash = h;
391
+ this.streak += 1;
392
+ if (this.streak >= this.stopAfter)
393
+ return { action: "halt", streak: this.streak, message: POLL_SPIN_STOP };
394
+ if (this.streak >= this.nudgeAfter && !this.nudged) {
395
+ this.nudged = true;
396
+ return { action: "nudge", streak: this.streak, message: POLL_SPIN_NUDGE };
397
+ }
398
+ return { action: "allow", streak: this.streak };
399
+ }
400
+ }
401
+ // ── No-write-progress detector ───────────────────────────────────────────────
402
+ // Catches investigate-loops: consecutive rounds of tool calls where ZERO are mutating calls.
403
+ // The existing loop guard (identical-call, cycle, failure) evades this by varying args each round.
404
+ // This detector keys on the ABSENCE of progress, not on repetition. It is a round-level guard
405
+ // (fed one settled round at a time), not a per-call guard.
406
+ export const INVESTIGATE_LOOP_NUDGE = "You have made no write-progress in the last {n} rounds — only reads, searches, and status checks. " +
407
+ "If you can STATE the pattern, research is over — create something. Pick a direction and act on it.";
408
+ export const INVESTIGATE_LOOP_STOP = "[stopped — no write-progress in {n} consecutive rounds. You have been gathering context without producing output. " +
409
+ "Pick a direction and act on it, or end the turn.]";
410
+ /** Watches settled tool rounds for zero write-progress. Fed one round at a time via observe(); a
411
+ * mutating call resets the streak. Side-effect-free: the engine acts on the returned action.
412
+ * Hard-stop is unattended-only (warn for interactive). */
413
+ export class NoWriteProgressGuard {
414
+ warnAfter;
415
+ stopAfter;
416
+ unattended;
417
+ streak = 0;
418
+ warned = false;
419
+ constructor(warnAfter, stopAfter, unattended) {
420
+ this.warnAfter = warnAfter;
421
+ this.stopAfter = stopAfter;
422
+ this.unattended = unattended;
423
+ }
424
+ reset() { this.streak = 0; this.warned = false; }
425
+ /** One settled round: the tools it ran (names) and their results, index-aligned. */
426
+ observe(names) {
427
+ // Any write-progress call ⇒ progress, reset.
428
+ if (names.some((n) => WRITE_PROGRESS_TOOLS.has(n))) {
429
+ this.reset();
430
+ return { action: "allow", streak: 0 };
431
+ }
432
+ this.streak += 1;
433
+ if (this.streak >= this.stopAfter && this.unattended) {
434
+ return { action: "halt", streak: this.streak, message: INVESTIGATE_LOOP_STOP.replace("{n}", String(this.streak)) };
435
+ }
436
+ if (this.streak >= this.warnAfter && !this.warned) {
437
+ this.warned = true;
438
+ return { action: "warn", streak: this.streak, message: INVESTIGATE_LOOP_NUDGE.replace("{n}", String(this.streak)) };
439
+ }
440
+ return { action: "allow", streak: this.streak };
441
+ }
442
+ }
443
+ /** Text the turn ends with when the guard halts it. Plain, no internals; the prefix matches the engine's other
444
+ * stop notes so hosts and the learning loop treat it the same way. */
445
+ export function loopStopNote(d) {
446
+ return `[stopped — the loop guard ended this turn: ${d.message}. Repeating it unchanged was not making progress. ` +
447
+ `Nothing was lost; tell me how you'd like to proceed, or ask me to continue and I'll take a different approach.]`;
448
+ }
@@ -1,4 +1,8 @@
1
- const PROPOSER_TIMEOUT_MS = 60_000;
1
+ // Fan-out budget per proposer. 60s default: generous for a draft, hard enough that a contended
2
+ // JL1 slot times out gracefully instead of stalling the aggregator (measured 2026-10-12: same
3
+ // task 1.1s local vs 60s+ timeout on the shared lane). Env-overridable — heavy offline drafts on
4
+ // a slow link want more; JSC/mobile has no process, so this reads the same way agent.ts reads env.
5
+ const PROPOSER_TIMEOUT_MS = Math.min(600_000, Math.max(5_000, Number(globalThis.process?.env?.KODE_PROPOSER_TIMEOUT_MS) || 60_000));
2
6
  /** One proposer call: a plain (non-streaming, tool-free) OpenAI-compatible chat completion. Never
3
7
  * throws — a failure or timeout comes back as a draft with empty content + an `error`, so the
4
8
  * caller can drop it without the whole fan-out failing (a proposer is a nice-to-have, not a
@@ -0,0 +1,24 @@
1
+ // Turn-error text. A bare "[turn error: fetch failed]" tells the owner nothing about WHICH model or box was
2
+ // unreachable. For network-level failures (the request never got an HTTP answer) this appends the active
3
+ // model's label and the endpoint hosts that were tried, plus the one action that helps. The original message is
4
+ // never swallowed, and any other error renders exactly as before.
5
+ const NET_RE = /fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|socket hang up|network (?:error|request failed)/i;
6
+ export function isNetworkFailure(message) {
7
+ return NET_RE.test(message);
8
+ }
9
+ function hostOf(base) {
10
+ try {
11
+ return new URL(base).host;
12
+ }
13
+ catch {
14
+ return base.replace(/^https?:\/\//, "").replace(/\/.*$/, "");
15
+ }
16
+ }
17
+ export function describeTurnError(message, ctx = {}) {
18
+ if (!isNetworkFailure(message))
19
+ return `[turn error: ${message}]`;
20
+ const hosts = [...new Set((ctx.bases ?? []).map(hostOf))];
21
+ const who = ctx.label ? ` — ${ctx.label}: ` : " — ";
22
+ const tried = hosts.length > 1 ? `tried ${hosts.join(" → ")}, none reachable` : hosts.length === 1 ? `${hosts[0]} unreachable` : "endpoint unreachable";
23
+ return `[turn error: ${message}${who}${tried}; /model to switch]`;
24
+ }