neurastream 0.3.20 → 0.3.21

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 (49) hide show
  1. package/package.json +1 -1
  2. package/src/adapters/index.ts +3 -2
  3. package/src/adapters/omp/adapter.ts +2 -1
  4. package/src/adapters/omp/auto-close.ts +64 -0
  5. package/src/adapters/omp/chat-commands.ts +161 -0
  6. package/src/adapters/omp/inbox.ts +221 -0
  7. package/src/adapters/omp/index.ts +115 -1039
  8. package/src/adapters/omp/launch.ts +31 -3
  9. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  10. package/src/adapters/omp/rollover-controller.ts +334 -0
  11. package/src/adapters/omp/types.ts +143 -0
  12. package/src/cli/commands.ts +33 -2
  13. package/src/cli/dispatch.ts +37 -16
  14. package/src/cli/recall.ts +3 -2
  15. package/src/cli/results-build.ts +1 -1
  16. package/src/cli/workspace.ts +13 -2
  17. package/src/core/adapter.ts +16 -0
  18. package/src/core/blockers.ts +326 -30
  19. package/src/core/file-lock.ts +71 -12
  20. package/src/core/guards/plan-edit.ts +338 -0
  21. package/src/core/guards/planner.ts +70 -0
  22. package/src/core/guards/review.ts +391 -0
  23. package/src/core/guards/spawn.ts +699 -0
  24. package/src/core/guards/state.ts +581 -0
  25. package/src/core/guards/stop.ts +235 -0
  26. package/src/core/guards/tool.ts +541 -0
  27. package/src/core/guards.ts +12 -2658
  28. package/src/core/incidents.ts +125 -91
  29. package/src/core/machine-guard.ts +23 -5
  30. package/src/core/main-start.ts +10 -8
  31. package/src/core/owner-topics.ts +2 -13
  32. package/src/core/owner-ui/auth.ts +164 -0
  33. package/src/core/owner-ui/data.ts +437 -0
  34. package/src/core/owner-ui/handlers.ts +250 -0
  35. package/src/core/owner-ui/messages.ts +209 -0
  36. package/src/core/owner-ui/render.ts +714 -0
  37. package/src/core/owner-ui/results.ts +266 -0
  38. package/src/core/owner-ui/server.ts +142 -0
  39. package/src/core/owner-ui.ts +11 -2121
  40. package/src/core/page-notes.ts +25 -0
  41. package/src/core/pages.ts +452 -77
  42. package/src/core/plan-approval.ts +12 -14
  43. package/src/core/queue/lib.ts +88 -39
  44. package/src/core/queue-cancel.ts +21 -17
  45. package/src/core/queue-close.ts +48 -23
  46. package/src/core/secret-redact.ts +65 -14
  47. package/src/core/tailscale.ts +79 -3
  48. package/src/core/team-client.ts +13 -2
  49. package/src/core/uninstall.ts +2 -0
@@ -16,47 +16,51 @@
16
16
  // Harness payloads are untyped at the boundary: every field read goes through a runtime check.
17
17
 
18
18
  import { execFileSync, spawn } from "node:child_process";
19
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
- import { basename, dirname, extname, join, resolve } from "node:path";
21
- import type { Decision, TraceEvent } from "../../core/adapter.ts";
19
+ import { closeSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
20
+ import { basename, extname, join, resolve } from "node:path";
21
+ import type { TraceEvent } from "../../core/adapter.ts";
22
22
  import { AGENTS_TEMPLATE, renderBlock } from "../../core/agents-md.ts";
23
- import { chatGo, chatPlanner, chatTier, currentPlanner, plannerPin, stampPlannerMode, verifyPlannerMode, type Tier } from "../../core/autonomy.ts";
24
- import { chatApprove } from "../../core/plan-approval.ts";
25
- import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
23
+ import { currentPlanner, plannerPin, stampPlannerMode, verifyPlannerMode } from "../../core/autonomy.ts";
24
+ import { briefPaths } from "../../core/brief-lint.ts";
25
+ import { fileClaimStore, type ClaimStore } from "../../core/claims.ts";
26
+ import { nowSec } from "../../core/clock.ts";
26
27
  import { configFile, loadConfig, reloadingConfig, type Config } from "../../core/config.ts";
27
- import { checkWrite, deferSteer, type WriteCheckConfig } from "../../core/write-check.ts";
28
- import { nowSec, strftime } from "../../core/clock.ts";
28
+ import { tryLock, type HeldLock } from "../../core/file-lock.ts";
29
+ import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, mainId, mainStateDir, newProgressEntries, planReadNote, plannerSpawnPlan, recordMainResult, rekeySpawnFile, resetMainCalls, revertMainEdit, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
29
30
  import { runDetectors, type DetectorInput } from "../../core/incident-detectors.ts";
30
- import { fileClaimStore, type ClaimStore } from "../../core/claims.ts";
31
- import { remoteStoreFor } from "../../core/team-client.ts";
32
- import { appendOwnerAnswer, readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
31
+ import { appendOwnerAnswer } from "../../core/incidents.ts";
32
+ import { mainDetectors } from "../../core/main-start.ts";
33
+ import { notifyProviders, ownerAnswerHandback, ownerAnswerSteer, postReply } from "../../core/notify.ts";
33
34
  import { appendedSinceSpawn, markTopicsSpawned, ownerLogDir, recordOwnerLog } from "../../core/owner-log.ts";
34
35
  import { topicsDue, topicsLogFile } from "../../core/owner-topics.ts";
35
- import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, mainId, mainStateDir, newProgressEntries, planReadNote, plannerSpawnPlan, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
36
- import { rateLimited } from "../../core/rate-limit.ts";
37
- import { backPost, clearLimitState, limitMetric, limitedPost, onLimited, readLimitState, timingOf, writeLimitState } from "../../core/limit-probe.ts";
38
- import { appendMetric } from "../../core/metrics.ts";
39
- import { notifyProviders, ownerAnswerHandback, ownerAnswerSteer, postReply } from "../../core/notify.ts";
36
+ import { readPressure } from "../../core/pressure.ts";
37
+ import * as q from "../../core/queue/lib.ts";
38
+ import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
39
+ import { notePath, ownerText, spawnRefusal } from "../../core/rollover.ts";
40
40
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
41
- import { inboxPath } from "../../core/owner-ui.ts";
42
41
  import { realTailscale } from "../../core/tailscale.ts";
43
- import { briefPaths } from "../../core/brief-lint.ts";
42
+ import { remoteStoreFor } from "../../core/team-client.ts";
44
43
  import { actionsRules, ownedRepoOf, suspiciousActions, unreportedFindings } from "../../core/trace-actions.ts";
45
- import { mainDetectors, mainStartText } from "../../core/main-start.ts";
46
-
47
- import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, unansweredOwnerMessages, type RolloverState } from "../../core/rollover.ts";
48
- import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
49
- import { ompProviders } from "./providers.ts";
44
+ import { checkWrite, deferSteer, type WriteCheckConfig } from "../../core/write-check.ts";
45
+ import { autoClose } from "./auto-close.ts";
46
+ import { registerChatCommands } from "./chat-commands.ts";
47
+ import { CLAIM_BEAT_MS, deliverOwnerInbox, OWNER_INBOX_POLL_MS, ownerInboxCursorPath, ownerInboxMessage, pendingInboxRecords, pressureTick, seedInboxFloor } from "./inbox.ts";
50
48
  import { adapterLog, MAIN_ENV } from "./launch.ts";
51
- import { parseTraceFile } from "./traces.ts";
52
- import { packageJsonPath, packageVersion } from "./package-root.ts";
53
- import * as q from "../../core/queue/lib.ts";
54
- import { pinModel, providerOfModel, recordOut, resetEpochFromText } from "../../core/provider-state.ts";
55
- import { annotateResetTimes } from "../../core/reset-time.ts";
56
- import { tryLock, type HeldLock } from "../../core/file-lock.ts";
57
- import { currentHolder, pressureLevel, pressureMessage, pressureTransition, readPressure, type PressureSample, type PressureState } from "../../core/pressure.ts";
58
49
  // Registers the plugin-command matcher into core's writeTargets (side effect).
59
50
  import "./package-ops.ts";
51
+ import { createRateLimitController, limitProbeSpawn, recordProviderOutFromRateLimit, recordProviderOutFromTask } from "./rate-limit-controller.ts";
52
+ import { createRolloverController } from "./rollover-controller.ts";
53
+ import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
54
+ import { parseTraceFile } from "./traces.ts";
55
+ import { asCtx, asRecord, asRolloverCtx, asString, call, isMain, lastAssistantIn, toExtensionResult, type EventReply, type ExtensionHost, type RolloverCtx } from "./types.ts";
56
+
57
+ export { adapterLog, autoClose, CLAIM_BEAT_MS, deliverOwnerInbox, limitProbeSpawn, OWNER_INBOX_POLL_MS, ownerInboxCursorPath, ownerInboxMessage, pendingInboxRecords, pressureTick, recordProviderOutFromRateLimit, toExtensionResult, type ExtensionHost };
58
+
59
+ /** Optional test/caller seams for `createOmpAdapter`. */
60
+ export interface OmpAdapterOptions {
61
+ /** Overrides the `doctor` runner passed into `mainStartText` during in-process rollover fallback. */
62
+ doctor?: () => Promise<string> | string;
63
+ }
60
64
 
61
65
  /**
62
66
  * Re-reads the config, then holds the planner mode facts to the owner's baseline (P2 d): a
@@ -87,105 +91,9 @@ function defaultMainEvents(cfg: Config): TraceEvent[] {
87
91
  }
88
92
  }
89
93
 
90
- /** Subset of the harness extension host the adapter needs. */
91
- export interface ExtensionHost {
92
- on(event: string, cb: (...args: unknown[]) => unknown): void;
93
- registerCommand(name: string, opts: { description?: string; handler: (args: unknown, ctx: unknown) => unknown }): void;
94
- sendUserMessage(content: string | ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[]): void;
95
- sendMessage(message: { customType: string; content: string; display: boolean }, options: { triggerTurn: boolean; deliverAs: "nextTurn" }): void;
96
- }
97
-
98
- /** The parts of a harness call context the handlers look at. */
99
- interface HostCtx {
100
- hasAgent: boolean;
101
- kind?: string;
102
- id?: string;
103
- cwd?: string;
104
- setInterval?: (cb: () => void, ms: number) => unknown;
105
- spawnLimitProbe?: () => void;
106
- }
107
-
108
- function asRecord(v: unknown): Record<string, unknown> {
109
- return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
110
- }
111
-
112
- function asString(v: unknown, fallback = ""): string {
113
- return typeof v === "string" ? v : fallback;
114
- }
115
-
116
- /** The last assistant message of an omp event's `messages` array, as the adapter needs it: its
117
- * joined text-block text and the shape that tells a real hand-back from a mid-run continuation
118
- * (plan 20261025_0130). omp sends the reply in `session_stop.last_assistant_message` (falling
119
- * back to the last assistant entry of `messages`) and in `agent_end.messages`; reading the
120
- * session file instead lags a whole turn because session_stop fires BEFORE agent_end. */
121
- interface EventReply {
122
- text: string;
123
- stopReason: string | null;
124
- toolCalls: number;
125
- /** The provider's error text on a turn that ended on one (`429 … retry-after-ms=…`); null otherwise. */
126
- errorMessage: string | null;
127
- /** The provider and model fields of the assistant message, when the event carries them; the provider-out recording keys on the provider. */
128
- provider: string | null;
129
- model: string | null;
130
- }
131
-
132
- function lastAssistantIn(messages: unknown): EventReply | null {
133
- const arr = Array.isArray(messages) ? messages : [];
134
- for (let i = arr.length - 1; i >= 0; i--) {
135
- const m = asRecord(arr[i]);
136
- if (m.role !== "assistant") continue;
137
- const content = Array.isArray(m.content) ? m.content : [];
138
- const text = content
139
- .filter(c => asRecord(c).type === "text")
140
- .map(c => asString(asRecord(c).text))
141
- .join("\n")
142
- .trim();
143
- return {
144
- text,
145
- stopReason: typeof m.stopReason === "string" ? m.stopReason : null,
146
- toolCalls: content.filter(c => asRecord(c).type === "toolCall").length,
147
- errorMessage: typeof m.errorMessage === "string" ? m.errorMessage : null,
148
- provider: typeof m.provider === "string" ? m.provider : null,
149
- model: typeof m.model === "string" ? m.model : null,
150
- };
151
- }
152
- return null;
153
- }
154
-
155
- function asCtx(v: unknown): HostCtx {
156
- const r = asRecord(v);
157
- // The agent envelope only ever carries kind/id strings (original extensions read just those);
158
- // cast fixes the envelope, every field below is checked before use.
159
- const agent = r.agent as { kind?: unknown; id?: unknown } | null | undefined;
160
- const out: HostCtx = { hasAgent: agent !== null && agent !== undefined };
161
- if (agent) {
162
- if (typeof agent.kind === "string") out.kind = agent.kind;
163
- if (typeof agent.id === "string") out.id = agent.id;
164
- }
165
- if (typeof r.cwd === "string") out.cwd = r.cwd;
166
- // Harness-injected timer with the original main-guard signature (ctx.setInterval).
167
- const interval = r.setInterval as ((cb: () => void, ms: number) => unknown) | undefined;
168
- if (typeof interval === "function") out.setInterval = interval;
169
- // Harness-injected probe spawner (tests); the default starts the niced probe child.
170
- const probe = r.spawnLimitProbe as (() => void) | undefined;
171
- if (typeof probe === "function") out.spawnLimitProbe = probe;
172
- return out;
173
- }
174
-
175
- /** Map a core decision onto the extension return shapes. */
176
- export function toExtensionResult(d: Decision): Record<string, unknown> {
177
- if (!d.allow) return { block: true, reason: d.reason, decision: "block" };
178
- if (d.inject) return { additionalContext: d.inject };
179
- return {};
180
- }
181
-
182
94
  // A push or merge by Main may have landed a completed plan: try closing right away.
183
95
  const PUSH_MERGE = /\bgit\b[^\n;|&]*\bpush\b|\b(glab\s+mr|gh\s+pr)\s+merge\b/;
184
96
 
185
- // The installed package and its version: see ./package-root.ts.
186
-
187
- export { adapterLog };
188
-
189
97
  /**
190
98
  * Paths named inside the one configured method doc (brief.method_read): Main-owned and outside
191
99
  * every run's write scope, so its named paths are trusted one hop past the brief text (P10c).
@@ -239,63 +147,6 @@ function subActionDetectors(cfg: Config, ctx: unknown, planFile: string, before:
239
147
  }
240
148
  }
241
149
 
242
- // Background queue-close for every plan Main marked complete — and (P4, plan 20261031_0911) for
243
- // every OPEN plan whose work has landed. Ported from the original autoClose: same filter, same
244
- // "--- auto-close attempt" log line, detached child with stdio on the per-plan close log.
245
- // QUEUE_CLOSE_BIN overrides the binary (tests); without it the package's own executable
246
- // bin/queue-close runs (its `#!/usr/bin/env bun` shebang picks bun).
247
- // Never process.execPath: inside the harness that is the harness binary itself, so the child was
248
- // a new agent session that loaded this plugin and auto-closed again — a process fork bomb
249
- // (2026-10-21 OOMs, ~175 processes).
250
- function closeChildArgs(plan: string, auto: boolean): [string, string[]] {
251
- const bin = process.env.QUEUE_CLOSE_BIN;
252
- const args = auto ? ["--auto", plan] : [plan];
253
- if (bin) return [bin, args];
254
- return [join(import.meta.dir, "..", "..", "..", "bin", "queue-close"), args];
255
- }
256
-
257
- export function autoClose(cfg: Config): string[] {
258
- const started: string[] = [];
259
- let plans: q.Plan[];
260
- try {
261
- // P4: landed open plans auto-close too (q.autoCloseCandidate) — the child runs queue-close
262
- // --auto and writes "Status: complete" itself when the done check passes.
263
- plans = q.activePlans(cfg.paths).filter(p => (p.status === "complete" || p.status === "cancelled" || q.autoCloseCandidate(p)) && !p.errors.length);
264
- } catch {
265
- return started;
266
- }
267
- try {
268
- mkdirSync(cfg.paths.queue_state, { recursive: true });
269
- } catch {}
270
- for (const p of plans) {
271
- try {
272
- const outFile = q.closeLog(p.file, cfg.paths);
273
- appendFileSync(outFile, `--- ${new Date().toISOString()} auto-close attempt\n`);
274
- const out = openSync(outFile, "a");
275
- const [bin, args] = closeChildArgs(p.file, p.status === "open");
276
- const childEnv: NodeJS.ProcessEnv = {
277
- ...process.env,
278
- HOME: cfg.paths.home,
279
- QUEUE_AGENT: cfg.paths.agent_dir,
280
- QUEUE_INDEX: cfg.paths.queue_index,
281
- QUEUE_BLOCKERS: cfg.paths.blockers,
282
- QUEUE_STATE: cfg.paths.queue_state,
283
- QUEUE_SUBAGENTS: cfg.paths.subagents,
284
- QUEUE_CANCELLED: cfg.paths.cancelled,
285
- QUEUE_UNLOCK: cfg.paths.unlock,
286
- };
287
- const child = spawn(bin, args, { detached: true, stdio: ["ignore", out, out], env: childEnv });
288
- child.unref();
289
- closeSync(out);
290
- started.push(p.file);
291
- } catch (err) {
292
- adapterLog(cfg, `auto-close: could not start for ${p.file}: ${err}`);
293
- }
294
- }
295
- if (started.length) adapterLog(cfg, `auto-close started: ${started.join(", ")}`);
296
- return started;
297
- }
298
-
299
150
  // Main's stop gate needs the ledger output (original: `agent-ledger --hours 12` through bash -lc,
300
151
  // errors folded into empty output).
301
152
  function ledgerText(cfg: Config): string {
@@ -375,98 +226,6 @@ function redactToolResult(content: unknown[], cfg: Config): { content: unknown[]
375
226
  return { content: out, note: redactSummary([...hits].map(([type, count]) => ({ type, count }))) };
376
227
  }
377
228
 
378
- // Provider out-until from live data (plan 20261025_1700 P1). Two automatic recordings, both
379
- // keyed on the provider half of an agent pin's `model:` frontmatter, both best effort and
380
- // logged once. The reset-time case trusts the provider's own words; the no-time case falls
381
- // back to the armed rate-limit wait, so a provider without a quoted reset time still lands in
382
- // the file the guards and the ledger read.
383
- const resetRule = (cfg: Config): { pattern: string; zone: string } => ({ pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz });
384
-
385
- /** Task result that quotes a reset time: record it for the sub's provider. A batch naming
386
- * several providers cannot attribute the time to one of them, so it records nothing. */
387
- function recordProviderOutFromTask(e: Record<string, unknown>, content: unknown[], cfg: Config): void {
388
- if (asString(e.toolName) !== "task" || e.isError === true) return;
389
- const text = content.map(p => asString(asRecord(p).text)).join("\n");
390
- const epoch = resetEpochFromText(text, resetRule(cfg));
391
- if (epoch === null) return;
392
- const tasks = Array.isArray(asRecord(e.input).tasks) ? (asRecord(e.input).tasks as unknown[]) : [];
393
- const providers = new Set<string>();
394
- for (const t of tasks) {
395
- const provider = providerOfModel(pinModel(cfg, asString(asRecord(t).agent)));
396
- if (provider) providers.add(provider);
397
- }
398
- if (providers.size !== 1) return;
399
- const provider = [...providers][0]!;
400
- recordOut(cfg, provider, epoch, "task-result");
401
- adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (task result)`);
402
- }
403
-
404
- /** Rate-limited turn end: record the reset time the error text names, else the armed wait. Returns the
405
- * named reset in epoch ms (null when the text names none): the one parse of that text, which the call
406
- * site passes on to the rate-limit episode (plan 20261027_1500 P2/P3). */
407
- export function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs: number, cfg: Config): number | null {
408
- const named = reply ? resetEpochFromText(reply.errorMessage ?? "", resetRule(cfg)) : null;
409
- const provider = reply?.provider ?? providerOfModel(reply?.model ?? null);
410
- if (provider) {
411
- const epoch = named ?? Math.floor(untilMs / 1000);
412
- recordOut(cfg, provider, epoch, named !== null ? "rate-limit-reset" : "rate-limit");
413
- 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"})`);
414
- }
415
- return named === null ? null : named * 1000;
416
- }
417
-
418
- // Session rollover helpers: the harness context read through runtime checks, and the file size and
419
- // mtime reads. The decisions are in src/core/rollover.ts.
420
- const WAIT_NOTICE_MS = 15 * 60_000;
421
-
422
- interface RolloverCtx {
423
- sessionId: string;
424
- sessionFile: string;
425
- runningJobs(): string[];
426
- waitForIdle(): unknown;
427
- newSession(opts: { parentSession: string }): unknown;
428
- notify(message: string): void;
429
- draft(): string;
430
- shutdown(): void;
431
- }
432
-
433
- /** Call a method on a harness object by name; undefined when it is not a function. */
434
- function call(obj: Record<string, unknown>, key: string, args: unknown[] = []): unknown {
435
- const fn = obj[key];
436
- return typeof fn === "function" ? Reflect.apply(fn, obj, args) : undefined;
437
- }
438
-
439
- function asRolloverCtx(v: unknown): RolloverCtx | null {
440
- const r = asRecord(v);
441
- const sm = asRecord(r.sessionManager);
442
- const sessionId = call(sm, "getSessionId");
443
- const sessionFile = call(sm, "getSessionFile");
444
- if (typeof sessionId !== "string" || typeof sessionFile !== "string") return null;
445
- return {
446
- sessionId,
447
- sessionFile,
448
- runningJobs: () => {
449
- const running = asRecord(call(r, "getAsyncJobSnapshot")).running;
450
- return Array.isArray(running) ? running.map(j => asString(asRecord(j).label, "job")) : [];
451
- },
452
- waitForIdle: () => call(r, "waitForIdle"),
453
- newSession: opts => call(r, "newSession", [opts]),
454
- notify: message => call(asRecord(r.ui), "notify", [message]),
455
- draft: () => {
456
- const text = call(asRecord(r.ui), "getEditorText");
457
- return typeof text === "string" ? text : "";
458
- },
459
- shutdown: () => {
460
- call(r, "shutdown");
461
- },
462
- };
463
- }
464
-
465
- function isMain(ctx: unknown): boolean {
466
- const c = asCtx(ctx);
467
- return !c.hasAgent || c.kind === "main";
468
- }
469
-
470
229
  // Owner topics (plan P8): one detached, niced `recall` child, as the limit probe is. The child env drops
471
230
  // MAIN_ENV so the child is not Main. Its stdout and stderr append to owner-topics.log (stats and `topics: fail`
472
231
  // lines only). A context that injects `spawnTopics` (tests) gets the call instead.
@@ -491,207 +250,8 @@ function spawnTopics(cfg: Config, ctx: unknown, args: string[]): void {
491
250
  }
492
251
  }
493
252
 
494
- function mtimeOf(path: string): number | null {
495
- try {
496
- return statSync(path).mtimeMs;
497
- } catch {
498
- return null;
499
- }
500
- }
501
-
502
- function sizeOf(path: string): number {
503
- try {
504
- return statSync(path).size;
505
- } catch {
506
- return 0;
507
- }
508
- }
509
-
510
- // ---- owner inbox delivery (plan 20261024_2230 P3b) ----
511
- // The phone page appends answers to <queue_state>/owner-inbox.jsonl — a protected state file, so
512
- // no agent can forge an owner answer (guards refuse the write). Main's session delivers each
513
- // record once as a user message (pi.sendUserMessage, no options: idle → a new turn, streaming →
514
- // the steer queue), at turn end and on a 15 s timer while idle. The consumed-row count lives in
515
- // <queue_state>/owner-inbox.cursor; subagent sessions never deliver and never move it.
516
-
517
- /** Idle-poll interval for the owner inbox. */
518
- export const OWNER_INBOX_POLL_MS = 15_000;
519
- /** How often the adapter heartbeats every claim this Main holds (plan 20261027_1300 P3). */
520
- export const CLAIM_BEAT_MS = 60_000;
521
-
522
- /** The delivered cursor: how many owner-inbox rows this Main's session has consumed (P5: one file per Main, under its mainStateDir). */
523
- export function ownerInboxCursorPath(cfg: Config | Pick<q.QueuePaths, "queue_state">): string {
524
- return `${mainStateDir(cfg)}/inbox-cursor`;
525
- }
526
-
527
- /** Rows this Main starts past when it has never delivered (P5): set at adapter creation so a Main that registers late does not replay old rows. null = adopt the file or 0. */
528
- let inboxFloor: number | null = null;
529
-
530
- function readOwnerInboxCursor(cfg: Config): number {
531
- try {
532
- const n = Number(readFileSync(ownerInboxCursorPath(cfg), "utf8").trim());
533
- return Number.isInteger(n) && n >= 0 ? n : inboxFloor ?? 0;
534
- } catch {
535
- return inboxFloor ?? 0;
536
- }
537
- }
538
-
539
- function writeOwnerInboxCursor(cfg: Config, n: number): void {
540
- try {
541
- mkdirSync(mainStateDir(cfg), { recursive: true });
542
- writeFileSync(ownerInboxCursorPath(cfg), `${n}\n`);
543
- } catch {}
544
- }
545
-
546
- /** The user message one inbox record becomes, or null when the record is not one Main can act on.
547
- * Records without `kind` are page answers (the original shape). */
548
- export function ownerInboxMessage(rec: Record<string, unknown>, queuePaths?: Pick<q.QueuePaths, "queue_state">): string | ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[] | null {
549
- const kind = rec.kind === undefined ? "answer" : asString(rec.kind);
550
- const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
551
- switch (kind) {
552
- case "answer": {
553
- const plan = asString(rec.plan);
554
- const question = asString(rec.question);
555
- const answer = asString(rec.answer);
556
- if (!plan || !question || !answer) return null;
557
- return `Owner answered on the phone page — ${basename(plan)}: ${question} → ${answer}`;
558
- }
559
- case "unlock": {
560
- const minutes = num(rec.minutes);
561
- const until = num(rec.until);
562
- if (minutes === null || until === null) return null;
563
- return `Owner unlocked the guards from the phone page for ${minutes} min (until ${strftime(until, "%H:%M")}). Do the step that waited on the unlock now.`;
564
- }
565
- case "lock":
566
- return "Owner locked the guards from the phone page.";
567
- case "approval": {
568
- const page = asString(rec.page);
569
- const plan = asString(rec.plan);
570
- if (page === "" || plan === "") return null;
571
- return `Owner approved ${basename(plan)} on page ${page}.`;
572
- }
573
- case "reorder": {
574
- const plan = asString(rec.plan);
575
- const from = num(rec.from);
576
- const to = num(rec.to);
577
- if (!plan || from === null || to === null) return null;
578
- return `Owner moved ${basename(plan)} from #${from} to #${to} on the phone page; INDEX.md has the new order — work by it.`;
579
- }
580
- case "message": {
581
- const ts = num(rec.ts);
582
- const id = asString(rec.id);
583
- if (ts === null || !/^[0-9]+-[0-9a-f]{6}$/.test(id)) return null;
584
- const at = strftime(ts, "%H:%M");
585
- if (!queuePaths) return null;
586
- const dir = join(queuePaths.queue_state, "owner-messages", id);
587
- let message: Record<string, unknown>;
588
- try {
589
- message = JSON.parse(readFileSync(join(dir, "message.json"), "utf8")) as Record<string, unknown>;
590
- } catch {
591
- return [{ type: "text", text: `Owner sent a message from the phone page at ${at}; it expired (12 h) before delivery.` }];
592
- }
593
- const text = asString(message.text);
594
- const names = Array.isArray(message.images) ? message.images.filter((name): name is string => typeof name === "string" && /^[1-4]\.(png|jpg|gif|webp)$/.test(name)) : [];
595
- const parts: ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[] = [];
596
- const paths = names.map(name => join(dir, name));
597
- parts.push({
598
- type: "text",
599
- text: `Owner message from the phone page (${at}): ${text}${paths.length ? `\nImages:\n${paths.map(path => `- ${path}`).join("\n")}` : ""}`,
600
- });
601
- for (const name of names) {
602
- const ext = name.slice(name.lastIndexOf(".") + 1);
603
- const mimeType = ext === "jpg" ? "image/jpeg" : `image/${ext}`;
604
- try {
605
- parts.push({ type: "image", data: readFileSync(join(dir, name)).toString("base64"), mimeType });
606
- } catch {
607
- return [{ type: "text", text: `Owner sent a message from the phone page at ${at}; it expired (12 h) before delivery.` }];
608
- }
609
- }
610
- return parts;
611
- }
612
- case "page-note": {
613
- // One row per note the owner left on a published page (plan 20261026 P6).
614
- const page = asString(rec.page);
615
- const quote = asString(rec.quote);
616
- const note = asString(rec.note);
617
- if (!page || !note) return null;
618
- const id = asString(rec.id);
619
- const url = asString(rec.url);
620
- const where = `Owner note on the page ${page}${id ? ` (${id})` : ""}${url ? ` — ${url}` : ""}: `;
621
- return quote ? `${where}on "${quote}" → ${note}` : `${where}${note}`;
622
- }
623
- default:
624
- return null;
625
- }
626
- }
627
-
628
- /** The JSONL rows after `cursor` (a row count), as records, plus the new cursor. A torn last row
629
- * (a page write that has not landed completely) stays unconsumed; a malformed complete row is
630
- * consumed but skipped, so one bad line cannot wedge delivery. */
631
- export function pendingInboxRecords(text: string, cursor: number): { records: Record<string, unknown>[]; next: number } {
632
- const endsClean = text === "" || text.endsWith("\n");
633
- const rows = text.split("\n");
634
- if (rows.length && rows[rows.length - 1] === "") rows.pop();
635
- const records: Record<string, unknown>[] = [];
636
- let next = Math.min(cursor, rows.length);
637
- for (let i = cursor; i < rows.length; i++) {
638
- const torn = i === rows.length - 1 && !endsClean;
639
- try {
640
- const rec: unknown = JSON.parse((rows[i] ?? "").trim());
641
- if (rec !== null && typeof rec === "object" && !Array.isArray(rec)) records.push(rec as Record<string, unknown>);
642
- } catch {}
643
- if (!torn) next = i + 1;
644
- }
645
- return { records, next };
646
- }
647
-
648
- /** Deliver every inbox row past the cursor once, as a user message to Main; then store the cursor.
649
- * Synchronous, so the turn-end path and the idle timer cannot interleave. */
650
- export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
651
- let text: string;
652
- try {
653
- text = readFileSync(inboxPath(cfg.paths), "utf8");
654
- } catch {
655
- return; // no inbox yet: nothing to deliver
656
- }
657
- const cursor = readOwnerInboxCursor(cfg);
658
- const { records, next } = pendingInboxRecords(text, cursor);
659
- if (next === cursor) return;
660
- let delivered = 0;
661
- for (const rec of records) {
662
- // P5: a row addressed to another Main (`to` set and not this Main's id) is consumed but not delivered here.
663
- if (typeof rec.to === "string" && rec.to !== "" && rec.to !== mainId()) continue;
664
- const msg = ownerInboxMessage(rec, cfg.paths);
665
- if (msg === null) continue;
666
- pi.sendUserMessage(msg);
667
- delivered++;
668
- }
669
- writeOwnerInboxCursor(cfg, next);
670
- adapterLog(cfg, `owner inbox: delivered ${delivered} answer(s) (cursor ${cursor} → ${next})`);
671
- }
672
-
673
253
  /** The most recently registered createOmpAdapter cleanup, for the exported reset(). */
674
254
  let activeAdapterReset: (() => void) | null = null;
675
- /** Pressure alert tick (plan 20261026_0100 P2): classifies one sample, runs the transition, and tells Main on a RED or GREEN fire. The state lives in <queue_state>/pressure.json and is rewritten only when it changes, so a reloaded session does not re-fire. */
676
- export function pressureTick(pi: ExtensionHost, cfg: Config, sample: PressureSample, now: number): void {
677
- const file = join(cfg.paths.queue_state, "pressure.json");
678
- let prev: PressureState | null = null;
679
- try {
680
- prev = JSON.parse(readFileSync(file, "utf8")) as PressureState;
681
- } catch {}
682
- const level = pressureLevel(sample, cfg);
683
- const r = pressureTransition(prev, level, now, cfg);
684
- const next = JSON.stringify(r.state);
685
- if (next !== JSON.stringify(prev)) {
686
- try {
687
- mkdirSync(cfg.paths.queue_state, { recursive: true });
688
- writeFileSync(file, next);
689
- } catch {}
690
- }
691
- if (r.fire === "red") {
692
- pi.sendUserMessage(pressureMessage("red", sample, currentHolder(cfg, now)));
693
- } else if (r.fire === "green") pi.sendUserMessage(pressureMessage("green", sample, null));
694
- }
695
255
 
696
256
  /** This process's held Main session lock (plan 20261103_1146 P2): the first main session_start
697
257
  * locks `<queue_state>/mains/<id>/session.lock` for the process lifetime — the kernel frees it
@@ -699,52 +259,30 @@ export function pressureTick(pi: ExtensionHost, cfg: Config, sample: PressureSam
699
259
  * process take the id, and a new flock of the same file in this process is busy. reset() is the
700
260
  * only release, so tests do not leak the flock into the next file. */
701
261
  let heldSessionLock: HeldLock | null = null;
702
- /** The limit tick: one check of the open episode every 30 s (plan 20261027_1500 P3). */
703
- const LIMIT_TICK_MS = 30_000;
704
- /** The probe's command line and env. Never process.execPath: inside the harness that is the omp
705
- * binary, so the child was a full Main session (2026-11-03: stray Mains). bun comes from PATH, as
706
- * every bin's `#!/usr/bin/env bun` shebang does; the child env drops MAIN_ENV. */
707
- export function limitProbeSpawn(env: NodeJS.ProcessEnv = process.env): { cmd: string; args: string[]; env: NodeJS.ProcessEnv } {
708
- const { [MAIN_ENV]: _main, ...rest } = env;
709
- return { cmd: "nice", args: ["-n", "19", "bun", join(import.meta.dir, "../../cli/limit-probe.ts")], env: rest };
710
- }
711
- /** One limit probe as a niced child (cli/limit-probe.ts). It writes the episode state itself;
712
- * a failed start is logged and the next tick tries again. */
713
- function spawnLimitProbeChild(cfg: Config): void {
714
- const p = limitProbeSpawn();
715
- const child = spawn(p.cmd, p.args, { detached: true, stdio: "ignore", env: p.env });
716
- child.on("error", err => adapterLog(cfg, `RATE-LIMIT probe: could not start: ${err.message}`));
717
- child.unref();
718
- }
262
+
719
263
  /** Register the guard handlers on one extension host. `initial` is injectable for tests; `freshConfig` re-reads the config per guarded call. */
720
- export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig: () => Config = () => initial): void {
264
+ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig: () => Config = () => initial, opts: OmpAdapterOptions = {}): void {
721
265
  // Guarded handlers take `cfg = freshConfig()` first, so an edited config.yml reaches the next call (P4e).
722
266
  let cfg = initial;
723
267
  // P2 d: the first seam — a mode fact another writer left behind is reverted before any handler runs.
724
268
  cfg = freshPlannerConfig(freshConfig);
725
- // P5: seed the per-Main inbox floor once — a Main that has never delivered starts past rows
726
- // that predate its registration; the pre-multi-main cursor file belongs to the default id's
727
- // first start. Later reads/writes own the file, so the floor is only a creation-time default.
728
- try {
729
- if (!existsSync(ownerInboxCursorPath(cfg))) {
730
- mkdirSync(mainStateDir(cfg), { recursive: true });
731
- if (mainId() === "main") {
732
- try {
733
- renameSync(`${cfg.paths.queue_state}/owner-inbox.cursor`, ownerInboxCursorPath(cfg));
734
- } catch {}
735
- }
736
- if (!existsSync(ownerInboxCursorPath(cfg))) {
737
- try {
738
- inboxFloor = pendingInboxRecords(readFileSync(inboxPath(cfg.paths), "utf8"), 0).next;
739
- } catch {
740
- inboxFloor = 0;
741
- }
742
- }
743
- }
744
- } catch {}
269
+ const getCfg = (): Config => cfg;
270
+ seedInboxFloor(cfg);
745
271
  // Main's rules ride its system prompt each turn; they are never written into the owner's AGENTS.md.
746
272
  const mainRules = renderBlock(cfg);
747
273
 
274
+ const rateLimit = createRateLimitController(pi, getCfg);
275
+ const rollover = createRolloverController(pi, getCfg, { doctor: opts.doctor });
276
+
277
+ // Clear the previous adapter's armed grace timer before this one overwrites the pointer (P3c).
278
+ // Do not release heldSessionLock: this runs on every factory re-entry, and the lock is
279
+ // process-lifetime (plan 20261103_1146 P4). reset() still releases it.
280
+ activeAdapterReset?.();
281
+ activeAdapterReset = (): void => {
282
+ rollover.clearState();
283
+ rateLimit.stopTick();
284
+ };
285
+
748
286
  let callsSinceStop = 0;
749
287
  let idleStops = 0;
750
288
  let timer: unknown;
@@ -764,26 +302,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
764
302
  // emits (sessionStopWillContinue) consumes it and posts nothing — a blocked stop's reply is a
765
303
  // mid-work report, never a hand-back.
766
304
  let stopBlocked = false;
767
- // Rate-limit probe loop (plan 20261027_1500 P3). A limited turn end opens one episode in
768
- // main-limit.json: a named reset is waited for; otherwise a niced probe child runs every
769
- // probe_interval_s until one gets through or max_probes is spent. ONE tick (LIMIT_TICK_MS)
770
- // reads the episode: it spawns a due probe, or, once the provider is back, sends Main ONE new
771
- // turn. A new Main turn cancels the tick and keeps the episode (probe count kept); a turn that
772
- // ends without a limit clears it.
773
- let limitTickArmed = false;
774
- let limitTick: NodeJS.Timeout | null = null;
775
- const rateClock = (ms: number): string => strftime(ms / 1000, "%H:%M");
776
- const stopLimitTick = (): void => {
777
- limitTickArmed = false;
778
- if (limitTick !== null) {
779
- clearInterval(limitTick);
780
- limitTick = null;
781
- }
782
- };
783
- const disarmRateEpisode = (): void => {
784
- stopLimitTick();
785
- clearLimitState(cfg);
786
- };
305
+
787
306
  // P5b: a real turn end answers every owner message it followed — the answer (the turn's own
788
307
  // reply, the page's lastAnswerFor shape) rides the same owner-message store. Rate-limited,
789
308
  // blocked and mid-run ends are not turn ends: nothing is recorded.
@@ -800,69 +319,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
800
319
  adapterLog(cfg, `OWNER-ANSWER record failed: ${err instanceof Error ? err.message : String(err)}`);
801
320
  }
802
321
  };
803
- const limitTickFire = (c: HostCtx): void => {
804
- if (!limitTickArmed) return;
805
- const state = readLimitState(cfg);
806
- if (state === null) {
807
- stopLimitTick();
808
- adapterLog(cfg, "RATE-LIMIT give up: episode state gone (max_probes spent or unreadable)");
809
- return;
810
- }
811
- const now = Date.now();
812
- if (state.back_at !== null) {
813
- if (now < state.back_at) return;
814
- stopLimitTick();
815
- clearLimitState(cfg);
816
- // P4: the finished episode is recorded once and the owner hears one back post; both are
817
- // times and counts only — the episode's last_error never reaches chat or ledger.
818
- appendMetric(cfg, limitMetric(state, now));
819
- adapterLog(cfg, `RATE-LIMIT back: provider limit over (back at ${rateClock(state.back_at)}); new turn sent`);
820
- void postReply(backPost(state), cfg).then(results => {
821
- for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
822
- });
823
- pi.sendUserMessage(`main-guard: the provider limit is over (back at ${rateClock(state.back_at)}). Continue the queue where you stopped.`);
824
- return;
825
- }
826
- if (now < state.next_probe_at) return;
827
- (c.spawnLimitProbe ?? (() => spawnLimitProbeChild(cfg)))();
828
- };
829
- const armLimitTick = (c: HostCtx): void => {
830
- stopLimitTick();
831
- limitTickArmed = true;
832
- const t: unknown = c.setInterval ? c.setInterval(() => limitTickFire(c), LIMIT_TICK_MS) : setInterval(() => limitTickFire(c), LIMIT_TICK_MS);
833
- if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
834
- limitTick = t as NodeJS.Timeout;
835
- };
836
- // A turn that ended on a provider rate limit: the episode opens (or continues with its probe
837
- // count), the owner chat hears once per episode, and the tick takes over.
838
- const onRateLimitedStop = (c: HostCtx, namedResetMs: number | null, errorText: string, model: string): void => {
839
- const prev = readLimitState(cfg);
840
- const timing = timingOf(cfg);
841
- const state = onLimited(prev, namedResetMs, errorText, Date.now(), model, timing);
842
- try {
843
- writeLimitState(cfg, state);
844
- } catch (err) {
845
- adapterLog(cfg, `RATE-LIMIT state write failed: ${err instanceof Error ? err.message : String(err)}`);
846
- return;
847
- }
848
- adapterLog(cfg, `RATE-LIMIT stop: ${state.reset_named ? "named reset" : "probe"} at ${rateClock(state.next_probe_at)} (probes ${state.probes} of ${timing.max_probes})`);
849
- if (prev === null) {
850
- adapterLog(cfg, "notify: posted (rate-limit)");
851
- void postReply(limitedPost(state, timing.probe_interval_s), cfg).then(results => {
852
- for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
853
- });
854
- }
855
- armLimitTick(c);
856
- };
857
- // The rate-limit decision for one turn end, from the event's own last assistant message. The
858
- // untilMs is the fallback wait recorded with PROVIDER-OUT when the error text names no reset.
859
- const rateLimitOf = (reply: EventReply | null): { untilMs: number } | null => {
860
- const rl = cfg.guards.rate_limit;
861
- const hit = rateLimited(reply?.stopReason ?? null, reply?.errorMessage ?? null, rl);
862
- if (!hit) return null;
863
- const waitMs = (hit.retryAfterMs ?? rl.probe_interval_s * 1000) + rl.slack_s * 1000;
864
- return { untilMs: Date.now() + waitMs };
865
- };
322
+
866
323
  // One guard-log line per notify decision: `notify: posted|skipped (<why>)`. Fire-and-forget:
867
324
  // the decision never awaits the post; a failed or slow post logs one line and never blocks
868
325
  // or retries.
@@ -1070,14 +527,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1070
527
  const content = unhanded(asString(c.id) || "sub", plans.find(file => prompt.includes(file)) ?? null);
1071
528
  return content ? { message: { customType: "main-guard.rules", content, display: false } } : undefined;
1072
529
  }
1073
- if (limitTickArmed) {
1074
- stopLimitTick();
1075
- adapterLog(cfg, "RATE-LIMIT tick cancelled: owner message (probe count kept)");
1076
- }
530
+ rateLimit.onOwnerPrompt();
1077
531
  const d = checkInject({ inject: prompt, agent: "main" }, cfg);
1078
532
  callsSinceStop = d.state?.callsSinceStop ?? callsSinceStop;
1079
533
  idleStops = d.state?.idleStops ?? idleStops;
1080
- const notice = rolloverNotice(ctx);
534
+ const notice = rollover.notice(ctx);
1081
535
  // A turn the harness starts from the guard's own stop continuation is not an owner
1082
536
  // message: D4 (owner-correction) only sees real prompts; D1/D3 run either way.
1083
537
  // Machine prompts (guard continuation, rollover note request, handoff note) are not owner messages.
@@ -1146,7 +600,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1146
600
  const rc = lastMainRc;
1147
601
  runningJobs = rc?.runningJobs();
1148
602
  if (cfg.rollover.enabled && rc) {
1149
- const why = spawnRefusal(rolloverSnapshot(rc).state, runningJobs ?? []);
603
+ const why = spawnRefusal(rollover.snapshot(rc).state, runningJobs ?? []);
1150
604
  if (why) {
1151
605
  const tasks = Array.isArray(input.tasks) ? input.tasks : [];
1152
606
  adapterLog(cfg, `BLOCK spawn ${String(asRecord(tasks[0]).agent ?? "task")}: rollover pending`);
@@ -1203,7 +657,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1203
657
  const steer = ownerAnswerSteer(cfg, nowSec());
1204
658
  if (steer) pi.sendUserMessage(steer);
1205
659
  }
1206
- onSizeCheck("tool_result", event, ctx);
660
+ rollover.onSizeCheck("tool_result", event, ctx);
1207
661
  const e = asRecord(event);
1208
662
  const c = asCtx(ctx);
1209
663
  const id = asString(e.toolCallId);
@@ -1320,7 +774,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1320
774
  const c = asCtx(ctx);
1321
775
  if (c.hasAgent && c.kind !== "main") return;
1322
776
  // A relaunch is requested: omp shuts down at the next idle, so the stop must not be continued.
1323
- if (relaunched) {
777
+ if (rollover.isRelaunched()) {
1324
778
  adapterLog(cfg, "notify: skipped (relaunch requested)");
1325
779
  return undefined;
1326
780
  }
@@ -1333,7 +787,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1333
787
  // A turn that ended on a provider rate limit waits it out (plan 20261025_0640): ALLOW before
1334
788
  // the rollover and queue decisions — any block here would re-ask straight into the limit —
1335
789
  // and without touching the idle-stop counters: checkStop is not consulted.
1336
- const rl = rateLimitOf(reply);
790
+ const rl = rateLimit.rateLimitOf(reply);
1337
791
  if (rl) {
1338
792
  // Who is rate-limited is live data (plan 20261025_1700 P1): the error text's own reset
1339
793
  // time, else the fallback wait. Best effort — a failed write never changes the stop.
@@ -1343,28 +797,28 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1343
797
  } catch (err) {
1344
798
  adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
1345
799
  }
1346
- onRateLimitedStop(c, named, reply?.errorMessage ?? "", reply?.model ?? "");
800
+ rateLimit.onRateLimitedStop(c, named, reply?.errorMessage ?? "", reply?.model ?? "");
1347
801
  return undefined;
1348
802
  }
1349
803
  // Any turn that ends without a rate limit ends the episode and disarms its resume timer.
1350
- disarmRateEpisode();
804
+ rateLimit.disarmEpisode();
1351
805
  // A pending rollover decides the stop and checkStop is not consulted: its queue, incident and cancel
1352
806
  // blocks would hold Main at a wait the new session raises again through main-start, and its "spawn an
1353
807
  // agent" text is refused while the rollover is pending.
1354
808
  const rc = cfg.rollover.enabled ? asRolloverCtx(ctx) : null;
1355
809
  if (rc) {
1356
- const snap = rolloverSnapshot(rc);
810
+ const snap = rollover.snapshot(rc);
1357
811
  if (snap.state === "need-note") {
1358
812
  adapterLog(cfg, "BLOCK stop: rollover need-note");
1359
813
  notifyHandback(reply, "blocked session_stop");
1360
814
  stopBlocked = true;
1361
- return { decision: "block", reason: noteRequestFor(rc, snap) };
815
+ return { decision: "block", reason: rollover.noteRequestFor(rc, snap) };
1362
816
  }
1363
817
  if (snap.state === "ready" || snap.state === "wait-jobs") {
1364
818
  adapterLog(cfg, `ALLOW stop: rollover ${snap.state}`);
1365
819
  recordTurnAnswer(reply);
1366
820
  // Under the launcher a ready rollover starts now (not a hand-back to the owner).
1367
- const handsToOwner = !(snap.state === "ready" && requestRelaunch(rc, notePath(rc.sessionId, mainStateDir(cfg))));
821
+ const handsToOwner = !(snap.state === "ready" && rollover.requestRelaunch(rc, notePath(rc.sessionId, mainStateDir(cfg))));
1368
822
  if (handsToOwner) notifyHandback(reply, "allowed session_stop");
1369
823
  else adapterLog(cfg, "notify: skipped (relaunch requested)");
1370
824
  return undefined;
@@ -1383,221 +837,17 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1383
837
  return { decision: "block", reason: d.reason };
1384
838
  });
1385
839
 
1386
- // Session rollover (src/core/rollover.ts). Main's session size decides when a handoff note is
1387
- // asked for at turn end (a sendMessage that triggers Main's next turn). The owner's next message
1388
- // then starts a fresh session from that note; under `neurastream main` the launcher starts it at
1389
- // once. The size and the installed version are re-read at every turn end and tool result; the
1390
- // note request goes out once per session file and note state.
1391
- // The version this process loaded at start: the plugin code that is actually running.
1392
- const loadedVersion = packageVersion(packageJsonPath());
1393
- let crossed: { file: string; atMs: number } | null = null;
1394
- // The note request already sent, keyed by session file + note mtime at send time ("none" when
1395
- // no note exists): a note that expires while jobs run falls back to need-note with a key no
1396
- // request was sent for, so it gets exactly one new request and never a loop.
1397
- let asked: string | null = null;
1398
- let waitNoticeMs = 0;
1399
-
1400
- const rolloverSnapshot = (c: RolloverCtx): { state: RolloverState; noteMtimeMs: number | null; stale: boolean; liveVersion: string | null } => {
1401
- const nowMs = Date.now();
1402
- const bytes = sizeOf(c.sessionFile);
1403
- const maxMb = cfg.rollover.max_session_mb;
1404
- const noteMtimeMs = mtimeOf(notePath(c.sessionId, mainStateDir(cfg)));
1405
- const liveVersion = packageVersion(packageJsonPath());
1406
- const stale = liveVersion === null || loadedVersion === null || liveVersion !== loadedVersion;
1407
- if (stale) {
1408
- // Note freshness is measured against the crossing: a stale session counts as crossed
1409
- // from the first check that saw it, whatever its size.
1410
- if (crossed?.file !== c.sessionFile) crossed = { file: c.sessionFile, atMs: nowMs };
1411
- } else if (bytes < maxMb * 1024 * 1024) crossed = null;
1412
- else if (crossed?.file !== c.sessionFile) crossed = { file: c.sessionFile, atMs: nowMs };
1413
- return {
1414
- state: rolloverState({
1415
- sessionBytes: bytes,
1416
- maxMb,
1417
- runningJobs: c.runningJobs(),
1418
- crossedAtMs: crossed?.atMs ?? null,
1419
- noteMtimeMs,
1420
- nowMs,
1421
- stale,
1422
- }),
1423
- noteMtimeMs,
1424
- stale,
1425
- liveVersion,
1426
- };
1427
- };
840
+ // ---- ordered agent_end pipeline (consolidates all 7 turn-end stages in exact sequence) ----
1428
841
 
1429
- // The note request for a state. A stale install names both versions in place of the size line.
1430
- const noteRequestFor = (c: RolloverCtx, snap: { stale: boolean; liveVersion: string | null }): string => {
1431
- const reason = snap.stale ? `neurastream on disk is ${snap.liveVersion ?? "unknown"}, this session runs ${loadedVersion ?? "unknown"}` : undefined;
1432
- return noteRequest(notePath(c.sessionId, mainStateDir(cfg)), reason);
1433
- };
1434
-
1435
- let relaunched = false;
1436
- // omp 18.11.1 defers an extension shutdown: it re-checks only when shutdown() is called again or
1437
- // an owner submission finishes, so a refused exit once left a dead UI that swallowed every owner
1438
- // message (I-20261024-4). One unref'd timer per request: if omp still has not exited
1439
- // rollover.exit_grace_s after the request, the adapter rolls over in-process. The timer keeps its
1440
- // own clearer: session_shutdown cancels the fallback when omp really exits.
1441
- let clearGrace: (() => void) | null = null;
1442
- const armGraceTimer = (c: RolloverCtx): void => {
1443
- clearGrace?.();
1444
- const t = setTimeout(() => {
1445
- clearGrace = null;
1446
- exitGraceElapsed(c);
1447
- }, cfg.rollover.exit_grace_s * 1000);
1448
- if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
1449
- clearGrace = () => {
1450
- clearTimeout(t);
1451
- clearGrace = null;
1452
- };
1453
- };
1454
-
1455
- // One in-process rollover at a time: while it waits for idle, the size check must not start
1456
- // a relaunch over it.
1457
- let flight: string[] | null = null;
1458
-
1459
- // The one in-process rollover, the exit-grace fallback: gather the generated state, wait for
1460
- // idle, then start a fresh session whose first message is the handoff. A state change during
1461
- // the wait sends the owner's text to this session as an ordinary message.
1462
- const rolloverInProcess = async (c: RolloverCtx, owner: string[], notice: string): Promise<void> => {
1463
- const previous = c.sessionFile;
1464
- const path = notePath(c.sessionId, mainStateDir(cfg));
1465
- flight = owner;
1466
- try {
1467
- c.notify(notice);
1468
- const generated = [
1469
- await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg), providers: ompProviders(cfg) }),
1470
- holdsBlock(q.ownerHolds(cfg.paths)),
1471
- ].join("\n");
1472
- const note = readFileSync(path, "utf8");
1473
- adapterLog(cfg, `rollover: new session from ${previous}; note ${path}`);
1474
- await c.waitForIdle();
1475
- const again = rolloverSnapshot(c).state;
1476
- if (relaunched || again !== "ready") {
1477
- c.notify(`main-rollover: the state changed while waiting for idle (${relaunched ? "relaunch requested" : again}); no new session.`);
1478
- // The owner's text is not lost: it goes to this session as an ordinary message.
1479
- const pending = owner.filter(s => s !== "").join("\n");
1480
- if (pending !== "") pi.sendUserMessage(pending);
1481
- return;
1482
- }
1483
- const r = asRecord(await c.newSession({ parentSession: previous }));
1484
- if (r.cancelled === true) return;
1485
- // Read after the await: owner messages that arrived during newSession are part of the handoff.
1486
- const handoff = buildHandoff({
1487
- generated,
1488
- note,
1489
- previousSessionFile: previous,
1490
- ownerMessage: owner.filter(s => s !== "").join("\n"),
1491
- unanswered: unansweredOwnerMessages(readOwnerMessages(cfg.paths), readOwnerAnswers(cfg.paths)),
1492
- });
1493
- pi.sendUserMessage(handoff);
1494
- } finally {
1495
- flight = null;
1496
- }
1497
- };
1498
-
1499
- // Clear the rollover episode state so a later createOmpAdapter setup in the same
1500
- // process starts clean: a stale armGraceTimer would otherwise fire with this
1501
- // closure's cfg and recreate torn-down dirs (P3c).
1502
- const clearRolloverState = (): void => {
1503
- clearGrace?.();
1504
- relaunched = false;
1505
- flight = null;
1506
- };
1507
- // Clear the previous adapter's armed grace timer before this one overwrites the pointer (P3c).
1508
- // Do not release heldSessionLock: this runs on every factory re-entry, and the lock is
1509
- // process-lifetime (plan 20261103_1146 P4). reset() still releases it.
1510
- activeAdapterReset?.();
1511
- activeAdapterReset = (): void => {
1512
- clearRolloverState();
1513
- stopLimitTick();
1514
- };
1515
- // The launcher restarts omp: the request file carries the note and the editor draft, and omp
1516
- // shuts down only after the file is written. A failed write keeps the session running.
1517
- // Returns whether the request was written.
1518
- const requestRelaunch = (c: RolloverCtx, note: string, draft = c.draft()): boolean => {
1519
- const reqFile = relaunchPath(mainStateDir(cfg));
1520
- try {
1521
- mkdirSync(dirname(reqFile), { recursive: true });
1522
- writeFileSync(reqFile, `${JSON.stringify({ previousSessionFile: c.sessionFile, notePath: note, draft })}\n`);
1523
- } catch (err) {
1524
- adapterLog(cfg, `rollover: relaunch request not written: ${String(err)}`);
1525
- return false;
1526
- }
1527
- relaunched = true;
1528
- adapterLog(cfg, `rollover: relaunch requested from ${c.sessionFile}`);
1529
- c.shutdown();
1530
- armGraceTimer(c);
1531
- return true;
1532
- };
1533
-
1534
- // An owner message typed while the relaunch is pending joins the request's draft, in order; the
1535
- // launcher's handoff carries it. The rewrite is atomic, so the launcher never reads a partial file.
1536
- const appendToRelaunch = (text: string): boolean => {
1537
- const reqFile = relaunchPath(mainStateDir(cfg));
1538
- try {
1539
- const req = asRecord(JSON.parse(readFileSync(reqFile, "utf8")));
1540
- const draft = [asString(req.draft), text].filter(s => s !== "").join("\n");
1541
- const tmp = `${reqFile}.tmp`;
1542
- writeFileSync(tmp, `${JSON.stringify({ ...req, draft })}\n`);
1543
- renameSync(tmp, reqFile);
1544
- return true;
1545
- } catch (err) {
1546
- adapterLog(cfg, `rollover: owner message not added to the relaunch request: ${String(err)}`);
1547
- return false;
1548
- }
1549
- };
1550
-
1551
- // The grace elapsed without a session_shutdown: omp refused the exit. Read the request's draft,
1552
- // drop the request and roll over here, so the owner's messages reach a live session instead of a
1553
- // dead UI. The owner-away text stands in when nothing was typed.
1554
- const exitGraceElapsed = (c: RolloverCtx): void => {
1555
- adapterLog(cfg, `rollover: omp did not exit within ${cfg.rollover.exit_grace_s}s; rolling over in-process`);
1556
- const reqFile = relaunchPath(mainStateDir(cfg));
1557
- let draft = "";
1558
- try {
1559
- draft = asString(asRecord(JSON.parse(readFileSync(reqFile, "utf8"))).draft);
1560
- } catch {}
1561
- rmSync(reqFile, { force: true });
1562
- relaunched = false;
1563
- rolloverInProcess(c, [draft.trim() === "" ? OWNER_AWAY : draft], "rollover: omp did not restart; continuing in a new session here").catch((err: unknown) => {
1564
- adapterLog(cfg, `rollover: in-process rollover failed: ${err instanceof Error ? err.message : String(err)}`);
1565
- });
1566
- };
1567
-
1568
- const onSizeCheck = (kind: "tool_result" | "agent_end", e: unknown, ctx: unknown): void => {
1569
- const c = asRolloverCtx(ctx);
1570
- if (!cfg.rollover.enabled || !c || !isMain(ctx)) return;
1571
- const snap = rolloverSnapshot(c);
1572
- const key = `${c.sessionFile}:${snap.noteMtimeMs ?? "none"}`;
1573
- // A terminal run end: omp 18.11.1 sets willContinue on a non-terminal agent_end.
1574
- const terminal = kind === "agent_end" && asRecord(e).willContinue !== true;
1575
- if (snap.state === "need-note" && asked !== key) {
1576
- asked = key;
1577
- pi.sendMessage(
1578
- { customType: "main-guard.rollover", content: noteRequestFor(c, snap), display: false },
1579
- { triggerTurn: true, deliverAs: "nextTurn" },
1580
- );
1581
- } else if (terminal && snap.state === "ready" && !relaunched && flight === null) {
1582
- // flight !== null: an in-process rollover (the fallback) owns this session's end.
1583
- requestRelaunch(c, notePath(c.sessionId, mainStateDir(cfg)));
1584
- } else if (terminal && relaunched) {
1585
- // A tool result mid-run never restarts the session (I-20261024-4), and omp's interactive
1586
- // mode re-runs its deferred exit check only when shutdown() is called again: re-arm at
1587
- // every later terminal run end instead of waiting for an owner message.
1588
- c.shutdown();
1589
- }
1590
- };
1591
- pi.on("agent_end", (e, ctx) => onSizeCheck("agent_end", e, ctx));
1592
- // Hand-back without a session_stop (plan 20261025_0130): while an async job is pending omp
1593
- // fires agent_end with willContinue:true and SKIPS session_stop — this deferred hand-back
842
+ // Stage 2: Hand-back without a session_stop (plan 20261025_0130): while an async job is pending
843
+ // omp fires agent_end with willContinue:true and SKIPS session_stop — this deferred hand-back
1594
844
  // posts from the event's own messages. omp also sets willContinue after a BLOCKED stop
1595
845
  // (sessionStopWillContinue) and for todo/plan-mode/rewind continuations, so a post here needs
1596
846
  // both: no blocked stop just decided (the flag), and an async job really pending. A terminal
1597
847
  // end (willContinue unset) is not a hand-back: the session_stop that follows it decides. A
1598
848
  // mid-run continuation — tool calls, or a non-"stop" reason such as an auto-retry — posts
1599
849
  // nothing.
1600
- pi.on("agent_end", (e, ctx) => {
850
+ const onDeferredHandback = (e: unknown, ctx: unknown): void => {
1601
851
  if (!isMain(ctx)) return;
1602
852
  if (asRecord(e).willContinue !== true) return;
1603
853
  if (stopBlocked) {
@@ -1610,7 +860,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1610
860
  // hand-back opens the episode instead of logging "no reply text" — its reply carries an
1611
861
  // error, no text. A mid-run continuation (tool calls, auto-retry) is not a turn end: the
1612
862
  // episode state stays as it is.
1613
- const rl = rateLimitOf(reply);
863
+ const rl = rateLimit.rateLimitOf(reply);
1614
864
  if (rl) {
1615
865
  // The same one parse as session_stop (plan 20261027_1500 P1/P3): the error text's own
1616
866
  // reset time, else the fallback wait. Best effort — a failed write never changes the stop.
@@ -1620,7 +870,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1620
870
  } catch (err) {
1621
871
  adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
1622
872
  }
1623
- onRateLimitedStop(asCtx(ctx), named, reply?.errorMessage ?? "", reply?.model ?? "");
873
+ rateLimit.onRateLimitedStop(asCtx(ctx), named, reply?.errorMessage ?? "", reply?.model ?? "");
1624
874
  return;
1625
875
  }
1626
876
  const jobCount = asRolloverCtx(ctx)?.runningJobs().length ?? 0;
@@ -1630,7 +880,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1630
880
  }
1631
881
  if (!reply || !reply.text) {
1632
882
  // A turn that ended on some other no-text outcome is a turn end without a rate limit.
1633
- disarmRateEpisode();
883
+ rateLimit.disarmEpisode();
1634
884
  adapterLog(cfg, "notify: skipped (no reply text, agent_end hand-back)");
1635
885
  return;
1636
886
  }
@@ -1642,7 +892,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1642
892
  return;
1643
893
  }
1644
894
  // A real hand-back: the turn ended without a rate limit — the episode is over.
1645
- disarmRateEpisode();
895
+ rateLimit.disarmEpisode();
1646
896
  recordTurnAnswer(reply);
1647
897
  // A deferred hand-back fires no session_stop: reset the per-turn cap here (I-20261030-24),
1648
898
  // record the hand-back for the owner-answer wait (P9), and steer a promise like checkStop
@@ -1653,18 +903,12 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1653
903
  pi.sendUserMessage(STOP_PLAN_OFFER_REFUSAL);
1654
904
  }
1655
905
  notifyHandback(reply, "agent_end hand-back");
1656
- });
1657
- // Turn end: page answers that arrived during the turn go out (P3b), then open plans that now
1658
- // WAIT on the owner ping Discord (P3b). Main only.
1659
- pi.on("agent_end", (_e, ctx) => {
1660
- if (!isMain(ctx)) return;
1661
- deliverOwnerInbox(pi, cfg);
1662
- notifyWaitingPlans();
1663
- });
1664
- // Write-check deferral (I-20261028-166): at a session's own turn end its still-present deferred
1665
- // findings go out — Main by steer (the only session sendUserMessage is proven to reach), a
1666
- // subagent through the adapter log; cleared per session, so it is never repeated.
1667
- pi.on("agent_end", (_e, ctx) => {
906
+ };
907
+
908
+ // Stage 4: Write-check deferral (I-20261028-166): at a session's own turn end its still-present
909
+ // deferred findings go out — Main by steer (the only session sendUserMessage is proven to
910
+ // reach), a subagent through the adapter log; cleared per session, so it is never repeated.
911
+ const onDeferredWriteCheck = (ctx: unknown): void => {
1668
912
  const c = asCtx(ctx);
1669
913
  const wc = cfg.write_check;
1670
914
  const key = c.id ?? "main";
@@ -1683,40 +927,45 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1683
927
  if (steers.length === 0) return;
1684
928
  if (!c.hasAgent || c.kind === "main") pi.sendUserMessage(steers.join("\n"));
1685
929
  else adapterLog(cfg, `WRITE-CHECK deferred still present: ${steers.join(" | ")}`);
1686
- });
930
+ };
1687
931
 
1688
- // Terminal hand-back (plan 20261028_1545 P2): a willContinue agent_end keeps the turn going
1689
- // (blocked stop, todo/plan-mode continuation, deferred hand-back); only its absence ends the
1690
- // turn — the budget resets here and on the deferred hand-back above (I-20261030-24).
1691
932
  pi.on("agent_end", (e, ctx) => {
1692
- if (!isMain(ctx)) return;
1693
- if (asRecord(e).willContinue === true) return;
1694
- resetMainCalls(cfg.paths);
1695
- ownerAnswerHandback(nowSec(), cfg.paths);
1696
- });
1697
- // P4k backstop (plan 20261028_1600): a named review spawn that ends with no verdict recorded at its edit is judged here, from its own plan file; the note tells Main at its next prompt.
1698
- pi.on("agent_end", (_e, ctx) => {
933
+ // 1. Session rollover size/version check & relaunch re-arm
934
+ rollover.onSizeCheck("agent_end", e, ctx);
935
+ // 2. Deferred hand-back notify / rate-limit handling (when willContinue === true)
936
+ onDeferredHandback(e, ctx);
937
+ // 3. Deliver owner inbox & ping Discord on newly waiting plans (Main only)
938
+ if (isMain(ctx)) {
939
+ deliverOwnerInbox(pi, cfg);
940
+ notifyWaitingPlans();
941
+ }
942
+ // 4. Report still-present deferred write-check findings for this session
943
+ onDeferredWriteCheck(ctx);
944
+ // 5. Terminal hand-back: reset Main's per-turn call budget & record answer hand-back
945
+ if (isMain(ctx) && asRecord(e).willContinue !== true) {
946
+ resetMainCalls(cfg.paths);
947
+ ownerAnswerHandback(nowSec(), cfg.paths);
948
+ }
949
+ // 6. P4k backstop: check if a named review subagent ended without recording a verdict
1699
950
  const c = asCtx(ctx);
1700
- if (c.kind !== "sub" || !c.id) return;
1701
- const note = reviewSpawnEnd(c.id, cfg);
1702
- if (note) pendingReviewNotes.push(note);
951
+ if (c.kind === "sub" && c.id) {
952
+ const note = reviewSpawnEnd(c.id, cfg);
953
+ if (note) pendingReviewNotes.push(note);
954
+ }
955
+ // 7. Recall topics: spawn background segmentation when due (Main only)
956
+ if (isMain(ctx) && cfg.recall.topics_model !== "" && topicsDue(appendedSinceSpawn(), cfg.recall.topics_every)) {
957
+ markTopicsSpawned();
958
+ spawnTopics(cfg, ctx, ["recall", "topics"]);
959
+ }
1703
960
  });
1704
961
 
1705
- pi.on("agent_end", (_e, ctx) => {
1706
- if (!isMain(ctx) || cfg.recall.topics_model === "") return;
1707
- if (!topicsDue(appendedSinceSpawn(), cfg.recall.topics_every)) return;
1708
- markTopicsSpawned();
1709
- spawnTopics(cfg, ctx, ["recall", "topics"]);
1710
- });
1711
962
  pi.on("session_shutdown", (_e, ctx) => {
1712
- if (!isMain(ctx) || cfg.recall.topics_model === "") return;
1713
- spawnTopics(cfg, ctx, ["recall", "topics", "--close"]);
1714
- });
1715
-
1716
- // omp is really shutting down: the exit-grace fallback must not fire. A clean shutdown is also
1717
- // the owner's last stamp (P2 d): verify first, then record the state that pass confirmed.
1718
- pi.on("session_shutdown", () => {
1719
- clearGrace?.();
963
+ if (isMain(ctx) && cfg.recall.topics_model !== "") {
964
+ spawnTopics(cfg, ctx, ["recall", "topics", "--close"]);
965
+ }
966
+ // omp is really shutting down: the exit-grace fallback must not fire. A clean shutdown is also
967
+ // the owner's last stamp (P2 d): verify first, then record the state that pass confirmed.
968
+ rollover.clearGrace();
1720
969
  stampPlannerState(freshConfig);
1721
970
  });
1722
971
 
@@ -1733,184 +982,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1733
982
  };
1734
983
  });
1735
984
 
1736
- /** Wait-jobs notice for Main's next turn, throttled; null otherwise. The note request goes out at turn end. */
1737
- const rolloverNotice = (ctx: unknown): string | null => {
1738
- const c = asRolloverCtx(ctx);
1739
- if (!cfg.rollover.enabled || !c) return null;
1740
- const state = rolloverSnapshot(c).state;
1741
- if (state === "wait-jobs" && Date.now() - waitNoticeMs >= WAIT_NOTICE_MS) {
1742
- waitNoticeMs = Date.now();
1743
- const jobs = c.runningJobs().join(", ");
1744
- return `Session rollover: the handoff note is ready, but own jobs are still running (${jobs}). A rollover would cancel them, so the owner's messages stay in this session until they finish.`;
1745
- }
1746
- return null;
1747
- };
1748
-
1749
- // Chat unlock + autonomy tiers (guards.chat_unlock): the owner's whole message "unlock"/
1750
- // "unlock N"/"lock" moves the guard unlock file, "tier <name>" sets the autonomy tier and the
1751
- // approve phrase (autonomy.go_phrase, default "go push") approves one strict landing
1752
- // (src/core/queue/lib.ts chatUnlock, src/core/autonomy.ts
1753
- // chatTier/chatGo). Only prompts the owner really typed
1754
- // count: the local terminal (input event, source "interactive") and collab guest prompts from
1755
- // write peers. This handler is registered BEFORE the rollover input handler below, so the unlock
1756
- // wins while a rollover is ready or in flight (emitInput short-circuits on { handled: true }).
1757
- // An applied unlock also wakes Main (sendUserMessage: idle → a new turn, mid-turn → the steer
1758
- // queue), the same message the phone-page unlock sends through the owner inbox.
1759
- const notifyUnlock = (ctx: unknown, r: { command?: "unlock" | "lock"; minutes?: number; until?: number }): void => {
1760
- const c = asRolloverCtx(ctx);
1761
- if (r.command === "unlock" && r.minutes !== undefined && r.until !== undefined) {
1762
- const hhmm = strftime(r.until, "%H:%M");
1763
- c?.notify(`guard unlocked for ${r.minutes} min (until ${hhmm})`);
1764
- pi.sendUserMessage(`Owner unlocked the guards in chat for ${r.minutes} min (until ${hhmm}). Do the step that waited on the unlock now.`);
1765
- } else if (r.command === "lock") {
1766
- c?.notify("guard locked again");
1767
- }
1768
- };
1769
- // The tier switch and the one-shot `go` travel the same two owner paths and answer the same way.
1770
- const notifyTier = (ctx: unknown, r: { tier?: Tier }): void => {
1771
- const c = asRolloverCtx(ctx);
1772
- if (!c || r.tier === undefined) return;
1773
- c.notify(`tier now ${r.tier}`);
1774
- };
1775
- const notifyGo = (ctx: unknown, r: { minutes?: number }): void => {
1776
- const c = asRolloverCtx(ctx);
1777
- if (!c || r.minutes === undefined) return;
1778
- c.notify(`${cfg.autonomy.go_phrase}: one push/merge approved for ${r.minutes} min`);
1779
- };
1780
- pi.on("input", (event, ctx) => {
1781
- if (!cfg.guards.chat_unlock || !isMain(ctx)) return undefined;
1782
- const e = asRecord(event);
1783
- if (asString(e.source) !== "interactive") return undefined;
1784
- const text = asString(e.text);
1785
- const t = chatTier(text, cfg, "interactive");
1786
- if (t.applied) {
1787
- notifyTier(ctx, t);
1788
- return { handled: true };
1789
- }
1790
- const p = chatPlanner(text, cfg, "interactive");
1791
- if (p.applied) {
1792
- asRolloverCtx(ctx)?.notify(`planner now ${p.planner}`);
1793
- return { handled: true };
1794
- }
1795
- const g = chatGo(text, cfg, "interactive");
1796
- if (g.applied) {
1797
- notifyGo(ctx, g);
1798
- return { handled: true };
1799
- }
1800
- const a = chatApprove(text, cfg, "interactive");
1801
- if (a.applied) {
1802
- asRolloverCtx(ctx)?.notify(`approved ${basename(a.plan)}`);
1803
- return { handled: true };
1804
- }
1805
- if (a.problem !== undefined) {
1806
- asRolloverCtx(ctx)?.notify(a.problem);
1807
- return { handled: true };
1808
- }
1809
- const r = q.chatUnlock(asString(e.text), cfg, "interactive");
1810
- if (!r.applied) return undefined;
1811
- notifyUnlock(ctx, r);
1812
- return { handled: true };
1813
- });
1814
- // A collab guest prompt (collab/host.ts #handlePrompt, write peers only) is NOT an input event:
1815
- // it is session.promptCustomMessage({ customType: "collab-prompt", details: { from },
1816
- // attribution: "user" }), which lands in the agent context — the adapter sees it on the
1817
- // "context" event (types.ts ContextEvent, the messages about to go to the LLM). The message
1818
- // stays in the transcript, so later LLM calls replay it: a seen key (timestamp + text) is acted
1819
- // on once, and a resumed session replaying old prompts is stopped by the age limit.
1820
- const seenChatPrompts = new Set<string>();
1821
- const CHAT_PROMPT_MAX_AGE_MS = 10 * 60_000;
1822
- pi.on("context", (event, ctx) => {
1823
- if (!isMain(ctx)) return undefined;
1824
- const messages = asRecord(event).messages;
1825
- if (!Array.isArray(messages)) return undefined;
1826
- if (cfg.guards.chat_unlock) {
1827
- for (const raw of messages) {
1828
- const m = asRecord(raw);
1829
- if (m.role !== "custom" || m.customType !== "collab-prompt" || m.attribution !== "user") continue;
1830
- const from = asString(asRecord(m.details).from);
1831
- if (from === "") continue;
1832
- const text =
1833
- typeof m.content === "string"
1834
- ? m.content
1835
- : Array.isArray(m.content)
1836
- ? m.content.map(c => asString(asRecord(c).text)).join("")
1837
- : "";
1838
- const timestamp = typeof m.timestamp === "number" ? m.timestamp : 0;
1839
- if (Date.now() - timestamp > CHAT_PROMPT_MAX_AGE_MS) continue;
1840
- const key = `${timestamp}:${text}`;
1841
- if (seenChatPrompts.has(key)) continue;
1842
- seenChatPrompts.add(key);
1843
- const r = q.chatUnlock(text, cfg, `collab:${from}`);
1844
- if (r.applied) {
1845
- notifyUnlock(ctx, r);
1846
- continue;
1847
- }
1848
- const t = chatTier(text, cfg, `collab:${from}`);
1849
- if (t.applied) {
1850
- notifyTier(ctx, t);
1851
- continue;
1852
- }
1853
- const g = chatGo(text, cfg, `collab:${from}`);
1854
- if (g.applied) notifyGo(ctx, g);
1855
- }
1856
- }
1857
- const rule = { pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz };
1858
- let changed = false;
1859
- const mapped = messages.map(raw => {
1860
- const message = asRecord(raw);
1861
- if (typeof message.content === "string") {
1862
- const content = annotateResetTimes(message.content, rule);
1863
- if (content === message.content) return raw;
1864
- changed = true;
1865
- return { ...message, content };
1866
- }
1867
- if (!Array.isArray(message.content)) return raw;
1868
- let contentChanged = false;
1869
- const content = message.content.map(part => {
1870
- const block = asRecord(part);
1871
- if (typeof block.text !== "string") return part;
1872
- const text = annotateResetTimes(block.text, rule);
1873
- if (text === block.text) return part;
1874
- contentChanged = true;
1875
- return { ...block, text };
1876
- });
1877
- if (!contentChanged) return raw;
1878
- changed = true;
1879
- return { ...message, content };
1880
- });
1881
- return changed ? { messages: mapped } : undefined;
1882
- });
1883
-
1884
- // The relaunch is the only rollover path: a plain interactive message in the ready state
1885
- // requests it, and every such message joins the pending request's draft, in order.
1886
- pi.on("input", (event, ctx) => {
1887
- const e = asRecord(event);
1888
- const c = asRolloverCtx(ctx);
1889
- const text = asString(e.text);
1890
- if (!cfg.rollover.enabled || !c || !isMain(ctx)) return undefined;
1891
- if (asString(e.source) !== "interactive" || text === "" || text.startsWith("/")) return undefined;
1892
- if (!relaunched) {
1893
- if (rolloverSnapshot(c).state !== "ready") return undefined;
1894
- // The message is the request's first owner text, so the editor draft is not carried.
1895
- if (!requestRelaunch(c, notePath(c.sessionId, mainStateDir(cfg)), "")) return undefined;
1896
- }
1897
- if (appendToRelaunch(text)) c.notify("rollover in progress: your message goes to the new session");
1898
- else c.notify("rollover in progress: your message could not be saved and was not sent; send it again after the rollover");
1899
- // omp re-checks its deferred exit only when shutdown() is called again: re-arm per message.
1900
- c.shutdown();
1901
- return { handled: true };
1902
- });
1903
-
1904
- // The rollover starts on its own (size + idle), and the owner's next message joins the
1905
- // pending relaunch; the command only says so.
1906
- pi.registerCommand("main-rollover", {
1907
- description: "Start a fresh session from Main's handoff note; the rest of the message is the owner's first message",
1908
- handler: async (_args: unknown, ctx: unknown) => {
1909
- const c = asRolloverCtx(ctx);
1910
- if (!c) return;
1911
- c.notify("main-rollover: under neurastream main the rollover starts from your next message, not from this command.");
1912
- },
1913
- });
985
+ // Register chat commands (unlock/tier/planner/go/approve + context) BEFORE rollover input
986
+ // so unlock wins while a rollover is ready or in flight.
987
+ registerChatCommands(pi, getCfg);
988
+ pi.on("input", (event, ctx) => rollover.handleInput(event, ctx));
989
+ rollover.registerCommand();
1914
990
  }
1915
991
 
1916
992
  /** Clear the active adapter's rollover state and release the session lock. Tests call this in