neurastream 0.2.66 → 0.2.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -315,17 +315,11 @@ Then set `secrets.proxy: secretgate` and restart Main: `neurastream main` starts
315
315
 
316
316
  ## Provider rate limits
317
317
 
318
- When a Main turn ends on a provider rate limit, neurastream waits it out instead of asking again straight into the limit. The stop guard sees the turn's error text, matches it against `guards.rate_limit.patterns` (default `["429", "rate_limit", "rate limit", "overloaded", "529"]`, case-insensitive) and, on a hit, allows the stop without consulting the normal stop rules or touching the idle-stop counters. The chat channels get one post per episode — `⏳ Main is rate limited by its provider until HH:MM (local); it resumes on its own.` — and exactly one resume timer is armed (replacing any earlier one). When the wait is over, the plugin gives Main a new turn: `main-guard: the provider rate limit is over (waited until HH:MM). Continue the queue where you stopped.`, and the guard log carries the whole story:
318
+ When a Main turn ends on a provider rate limit, the stop guard matches the turn's error text against `guards.rate_limit.patterns` (default `["429", "rate_limit", "rate limit", "overloaded", "529"]`, case-insensitive), allows the stop without consulting the normal stop rules, and one episode opens. The chat channels get the first of exactly two posts: `⏳ Main hit its limit at HH:MM; resets at HH:MM` when the error text names a reset — a `retry-after-ms=<ms>` or `retry-after: <seconds>` the provider appended, or a timestamp it printed — or `⏳ Main hit its limit at HH:MM; checking every 5 min` when it names none.
319
319
 
320
- ```
321
- RATE-LIMIT stop: resume at 08:12 (35s, attempt 1)
322
- notify: posted (rate-limit)
323
- RATE-LIMIT resume: new turn sent (waited until 08:12)
324
- ```
325
-
326
- The wait is the `retry-after-ms=<ms>` or `retry-after: <seconds>` the error text names (omp appends the provider's header to the error message), else `default_wait_s` (300). A turn the resume started that ends on a limit again is the same episode at attempt 2: named retry-after values remain unchanged; only the default wait doubles, no second post. Any turn that ends without a limit ends the episode and disarms the timer. Every wait is clamped to `max_wait_s` (3600) before `slack_s` (15) is added on top. Your own message takes over and cancels the resume (`RATE-LIMIT resume cancelled: owner message`) when it starts a turn; a slash command or a handled input such as a chat unlock leaves the resume armed. A rate-limited deferred hand-back (an `agent_end` while an async job is pending) arms the same timer instead of logging "no reply text". The words and the waits live in `config.yml` (`guards.rate_limit`, `docs/config.md`); turns that did not end on a rate limit are unaffected.
320
+ A named reset is waited out (`slack_s`, default 15, added on top). An unnamed one is probed: a detached child runs `guards.rate_limit.probe_cmd` (default `omp -p --no-extensions --no-session --model {model} 'reply ok'`; `{model}` is replaced by the shell-quoted model, exit 0 = the provider answered) every `probe_interval_s` (default 300), killing any probe that runs longer than `probe_timeout_s` (default 90) — a killed or failing probe counts as still limited — up to `max_probes` (default 288 = 24 h at one probe per 5 min). When the named reset passes or a probe gets through, the plugin gives Main a new turn — `main-guard: the provider limit is over (back at HH:MM). Continue the queue where you stopped.` — and posts `✅ Main is back at HH:MM (limited N min, M checks)`; when `max_probes` is spent without an answer it posts `⚠ Main still limited after 24 h` once and closes the episode. Each finished episode appends one `{type: "limit", since, back_at, minutes, probes, reset_named}` metric, and the weekly report shows it as "Main limited: N h over K episodes". Posts, metric and report carry times and counts only, never the provider's error text.
327
321
 
328
- omp retries a 429 itself while the provider's wait fits its `retry.maxDelayMs` (300000 ms by default); only a longer wait ends the turn (`Retry failed after 1 attempts: Provider requested 731000ms wait, exceeds retry.maxDelayMs`), and that turn end is what neurastream waits out.
322
+ Your own message takes over and cancels the wait (`RATE-LIMIT tick cancelled: owner message (probe count kept)`) when it starts a turn; a slash command or a handled input such as a chat unlock leaves it armed. A rate-limited deferred hand-back does not open a second episode. omp itself retries a 429 while the provider's wait fits its `retry.maxDelayMs` (300000 ms by default); only a longer wait ends the turn (`Retry failed after 1 attempts: Provider requested 731000ms wait, exceeds retry.maxDelayMs`), and that turn end is what opens the episode.
329
323
 
330
324
  ## Provider reset times
331
325
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.66",
3
+ "version": "0.2.67",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -30,7 +30,9 @@ import { runDetectors, type DetectorInput } from "../../core/incident-detectors.
30
30
  import { fileClaimStore } from "../../core/claims.ts";
31
31
  import { appendOwnerAnswer, readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
32
32
  import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, mainId, mainStateDir, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
33
- import { rateLimitWait } from "../../core/rate-limit.ts";
33
+ import { rateLimited } from "../../core/rate-limit.ts";
34
+ import { backPost, clearLimitState, limitMetric, limitedPost, onLimited, readLimitState, timingOf, writeLimitState } from "../../core/limit-probe.ts";
35
+ import { appendMetric } from "../../core/metrics.ts";
34
36
  import { notifyProviders, ownerAnswerHandback, ownerAnswerSteer, postReply } from "../../core/notify.ts";
35
37
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
36
38
  import { inboxPath } from "../../core/owner-ui.ts";
@@ -40,7 +42,7 @@ import { actionsRules, ownedRepoOf, suspiciousActions, unreportedFindings } from
40
42
  import { applyQueueEnv } from "../../core/queue/env.ts";
41
43
  import { mainDetectors, mainStartText } from "../../core/main-start.ts";
42
44
 
43
- import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, unansweredOwnerMessages, withUnanswered, type RolloverState } from "../../core/rollover.ts";
45
+ import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, unansweredOwnerMessages, type RolloverState } from "../../core/rollover.ts";
44
46
  import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
45
47
  import { adapterLog, MAIN_ENV } from "./launch.ts";
46
48
  import { parseTraceFile } from "./traces.ts";
@@ -76,6 +78,7 @@ interface HostCtx {
76
78
  id?: string;
77
79
  cwd?: string;
78
80
  setInterval?: (cb: () => void, ms: number) => unknown;
81
+ spawnLimitProbe?: () => void;
79
82
  }
80
83
 
81
84
  function asRecord(v: unknown): Record<string, unknown> {
@@ -139,6 +142,9 @@ function asCtx(v: unknown): HostCtx {
139
142
  // Harness-injected timer with the original main-guard signature (ctx.setInterval).
140
143
  const interval = r.setInterval as ((cb: () => void, ms: number) => unknown) | undefined;
141
144
  if (typeof interval === "function") out.setInterval = interval;
145
+ // Harness-injected probe spawner (tests); the default starts the niced probe child.
146
+ const probe = r.spawnLimitProbe as (() => void) | undefined;
147
+ if (typeof probe === "function") out.spawnLimitProbe = probe;
142
148
  return out;
143
149
  }
144
150
 
@@ -353,14 +359,18 @@ function recordProviderOutFromTask(e: Record<string, unknown>, content: unknown[
353
359
  adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (task result)`);
354
360
  }
355
361
 
356
- /** Rate-limited turn end: record the reset time the error text names, else the armed wait. */
357
- function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs: number, cfg: Config): void {
358
- const provider = reply?.provider ?? providerOfModel(reply?.model ?? null);
359
- if (!provider) return;
362
+ /** Rate-limited turn end: record the reset time the error text names, else the armed wait. Returns the
363
+ * named reset in epoch ms (null when the text names none): the one parse of that text, which the call
364
+ * site passes on to the rate-limit episode (plan 20261027_1500 P2/P3). */
365
+ export function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs: number, cfg: Config): number | null {
360
366
  const named = reply ? resetEpochFromText(reply.errorMessage ?? "", resetRule(cfg)) : null;
361
- const epoch = named ?? Math.floor(untilMs / 1000);
362
- recordOut(cfg, provider, epoch, named !== null ? "rate-limit-reset" : "rate-limit");
363
- adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (${named !== null ? "reset time in error text" : "rate limit, no reset time"})`);
367
+ const provider = reply?.provider ?? providerOfModel(reply?.model ?? null);
368
+ if (provider) {
369
+ const epoch = named ?? Math.floor(untilMs / 1000);
370
+ recordOut(cfg, provider, epoch, named !== null ? "rate-limit-reset" : "rate-limit");
371
+ adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (${named !== null ? "reset time in error text" : "rate limit, no reset time"})`);
372
+ }
373
+ return named === null ? null : named * 1000;
364
374
  }
365
375
 
366
376
  // Session rollover helpers: the harness context read through runtime checks, and the file size and
@@ -595,6 +605,15 @@ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
595
605
 
596
606
  /** The most recently registered createOmpAdapter cleanup, for the exported reset(). */
597
607
  let activeAdapterReset: (() => void) | null = null;
608
+ /** The limit tick: one check of the open episode every 30 s (plan 20261027_1500 P3). */
609
+ const LIMIT_TICK_MS = 30_000;
610
+ /** One limit probe as a niced child (cli/limit-probe.ts). It writes the episode state itself;
611
+ * a failed start is logged and the next tick tries again. */
612
+ function spawnLimitProbeChild(cfg: Config): void {
613
+ const child = spawn("nice", ["-n", "19", process.execPath, join(import.meta.dir, "../../cli/limit-probe.ts")], { detached: true, stdio: "ignore", env: process.env });
614
+ child.on("error", err => adapterLog(cfg, `RATE-LIMIT probe: could not start: ${err.message}`));
615
+ child.unref();
616
+ }
598
617
  /** Register the guard handlers on one extension host. `initial` is injectable for tests; `freshConfig` re-reads the config per guarded call. */
599
618
  export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig: () => Config = () => initial): void {
600
619
  // Guarded handlers take `cfg = freshConfig()` first, so an edited config.yml reaches the next call (P4e).
@@ -643,24 +662,25 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
643
662
  // emits (sessionStopWillContinue) consumes it and posts nothing — a blocked stop's reply is a
644
663
  // mid-work report, never a hand-back.
645
664
  let stopBlocked = false;
646
- // Rate-limit wait-it-out (plan 20261025_0640): consecutive turn ends on a provider rate limit
647
- // form one episode. Named provider retry-after values remain authoritative; otherwise the
648
- // attempt doubles the default wait. The owner chat is told once per episode, and ONE timer
649
- // gives Main a new turn when the wait is over; a new Main turn before expiry takes over and
650
- // cancels it. Inputs that do not start a turn leave it armed. Any turn that ends without a
651
- // limit resets the episode and disarms it.
652
- let rateAttempt = 0;
653
- let rateTimer: NodeJS.Timeout | null = null;
665
+ // Rate-limit probe loop (plan 20261027_1500 P3). A limited turn end opens one episode in
666
+ // main-limit.json: a named reset is waited for; otherwise a niced probe child runs every
667
+ // probe_interval_s until one gets through or max_probes is spent. ONE tick (LIMIT_TICK_MS)
668
+ // reads the episode: it spawns a due probe, or, once the provider is back, sends Main ONE new
669
+ // turn. A new Main turn cancels the tick and keeps the episode (probe count kept); a turn that
670
+ // ends without a limit clears it.
671
+ let limitTickArmed = false;
672
+ let limitTick: NodeJS.Timeout | null = null;
654
673
  const rateClock = (ms: number): string => strftime(ms / 1000, "%H:%M");
655
- const clearRateTimer = (): void => {
656
- if (rateTimer !== null) {
657
- clearTimeout(rateTimer);
658
- rateTimer = null;
674
+ const stopLimitTick = (): void => {
675
+ limitTickArmed = false;
676
+ if (limitTick !== null) {
677
+ clearInterval(limitTick);
678
+ limitTick = null;
659
679
  }
660
680
  };
661
681
  const disarmRateEpisode = (): void => {
662
- clearRateTimer();
663
- rateAttempt = 0;
682
+ stopLimitTick();
683
+ clearLimitState(cfg);
664
684
  };
665
685
  // P5b: a real turn end answers every owner message it followed — the answer (the turn's own
666
686
  // reply, the page's lastAnswerFor shape) rides the same owner-message store. Rate-limited,
@@ -673,32 +693,69 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
673
693
  adapterLog(cfg, `OWNER-ANSWER record failed: ${err instanceof Error ? err.message : String(err)}`);
674
694
  }
675
695
  };
676
- // The one resume: replacing any armed timer, exactly one new user message when the wait is over.
677
- const armRateResume = (untilMs: number): void => {
678
- clearRateTimer();
679
- rateTimer = setTimeout(() => {
680
- rateTimer = null;
681
- // P5b: whichever resume text exists, it quotes owner messages no turn has answered.
682
- pi.sendUserMessage(withUnanswered(`main-guard: the provider rate limit is over (waited until ${rateClock(untilMs)}). Continue the queue where you stopped.`, readOwnerMessages(), readOwnerAnswers()));
683
- adapterLog(cfg, `RATE-LIMIT resume: new turn sent (waited until ${rateClock(untilMs)})`);
684
- }, untilMs - Date.now());
696
+ const limitTickFire = (c: HostCtx): void => {
697
+ if (!limitTickArmed) return;
698
+ const state = readLimitState(cfg);
699
+ if (state === null) {
700
+ stopLimitTick();
701
+ adapterLog(cfg, "RATE-LIMIT give up: episode state gone (max_probes spent or unreadable)");
702
+ return;
703
+ }
704
+ const now = Date.now();
705
+ if (state.back_at !== null) {
706
+ if (now < state.back_at) return;
707
+ stopLimitTick();
708
+ clearLimitState(cfg);
709
+ // P4: the finished episode is recorded once and the owner hears one back post; both are
710
+ // times and counts only — the episode's last_error never reaches chat or ledger.
711
+ appendMetric(cfg, limitMetric(state, now));
712
+ adapterLog(cfg, `RATE-LIMIT back: provider limit over (back at ${rateClock(state.back_at)}); new turn sent`);
713
+ void postReply(backPost(state), cfg).then(results => {
714
+ for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
715
+ });
716
+ pi.sendUserMessage(`main-guard: the provider limit is over (back at ${rateClock(state.back_at)}). Continue the queue where you stopped.`);
717
+ return;
718
+ }
719
+ if (now < state.next_probe_at) return;
720
+ (c.spawnLimitProbe ?? (() => spawnLimitProbeChild(cfg)))();
721
+ };
722
+ const armLimitTick = (c: HostCtx): void => {
723
+ stopLimitTick();
724
+ limitTickArmed = true;
725
+ const t: unknown = c.setInterval ? c.setInterval(() => limitTickFire(c), LIMIT_TICK_MS) : setInterval(() => limitTickFire(c), LIMIT_TICK_MS);
726
+ if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
727
+ limitTick = t as NodeJS.Timeout;
685
728
  };
686
- // A turn that ended on a rate limit: log, tell the owner once per episode, arm the resume.
687
- const onRateLimitedStop = (untilMs: number, waitMs: number): void => {
688
- rateAttempt++;
689
- const at = rateClock(untilMs);
690
- adapterLog(cfg, `RATE-LIMIT stop: resume at ${at} (${Math.round(waitMs / 1000)}s, attempt ${rateAttempt})`);
691
- if (rateAttempt === 1) {
729
+ // A turn that ended on a provider rate limit: the episode opens (or continues with its probe
730
+ // count), the owner chat hears once per episode, and the tick takes over.
731
+ const onRateLimitedStop = (c: HostCtx, namedResetMs: number | null, errorText: string, model: string): void => {
732
+ const prev = readLimitState(cfg);
733
+ const timing = timingOf(cfg);
734
+ const state = onLimited(prev, namedResetMs, errorText, Date.now(), model, timing);
735
+ try {
736
+ writeLimitState(cfg, state);
737
+ } catch (err) {
738
+ adapterLog(cfg, `RATE-LIMIT state write failed: ${err instanceof Error ? err.message : String(err)}`);
739
+ return;
740
+ }
741
+ adapterLog(cfg, `RATE-LIMIT stop: ${state.reset_named ? "named reset" : "probe"} at ${rateClock(state.next_probe_at)} (probes ${state.probes} of ${timing.max_probes})`);
742
+ if (prev === null) {
692
743
  adapterLog(cfg, "notify: posted (rate-limit)");
693
- void postReply(`⏳ Main is rate limited by its provider until ${at} (local); it resumes on its own.`, cfg).then(results => {
744
+ void postReply(limitedPost(state, timing.probe_interval_s), cfg).then(results => {
694
745
  for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
695
746
  });
696
747
  }
697
- armRateResume(untilMs);
748
+ armLimitTick(c);
749
+ };
750
+ // The rate-limit decision for one turn end, from the event's own last assistant message. The
751
+ // untilMs is the fallback wait recorded with PROVIDER-OUT when the error text names no reset.
752
+ const rateLimitOf = (reply: EventReply | null): { untilMs: number } | null => {
753
+ const rl = cfg.guards.rate_limit;
754
+ const hit = rateLimited(reply?.stopReason ?? null, reply?.errorMessage ?? null, rl);
755
+ if (!hit) return null;
756
+ const waitMs = (hit.retryAfterMs ?? rl.probe_interval_s * 1000) + rl.slack_s * 1000;
757
+ return { untilMs: Date.now() + waitMs };
698
758
  };
699
- // The rate-limit decision for one turn end, from the event's own last assistant message.
700
- const rateLimitOf = (reply: EventReply | null): { untilMs: number; waitMs: number } | null =>
701
- rateLimitWait(reply?.stopReason ?? null, reply?.errorMessage ?? null, Date.now(), cfg.guards.rate_limit, rateAttempt + 1);
702
759
  // One guard-log line per notify decision: `notify: posted|skipped (<why>)`. Fire-and-forget:
703
760
  // the decision never awaits the post; a failed or slow post logs one line and never blocks
704
761
  // or retries.
@@ -871,9 +928,9 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
871
928
  const content = unhanded(asString(c.id) || "sub", plans.find(file => prompt.includes(file)) ?? null);
872
929
  return content ? { message: { customType: "main-guard.rules", content, display: false } } : undefined;
873
930
  }
874
- if (rateTimer !== null) {
875
- clearRateTimer();
876
- adapterLog(cfg, "RATE-LIMIT resume cancelled: owner message");
931
+ if (limitTickArmed) {
932
+ stopLimitTick();
933
+ adapterLog(cfg, "RATE-LIMIT tick cancelled: owner message (probe count kept)");
877
934
  }
878
935
  const d = checkInject({ inject: prompt, agent: "main" }, cfg);
879
936
  callsSinceStop = d.state?.callsSinceStop ?? callsSinceStop;
@@ -1133,13 +1190,14 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1133
1190
  const rl = rateLimitOf(reply);
1134
1191
  if (rl) {
1135
1192
  // Who is rate-limited is live data (plan 20261025_1700 P1): the error text's own reset
1136
- // time, else the armed wait. Best effort — a failed write never changes the stop.
1193
+ // time, else the fallback wait. Best effort — a failed write never changes the stop.
1194
+ let named: number | null = null;
1137
1195
  try {
1138
- recordProviderOutFromRateLimit(reply, rl.untilMs, cfg);
1196
+ named = recordProviderOutFromRateLimit(reply, rl.untilMs, cfg);
1139
1197
  } catch (err) {
1140
1198
  adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
1141
1199
  }
1142
- onRateLimitedStop(rl.untilMs, rl.waitMs);
1200
+ onRateLimitedStop(c, named, reply?.errorMessage ?? "", reply?.model ?? "");
1143
1201
  return undefined;
1144
1202
  }
1145
1203
  // Any turn that ends without a rate limit ends the episode and disarms its resume timer.
@@ -1302,7 +1360,10 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1302
1360
  };
1303
1361
  // Clear the previous adapter's armed grace timer before this one overwrites the pointer (P3c).
1304
1362
  activeAdapterReset?.();
1305
- activeAdapterReset = clearRolloverState;
1363
+ activeAdapterReset = (): void => {
1364
+ clearRolloverState();
1365
+ stopLimitTick();
1366
+ };
1306
1367
  // The launcher restarts omp: the request file carries the note and the editor draft, and omp
1307
1368
  // shuts down only after the file is written. A failed write keeps the session running.
1308
1369
  // Returns whether the request was written.
@@ -1395,12 +1456,20 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1395
1456
  }
1396
1457
  const reply = lastAssistantIn(asRecord(e).messages);
1397
1458
  // The same rate-limit check as session_stop (plan 20261025_0640): a rate-limited deferred
1398
- // hand-back arms the resume timer instead of logging "no reply text" — its reply carries an
1459
+ // hand-back opens the episode instead of logging "no reply text" — its reply carries an
1399
1460
  // error, no text. A mid-run continuation (tool calls, auto-retry) is not a turn end: the
1400
1461
  // episode state stays as it is.
1401
1462
  const rl = rateLimitOf(reply);
1402
1463
  if (rl) {
1403
- onRateLimitedStop(rl.untilMs, rl.waitMs);
1464
+ // The same one parse as session_stop (plan 20261027_1500 P1/P3): the error text's own
1465
+ // reset time, else the fallback wait. Best effort — a failed write never changes the stop.
1466
+ let named: number | null = null;
1467
+ try {
1468
+ named = recordProviderOutFromRateLimit(reply, rl.untilMs, cfg);
1469
+ } catch (err) {
1470
+ adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
1471
+ }
1472
+ onRateLimitedStop(asCtx(ctx), named, reply?.errorMessage ?? "", reply?.model ?? "");
1404
1473
  return;
1405
1474
  }
1406
1475
  const jobCount = asRolloverCtx(ctx)?.runningJobs().length ?? 0;
@@ -0,0 +1,11 @@
1
+ // One tick of the main-agent limit probe (plan 20261027_1500, P3). The adapter spawns this detached
2
+ // every probe_interval_s while an episode is open; it runs at most one probe and exits. A give-up
3
+ // posts the ⚠ to the owner chat (P4), so the serial notify queue is drained before exit.
4
+
5
+ import { loadConfig } from "../core/config.ts";
6
+ import { probeStep } from "../core/limit-probe.ts";
7
+ import { notifyIdle } from "../core/notify.ts";
8
+
9
+ const cfg = loadConfig();
10
+ probeStep(cfg, Date.now());
11
+ await notifyIdle();
@@ -134,16 +134,20 @@ export interface Config {
134
134
  idle_stops: number;
135
135
  /** A Main stop reply matching this regex (case-insensitive) offers to plan instead of planning; the stop is refused (20261028_0900 P2). */
136
136
  plan_offer: string;
137
- /** Provider rate limits (src/core/rate-limit.ts): a turn that ends on one waits it out instead of
138
- * asking again straight into the limit. The words and the waits come from here. */
137
+ /** Provider rate limits (src/core/rate-limit.ts, src/core/limit-probe.ts): a turn that ends on one waits for the
138
+ * named reset, or probes the provider until it answers. The words and the timings come from here. */
139
139
  rate_limit: {
140
140
  /** Case-insensitive substrings in the error text that mark a rate limit. */
141
141
  patterns: string[];
142
- /** Wait when the error text names no retry-after. */
143
- default_wait_s: number;
144
- /** Cap for the parsed (or doubled) wait, before slack. */
145
- max_wait_s: number;
146
- /** Added on top of every wait. */
142
+ /** Probe the provider this often (s) while it names no reset. */
143
+ probe_interval_s: number;
144
+ /** Probes before the episode gives up. */
145
+ max_probes: number;
146
+ /** Kill a probe that runs longer than this (s). */
147
+ probe_timeout_s: number;
148
+ /** Shell command that probes the provider; {model} is replaced by the shell-quoted model. Exit 0 means it answered. */
149
+ probe_cmd: string;
150
+ /** Added on top of every wait (s). */
147
151
  slack_s: number;
148
152
  };
149
153
  blocker_timeout_ms: number;
@@ -581,8 +585,12 @@ function check(cfg: Config): void {
581
585
  if (!Array.isArray(cfg.guards.rate_limit.patterns) || cfg.guards.rate_limit.patterns.some(p => typeof p !== "string" || p === "")) {
582
586
  throw new ConfigError("guards.rate_limit.patterns must be a list of non-empty strings");
583
587
  }
584
- if (!(cfg.guards.rate_limit.default_wait_s >= 1)) throw new ConfigError("guards.rate_limit.default_wait_s must be >= 1");
585
- if (!(cfg.guards.rate_limit.max_wait_s >= 1)) throw new ConfigError("guards.rate_limit.max_wait_s must be >= 1");
588
+ if (!(cfg.guards.rate_limit.probe_interval_s >= 1)) throw new ConfigError("guards.rate_limit.probe_interval_s must be >= 1");
589
+ if (!(cfg.guards.rate_limit.max_probes >= 1)) throw new ConfigError("guards.rate_limit.max_probes must be >= 1");
590
+ if (!(cfg.guards.rate_limit.probe_timeout_s >= 1)) throw new ConfigError("guards.rate_limit.probe_timeout_s must be >= 1");
591
+ if (typeof cfg.guards.rate_limit.probe_cmd !== "string" || !cfg.guards.rate_limit.probe_cmd.includes("{model}")) {
592
+ throw new ConfigError("guards.rate_limit.probe_cmd must be a string containing {model}");
593
+ }
586
594
  if (!(cfg.guards.rate_limit.slack_s >= 0)) throw new ConfigError("guards.rate_limit.slack_s must be >= 0");
587
595
  if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
588
596
  if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
@@ -0,0 +1,225 @@
1
+ // The probe loop (plan 20261027_1500, P2): when the provider rate-limits the main agent, wait for
2
+ // the named reset if the provider gave one; otherwise probe it every probe_interval_s until it
3
+ // answers, up to max_probes. The state transitions are pure (onLimited, onProbe); runProbe runs the
4
+ // configured probe command under the main-limit lock. The episode file (main-limit.json) and
5
+ // probeStep (one tick of the loop) live here too. Harness-neutral: nothing here names a harness or a provider.
6
+
7
+ import { spawnSync } from "node:child_process";
8
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
9
+ import { dirname, join } from "node:path";
10
+ import type { Config } from "./config.ts";
11
+ import { strftime } from "./clock.ts";
12
+ import { tryLock } from "./file-lock.ts";
13
+ import { appendMetric } from "./metrics.ts";
14
+ import { postReply } from "./notify.ts";
15
+ import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
16
+
17
+ /** One rate-limit episode of the main agent. Times are epoch ms. */
18
+ export interface LimitState {
19
+ since: number;
20
+ model: string;
21
+ reset_named: boolean;
22
+ next_probe_at: number;
23
+ probes: number;
24
+ last_error: string;
25
+ back_at: number | null;
26
+ }
27
+
28
+ export interface ProbeTiming {
29
+ probe_interval_s: number;
30
+ max_probes: number;
31
+ slack_s: number;
32
+ }
33
+
34
+ export type ProbeOutcome = { kind: "resume" } | { kind: "again"; at: number } | { kind: "give_up" };
35
+
36
+ export interface ProbeStep {
37
+ state: LimitState;
38
+ outcome: ProbeOutcome;
39
+ }
40
+
41
+ export interface ProbeResult {
42
+ ok: boolean;
43
+ exitCode: number | null;
44
+ stderr: string;
45
+ }
46
+
47
+ export type ProbeRunner = (
48
+ file: string,
49
+ args: string[],
50
+ opts: { timeout: number },
51
+ ) => { status: number | null; stderr: string; error?: Error };
52
+
53
+ const defaultRun: ProbeRunner = (file, args, opts) => spawnSync(file, args, { ...opts, encoding: "utf8" as const });
54
+
55
+ const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
56
+
57
+ /**
58
+ * The main agent was rate-limited at `now`. A named reset (epoch ms) is waited for, plus slack;
59
+ * without one the first probe comes after probe_interval_s.
60
+ */
61
+ export function onLimited(
62
+ state: LimitState | null,
63
+ namedResetMs: number | null,
64
+ errorText: string,
65
+ now: number,
66
+ model: string,
67
+ timing: ProbeTiming,
68
+ ): LimitState {
69
+ const named = namedResetMs !== null;
70
+ const next = named ? namedResetMs + timing.slack_s * 1000 : now + timing.probe_interval_s * 1000;
71
+ return {
72
+ since: state?.since ?? now,
73
+ model,
74
+ reset_named: named,
75
+ next_probe_at: next,
76
+ probes: state?.probes ?? 0,
77
+ last_error: errorText,
78
+ back_at: named ? next : null,
79
+ };
80
+ }
81
+
82
+ /**
83
+ * A probe finished at `now`. Every probe counts. A successful probe resumes; a failed one probes
84
+ * again after probe_interval_s until max_probes is reached, then gives up.
85
+ */
86
+ export function onProbe(state: LimitState, ok: boolean, errorText: string, now: number, timing: ProbeTiming): ProbeStep {
87
+ const probes = state.probes + 1;
88
+ if (ok) return { state: { ...state, probes }, outcome: { kind: "resume" } };
89
+ if (probes >= timing.max_probes) {
90
+ return { state: { ...state, probes, last_error: errorText }, outcome: { kind: "give_up" } };
91
+ }
92
+ const at = now + timing.probe_interval_s * 1000;
93
+ return { state: { ...state, probes, last_error: errorText, next_probe_at: at }, outcome: { kind: "again", at } };
94
+ }
95
+
96
+ /**
97
+ * Run guards.rate_limit.probe_cmd once, with {model} replaced by the shell-quoted model, under the
98
+ * main-limit lock. Returns "busy" when another probe holds the lock. The output is never logged in
99
+ * full: stderr is redacted, then cut to 200 characters.
100
+ */
101
+ export function runProbe(cfg: Config, model: string, run: ProbeRunner = defaultRun): ProbeResult | "busy" {
102
+ const lock = tryLock(join(cfg.paths.queue_state, "main-limit.lock"));
103
+ if (!lock) return "busy";
104
+ try {
105
+ const rl = cfg.guards.rate_limit;
106
+ const cmd = rl.probe_cmd.replaceAll("{model}", shellQuote(model));
107
+ const r = run("sh", ["-c", cmd], { timeout: rl.probe_timeout_s * 1000 });
108
+ const stderr = redactSecrets(r.stderr, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text.slice(0, 200);
109
+ return { ok: r.status === 0 && !r.error, exitCode: r.status, stderr };
110
+ } finally {
111
+ lock.release();
112
+ }
113
+ }
114
+
115
+ /** Where the open episode lives: one JSON file in queue_state, replaced atomically. */
116
+ export function limitStatePath(cfg: Config): string {
117
+ return join(cfg.paths.queue_state, "main-limit.json");
118
+ }
119
+
120
+ /** The open episode, or null when there is none (or the file cannot be parsed). */
121
+ export function readLimitState(cfg: Config): LimitState | null {
122
+ try {
123
+ return JSON.parse(readFileSync(limitStatePath(cfg), "utf8")) as LimitState;
124
+ } catch {
125
+ return null;
126
+ }
127
+ }
128
+
129
+ export function writeLimitState(cfg: Config, state: LimitState): void {
130
+ const path = limitStatePath(cfg);
131
+ mkdirSync(dirname(path), { recursive: true });
132
+ writeFileSync(`${path}.tmp`, `${JSON.stringify(state)}\n`);
133
+ renameSync(`${path}.tmp`, path);
134
+ }
135
+
136
+ export function clearLimitState(cfg: Config): void {
137
+ rmSync(limitStatePath(cfg), { force: true });
138
+ }
139
+
140
+ export function timingOf(cfg: Config): ProbeTiming {
141
+ const rl = cfg.guards.rate_limit;
142
+ return { probe_interval_s: rl.probe_interval_s, max_probes: rl.max_probes, slack_s: rl.slack_s };
143
+ }
144
+
145
+ /**
146
+ * One tick of the probe loop at `now`. Returns "idle" when no episode is open, the episode is
147
+ * already back, or the next probe is not due; "busy" when another probe holds the lock. Otherwise
148
+ * runs one probe and records its outcome. A give-up closes the episode: one ⚠ post to the owner
149
+ * chat (via `notify`, default the redacting postReply) and one `limit` metric. If the episode was
150
+ * closed (turn-end disarm) or replaced while the probe ran, the result is dropped instead of
151
+ * written back. A resume only marks the episode back — the adapter's tick posts the ✅ and the
152
+ * metric when it sends Main's new turn.
153
+ */
154
+ export function probeStep(
155
+ cfg: Config,
156
+ now: number,
157
+ run: ProbeRunner = defaultRun,
158
+ notify: (text: string) => void = (text) => {
159
+ void postReply(text, cfg);
160
+ },
161
+ ): "idle" | "busy" | ProbeOutcome["kind"] {
162
+ const st = readLimitState(cfg);
163
+ if (!st || st.back_at !== null || now < st.next_probe_at) return "idle";
164
+ const r = runProbe(cfg, st.model, run);
165
+ if (r === "busy") return "busy";
166
+ const current = readLimitState(cfg);
167
+ if (!current || current.since !== st.since) return "idle";
168
+ const timing = timingOf(cfg);
169
+ const step = onProbe(current, r.ok, r.stderr, now, timing);
170
+ if (step.outcome.kind === "give_up") {
171
+ clearLimitState(cfg);
172
+ appendMetric(cfg, limitMetric(step.state, now));
173
+ notify(giveUpPost(timing));
174
+ } else if (step.outcome.kind === "resume") writeLimitState(cfg, { ...step.state, back_at: now });
175
+ else writeLimitState(cfg, step.state);
176
+ return step.outcome.kind;
177
+ }
178
+
179
+ // ---- P4 tell + record: the owner-facing texts and the metric record of a finished episode ----
180
+ // Every text here is built from times and counts only; the error text in LimitState.last_error is
181
+ // unredacted, so no builder takes it — a post, the metric and the report line cannot carry it.
182
+
183
+ /** Minutes the main agent has been limited, from `since` to the episode's end. */
184
+ function limitedMinutes(state: LimitState, now: number): number {
185
+ return Math.max(0, Math.round(((state.back_at ?? now) - state.since) / 60000));
186
+ }
187
+
188
+ /** A duration in whole units the owner reads at a glance: "24 h", "15 min", "5 s". */
189
+ function durationText(seconds: number): string {
190
+ if (seconds >= 3600) return `${Math.round(seconds / 360) / 10} h`;
191
+ if (seconds >= 60) return `${Math.round(seconds / 60)} min`;
192
+ return `${seconds} s`;
193
+ }
194
+
195
+ const clockHM = (ms: number): string => strftime(ms / 1000, "%H:%M");
196
+
197
+ /** The post when an episode opens: a named reset announces when it lifts, an unnamed one the probe cadence. */
198
+ export function limitedPost(state: LimitState, interval_s: number): string {
199
+ const at = clockHM(state.since);
200
+ return state.reset_named
201
+ ? `⏳ Main hit its limit at ${at}; resets at ${clockHM(state.next_probe_at)}`
202
+ : `⏳ Main hit its limit at ${at}; checking every ${durationText(interval_s)}`;
203
+ }
204
+
205
+ /** The post when the provider answered or the named reset passed: times and counts only. */
206
+ export function backPost(state: LimitState): string {
207
+ return `✅ Main is back at ${clockHM(state.back_at!)} (limited ${limitedMinutes(state, state.back_at!)} min, ${state.probes} checks)`;
208
+ }
209
+
210
+ /** The post when max_probes is spent without an answer. */
211
+ export function giveUpPost(timing: ProbeTiming): string {
212
+ return `⚠ Main still limited after ${durationText(timing.max_probes * timing.probe_interval_s)}`;
213
+ }
214
+
215
+ /** The metric record of one finished episode: numbers and a boolean, never the error text. */
216
+ export function limitMetric(state: LimitState, now: number): Record<string, unknown> {
217
+ return {
218
+ type: "limit",
219
+ since: state.since,
220
+ back_at: state.back_at,
221
+ minutes: limitedMinutes(state, now),
222
+ probes: state.probes,
223
+ reset_named: state.reset_named,
224
+ };
225
+ }
@@ -209,6 +209,13 @@ const enqueuePost = <T>(operation: () => Promise<T>): Promise<T> => {
209
209
  return result;
210
210
  }
211
211
 
212
+ /** Resolves once every post enqueued so far has finished. Posts are fire-and-forget for callers;
213
+ * tests drain the queue before clearing their hit lists, so one test's late post never lands in
214
+ * the next test's window. */
215
+ export function notifyIdle(): Promise<void> {
216
+ return postQueue;
217
+ }
218
+
212
219
  /** Post Main's final reply to every configured provider, serially across calls. 429s retry once
213
220
  * after Discord's requested delay (capped at 10 seconds); other failures return to the caller. */
214
221
  export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]> {
@@ -1,65 +1,37 @@
1
- // Provider rate limits (plan 20261025_0640): a turn that ended on one waits it out instead of
2
- // asking again straight into the limit. Pure decisions only: what counts as a rate limit, and how
3
- // long to wait. The words and the waits come from config (guards.rate_limit); the adapter supplies
4
- // the turn's stop reason and error text and arms the timer.
1
+ // Provider rate limits (plan 20261025_0640, reshaped by 20261027_1500 P2): a turn that ended on a
2
+ // rate limit is recognised here; what happens next (a named wait or probing the provider) is decided
3
+ // by the adapter and src/core/limit-probe.ts. Pure: what counts as a rate limit, and the retry-after
4
+ // the provider names. The words come from config (guards.rate_limit); the adapter supplies the turn's
5
+ // stop reason and error text.
5
6
 
6
7
  export interface RateLimitConfig {
7
8
  /** Case-insensitive substrings in the error text that mark a rate limit. */
8
9
  patterns: string[];
9
- /** Wait when the error text names no retry-after. */
10
- default_wait_s: number;
11
- /** Cap for the parsed (or doubled) wait, before slack. */
12
- max_wait_s: number;
13
- /** Added on top of every wait. */
14
- slack_s: number;
15
10
  }
16
11
 
17
- export interface RateLimitWait {
18
- /** Epoch ms when the next turn should start. */
19
- untilMs: number;
20
- /** Total wait in ms, slack included. */
21
- waitMs: number;
12
+ export interface RateLimited {
13
+ /** The provider's named retry-after in ms, or null when the error text names none. */
14
+ retryAfterMs: number | null;
22
15
  }
23
16
 
24
17
  const RETRY_AFTER_MS = /retry-after-ms[=:]\s*(\d+)/i;
25
18
  const RETRY_AFTER_S = /retry-after[=:]\s*(\d+)/i;
26
19
 
27
- function retryAfterMs(errorText: string, cfg: RateLimitConfig): { ms: number; named: boolean } {
20
+ function namedRetryAfterMs(errorText: string): number | null {
28
21
  const ms = RETRY_AFTER_MS.exec(errorText);
29
- if (ms) return { ms: Number(ms[1]), named: true };
22
+ if (ms) return Number(ms[1]);
30
23
  const s = RETRY_AFTER_S.exec(errorText);
31
- if (s) return { ms: Number(s[1]) * 1000, named: true };
32
- return { ms: cfg.default_wait_s * 1000, named: false };
24
+ if (s) return Number(s[1]) * 1000;
25
+ return null;
33
26
  }
34
27
 
35
28
  /**
36
- * The wait for a turn that ended on a provider rate limit, or null when it did not: the stop
37
- * reason must be "error" and the error text must contain one of the configured patterns
38
- * (case-insensitive). A named retry-after is used as-is; otherwise default_wait_s is doubled
39
- * for each later attempt. The resulting wait is clamped to max_wait_s, then slack_s is added.
29
+ * The rate limit a turn ended on, or null when it did not: the stop reason must be "error" and the
30
+ * error text must contain one of the configured patterns (case-insensitive).
40
31
  */
41
- export function rateLimitWait(
42
- stopReason: string | null,
43
- errorText: string | null,
44
- now: number,
45
- cfg: RateLimitConfig,
46
- attempt: number,
47
- ): RateLimitWait | null {
32
+ export function rateLimited(stopReason: string | null, errorText: string | null, cfg: RateLimitConfig): RateLimited | null {
48
33
  if (stopReason !== "error" || !errorText) return null;
49
34
  const text = errorText.toLowerCase();
50
35
  if (!cfg.patterns.some(p => text.includes(p.toLowerCase()))) return null;
51
- const capMs = cfg.max_wait_s * 1000;
52
- const retryAfter = retryAfterMs(errorText, cfg);
53
- let baseMs = retryAfter.ms;
54
- if (!retryAfter.named) {
55
- for (let i = 1; i < Math.max(1, attempt); i++) {
56
- baseMs *= 2;
57
- if (baseMs >= capMs) {
58
- baseMs = capMs;
59
- break;
60
- }
61
- }
62
- }
63
- const waitMs = Math.min(baseMs, capMs) + cfg.slack_s * 1000;
64
- return { untilMs: now + waitMs, waitMs };
36
+ return { retryAfterMs: namedRetryAfterMs(errorText) };
65
37
  }
@@ -292,10 +292,18 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
292
292
  }),
293
293
  ];
294
294
  const falseAlarms = events.filter((e) => e.type === "false-alarm" && inWindow(Number(e.ts), cur)).length;
295
+ // Plan 20261027_1500 P4: finished main-agent limit episodes, one line over the window. The
296
+ // metric record is numbers + a boolean, but read only the pinned fields here, so a stray
297
+ // last_error can never reach the report.
298
+ const limitEvents = events.filter((e) => e.type === "limit" && inWindow(Number(e.since) / 1000, cur));
299
+ const limitMinutes = limitEvents.reduce((n, e) => n + Number(e.minutes ?? 0), 0);
295
300
  const noisy = noisyDetectors(incidents, cur, cfg.watch);
296
301
  const quality = [
297
302
  `Silent failures: ${silentFailures(incidents, cur)} watch incidents; suspected false blocks: ${m7(incidents, falseAlarms, cur)}`,
298
303
  `Flaky jobs: ${events.filter((e) => e.type === "ci-flaky" && inWindow(Number(e.ts), cur)).length} same-commit red→green re-runs`,
304
+ ...(limitEvents.length > 0
305
+ ? [`Main limited: ${limitMinutes >= 60 ? `${Math.round(limitMinutes / 6) / 10} h` : `${limitMinutes} min`} over ${limitEvents.length} episodes`]
306
+ : []),
299
307
  "Dismiss rate by kind (opened, planned, dismissed):",
300
308
  ...kindStats(incidents, cur).map((k) => `- ${k.kind}: ${k.opened}, ${k.planned}, ${k.dismissed} (${Math.round(k.dismissRate * 100)}% dismissed)`),
301
309
  ];
@@ -131,9 +131,11 @@ guards:
131
131
  plan_offer: 'want me to (write|make) a plan|should i plan|shall i plan|if you want, i(''ll)? plan|plan it or|\bi will\b|\bi(''|’)ll\b' # refused: don't promise or offer it — do it now, or write the plan and index it
132
132
  rate_limit:
133
133
  patterns: ["429", "rate_limit", "rate limit", "overloaded", "529"] # error-text substrings (case-insensitive) that mark a provider rate limit
134
- default_wait_s: 300 # wait when the error text names no retry-after
135
- max_wait_s: 3600 # cap for the parsed (or doubled) wait, before slack
136
134
  slack_s: 15 # added on top of every wait
135
+ probe_interval_s: 300 # probe the provider this often (s) while it names no reset
136
+ max_probes: 288 # probes before the episode gives up (288 x 300 s = 24 h)
137
+ probe_timeout_s: 90 # kill a probe that runs longer than this (s)
138
+ probe_cmd: "omp -p --no-extensions --no-session --model {model} 'reply ok'" # {model} is replaced by the shell-quoted model; exit 0 = the provider answered
137
139
  blocker_timeout_ms: 10000 # timeout for blocker checks in milliseconds
138
140
  skip_tools: [todo, wait, ask, web_search, job, cancel_job] # tools the guard never counts
139
141
  read_tools: [read, grep, glob, find] # tools counted as reads