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.
- package/package.json +1 -1
- package/src/adapters/index.ts +3 -2
- package/src/adapters/omp/adapter.ts +2 -1
- package/src/adapters/omp/auto-close.ts +64 -0
- package/src/adapters/omp/chat-commands.ts +161 -0
- package/src/adapters/omp/inbox.ts +221 -0
- package/src/adapters/omp/index.ts +115 -1039
- package/src/adapters/omp/launch.ts +31 -3
- package/src/adapters/omp/rate-limit-controller.ts +196 -0
- package/src/adapters/omp/rollover-controller.ts +334 -0
- package/src/adapters/omp/types.ts +143 -0
- package/src/cli/commands.ts +33 -2
- package/src/cli/dispatch.ts +37 -16
- package/src/cli/recall.ts +3 -2
- package/src/cli/results-build.ts +1 -1
- package/src/cli/workspace.ts +13 -2
- package/src/core/adapter.ts +16 -0
- package/src/core/blockers.ts +326 -30
- package/src/core/file-lock.ts +71 -12
- package/src/core/guards/plan-edit.ts +338 -0
- package/src/core/guards/planner.ts +70 -0
- package/src/core/guards/review.ts +391 -0
- package/src/core/guards/spawn.ts +699 -0
- package/src/core/guards/state.ts +581 -0
- package/src/core/guards/stop.ts +235 -0
- package/src/core/guards/tool.ts +541 -0
- package/src/core/guards.ts +12 -2658
- package/src/core/incidents.ts +125 -91
- package/src/core/machine-guard.ts +23 -5
- package/src/core/main-start.ts +10 -8
- package/src/core/owner-topics.ts +2 -13
- package/src/core/owner-ui/auth.ts +164 -0
- package/src/core/owner-ui/data.ts +437 -0
- package/src/core/owner-ui/handlers.ts +250 -0
- package/src/core/owner-ui/messages.ts +209 -0
- package/src/core/owner-ui/render.ts +714 -0
- package/src/core/owner-ui/results.ts +266 -0
- package/src/core/owner-ui/server.ts +142 -0
- package/src/core/owner-ui.ts +11 -2121
- package/src/core/page-notes.ts +25 -0
- package/src/core/pages.ts +452 -77
- package/src/core/plan-approval.ts +12 -14
- package/src/core/queue/lib.ts +88 -39
- package/src/core/queue-cancel.ts +21 -17
- package/src/core/queue-close.ts +48 -23
- package/src/core/secret-redact.ts +65 -14
- package/src/core/tailscale.ts +79 -3
- package/src/core/team-client.ts +13 -2
- package/src/core/uninstall.ts +2 -0
|
@@ -7,12 +7,11 @@ import { spawn } from "node:child_process";
|
|
|
7
7
|
import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
8
8
|
import { tmpdir } from "node:os";
|
|
9
9
|
import { basename, dirname, join } from "node:path";
|
|
10
|
-
import type { LaunchOptions } from "../../core/adapter.ts";
|
|
10
|
+
import type { CompleteRequest, CompleteResult, LaunchOptions } from "../../core/adapter.ts";
|
|
11
11
|
import type { Config } from "../../core/config.ts";
|
|
12
12
|
import { readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
|
|
13
13
|
import { mainStartText } from "../../core/main-start.ts";
|
|
14
14
|
import { appendMetric } from "../../core/metrics.ts";
|
|
15
|
-
import type { CompleteRequest, CompleteResult } from "../../core/owner-topics.ts";
|
|
16
15
|
import { tryLock } from "../../core/file-lock.ts";
|
|
17
16
|
import { MAIN_ID_RE, mainId, mainStateDir } from "../../core/guards.ts";
|
|
18
17
|
import * as q from "../../core/queue/lib.ts";
|
|
@@ -448,6 +447,35 @@ function noteReadable(path: string): boolean {
|
|
|
448
447
|
}
|
|
449
448
|
}
|
|
450
449
|
|
|
450
|
+
/**
|
|
451
|
+
* Runs the CLI `doctor` command without blocking the event loop and returns its combined output.
|
|
452
|
+
* Invokes the CLI file via its `#!/usr/bin/env bun` shebang rather than `process.execPath` so a
|
|
453
|
+
* host harness process does not spawn another harness session.
|
|
454
|
+
*
|
|
455
|
+
* Returns:
|
|
456
|
+
* Promise<string>: Combined stdout, stderr, and any spawn error line from `neurastream doctor`
|
|
457
|
+
*/
|
|
458
|
+
export function runCliDoctor(): Promise<string> {
|
|
459
|
+
const cli = join(PACKAGE_ROOT, "src", "cli", "main.ts");
|
|
460
|
+
const { promise, resolve } = Promise.withResolvers<string>();
|
|
461
|
+
const child = spawn(cli, ["doctor"], { stdio: ["ignore", "pipe", "pipe"] });
|
|
462
|
+
let stdout = "";
|
|
463
|
+
let stderr = "";
|
|
464
|
+
child.stdout?.setEncoding("utf8").on("data", (chunk: string) => {
|
|
465
|
+
stdout += chunk;
|
|
466
|
+
});
|
|
467
|
+
child.stderr?.setEncoding("utf8").on("data", (chunk: string) => {
|
|
468
|
+
stderr += chunk;
|
|
469
|
+
});
|
|
470
|
+
child.on("error", err => {
|
|
471
|
+
const text = `${stdout}${stderr}`;
|
|
472
|
+
const body = text.endsWith("\n") || text === "" ? text : `${text}\n`;
|
|
473
|
+
resolve(`${body}${err.message}\n`);
|
|
474
|
+
});
|
|
475
|
+
child.on("close", () => resolve(`${stdout}${stderr}`));
|
|
476
|
+
return promise;
|
|
477
|
+
}
|
|
478
|
+
|
|
451
479
|
/** The next run's message: the handoff inline, or the pointer to a file that holds it. */
|
|
452
480
|
async function nextMessage(req: RelaunchRequest, cfg: Config, mainStart: typeof mainStartText): Promise<string | null> {
|
|
453
481
|
let note: string;
|
|
@@ -460,7 +488,7 @@ async function nextMessage(req: RelaunchRequest, cfg: Config, mainStart: typeof
|
|
|
460
488
|
let generated: string;
|
|
461
489
|
try {
|
|
462
490
|
generated = [
|
|
463
|
-
await mainStart([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg), providers: ompProviders(cfg), episodesFor: cutoff => ompEpisodes(cfg, cutoff) }),
|
|
491
|
+
await mainStart([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg), providers: ompProviders(cfg), episodesFor: cutoff => ompEpisodes(cfg, cutoff), doctor: runCliDoctor }),
|
|
464
492
|
holdsBlock(q.ownerHolds(cfg.paths)),
|
|
465
493
|
].join("\n");
|
|
466
494
|
} catch (err) {
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// Rate-limit probe loop & provider-out recording (plans 20261025_1700, 20261027_1500).
|
|
2
|
+
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { strftime } from "../../core/clock.ts";
|
|
6
|
+
import type { Config } from "../../core/config.ts";
|
|
7
|
+
import { backPost, clearLimitState, limitMetric, limitedPost, onLimited, readLimitState, timingOf, writeLimitState } from "../../core/limit-probe.ts";
|
|
8
|
+
import { appendMetric } from "../../core/metrics.ts";
|
|
9
|
+
import { postReply } from "../../core/notify.ts";
|
|
10
|
+
import { pinModel, providerOfModel, recordOut, resetEpochFromText } from "../../core/provider-state.ts";
|
|
11
|
+
import { rateLimited } from "../../core/rate-limit.ts";
|
|
12
|
+
import { adapterLog, MAIN_ENV } from "./launch.ts";
|
|
13
|
+
import { asRecord, asString, type EventReply, type ExtensionHost, type HostCtx } from "./types.ts";
|
|
14
|
+
|
|
15
|
+
// Provider out-until from live data (plan 20261025_1700 P1). Two automatic recordings, both
|
|
16
|
+
// keyed on the provider half of an agent pin's `model:` frontmatter, both best effort and
|
|
17
|
+
// logged once. The reset-time case trusts the provider's own words; the no-time case falls
|
|
18
|
+
// back to the armed rate-limit wait, so a provider without a quoted reset time still lands in
|
|
19
|
+
// the file the guards and the ledger read.
|
|
20
|
+
const resetRule = (cfg: Config): { pattern: string; zone: string } => ({ pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz });
|
|
21
|
+
|
|
22
|
+
/** Task result that quotes a reset time: record it for the sub's provider. A batch naming
|
|
23
|
+
* several providers cannot attribute the time to one of them, so it records nothing. */
|
|
24
|
+
export function recordProviderOutFromTask(e: Record<string, unknown>, content: unknown[], cfg: Config): void {
|
|
25
|
+
if (asString(e.toolName) !== "task" || e.isError === true) return;
|
|
26
|
+
const text = content.map(p => asString(asRecord(p).text)).join("\n");
|
|
27
|
+
const epoch = resetEpochFromText(text, resetRule(cfg));
|
|
28
|
+
if (epoch === null) return;
|
|
29
|
+
const tasks = Array.isArray(asRecord(e.input).tasks) ? (asRecord(e.input).tasks as unknown[]) : [];
|
|
30
|
+
const providers = new Set<string>();
|
|
31
|
+
for (const t of tasks) {
|
|
32
|
+
const provider = providerOfModel(pinModel(cfg, asString(asRecord(t).agent)));
|
|
33
|
+
if (provider) providers.add(provider);
|
|
34
|
+
}
|
|
35
|
+
if (providers.size !== 1) return;
|
|
36
|
+
const provider = [...providers][0]!;
|
|
37
|
+
recordOut(cfg, provider, epoch, "task-result");
|
|
38
|
+
adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (task result)`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Rate-limited turn end: record the reset time the error text names, else the armed wait. Returns the
|
|
42
|
+
* named reset in epoch ms (null when the text names none): the one parse of that text, which the call
|
|
43
|
+
* site passes on to the rate-limit episode (plan 20261027_1500 P2/P3). */
|
|
44
|
+
export function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs: number, cfg: Config): number | null {
|
|
45
|
+
const named = reply ? resetEpochFromText(reply.errorMessage ?? "", resetRule(cfg)) : null;
|
|
46
|
+
const provider = reply?.provider ?? providerOfModel(reply?.model ?? null);
|
|
47
|
+
if (provider) {
|
|
48
|
+
const epoch = named ?? Math.floor(untilMs / 1000);
|
|
49
|
+
recordOut(cfg, provider, epoch, named !== null ? "rate-limit-reset" : "rate-limit");
|
|
50
|
+
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"})`);
|
|
51
|
+
}
|
|
52
|
+
return named === null ? null : named * 1000;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The limit tick: one check of the open episode every 30 s (plan 20261027_1500 P3). */
|
|
56
|
+
const LIMIT_TICK_MS = 30_000;
|
|
57
|
+
|
|
58
|
+
/** The probe's command line and env. Never process.execPath: inside the harness that is the omp
|
|
59
|
+
* binary, so the child was a full Main session (2026-11-03: stray Mains). bun comes from PATH, as
|
|
60
|
+
* every bin's `#!/usr/bin/env bun` shebang does; the child env drops MAIN_ENV. */
|
|
61
|
+
export function limitProbeSpawn(env: NodeJS.ProcessEnv = process.env): { cmd: string; args: string[]; env: NodeJS.ProcessEnv } {
|
|
62
|
+
const { [MAIN_ENV]: _main, ...rest } = env;
|
|
63
|
+
return { cmd: "nice", args: ["-n", "19", "bun", join(import.meta.dir, "../../cli/limit-probe.ts")], env: rest };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** One limit probe as a niced child (cli/limit-probe.ts). It writes the episode state itself;
|
|
67
|
+
* a failed start is logged and the next tick tries again. */
|
|
68
|
+
function spawnLimitProbeChild(cfg: Config): void {
|
|
69
|
+
const p = limitProbeSpawn();
|
|
70
|
+
const child = spawn(p.cmd, p.args, { detached: true, stdio: "ignore", env: p.env });
|
|
71
|
+
child.on("error", err => adapterLog(cfg, `RATE-LIMIT probe: could not start: ${err.message}`));
|
|
72
|
+
child.unref();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface RateLimitController {
|
|
76
|
+
stopTick(): void;
|
|
77
|
+
disarmEpisode(): void;
|
|
78
|
+
onOwnerPrompt(): void;
|
|
79
|
+
rateLimitOf(reply: EventReply | null): { untilMs: number } | null;
|
|
80
|
+
onRateLimitedStop(c: HostCtx, namedResetMs: number | null, errorText: string, model: string): void;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Creates the per-adapter rate-limit episode controller managing probe ticks, resume notifications,
|
|
85
|
+
* and episode cleanup on clean turns or owner prompts.
|
|
86
|
+
*
|
|
87
|
+
* Args:
|
|
88
|
+
* pi (ExtensionHost): Active extension host used to send resume messages
|
|
89
|
+
* getCfg (() => Config): Accessor returning the adapter's current config
|
|
90
|
+
*
|
|
91
|
+
* Returns:
|
|
92
|
+
* RateLimitController: Controller methods bound to this adapter instance
|
|
93
|
+
*/
|
|
94
|
+
export function createRateLimitController(pi: ExtensionHost, getCfg: () => Config): RateLimitController {
|
|
95
|
+
// Rate-limit probe loop (plan 20261027_1500 P3). A limited turn end opens one episode in
|
|
96
|
+
// main-limit.json: a named reset is waited for; otherwise a niced probe child runs every
|
|
97
|
+
// probe_interval_s until one gets through or max_probes is spent. ONE tick (LIMIT_TICK_MS)
|
|
98
|
+
// reads the episode: it spawns a due probe, or, once the provider is back, sends Main ONE new
|
|
99
|
+
// turn. A new Main turn cancels the tick and keeps the episode (probe count kept); a turn that
|
|
100
|
+
// ends without a limit clears it.
|
|
101
|
+
let limitTickArmed = false;
|
|
102
|
+
let limitTick: NodeJS.Timeout | null = null;
|
|
103
|
+
const rateClock = (ms: number): string => strftime(ms / 1000, "%H:%M");
|
|
104
|
+
|
|
105
|
+
const stopTick = (): void => {
|
|
106
|
+
limitTickArmed = false;
|
|
107
|
+
if (limitTick !== null) {
|
|
108
|
+
clearInterval(limitTick);
|
|
109
|
+
limitTick = null;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const disarmEpisode = (): void => {
|
|
114
|
+
stopTick();
|
|
115
|
+
clearLimitState(getCfg());
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const limitTickFire = (c: HostCtx): void => {
|
|
119
|
+
if (!limitTickArmed) return;
|
|
120
|
+
const cfg = getCfg();
|
|
121
|
+
const state = readLimitState(cfg);
|
|
122
|
+
if (state === null) {
|
|
123
|
+
stopTick();
|
|
124
|
+
adapterLog(cfg, "RATE-LIMIT give up: episode state gone (max_probes spent or unreadable)");
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const now = Date.now();
|
|
128
|
+
if (state.back_at !== null) {
|
|
129
|
+
if (now < state.back_at) return;
|
|
130
|
+
stopTick();
|
|
131
|
+
clearLimitState(cfg);
|
|
132
|
+
// P4: the finished episode is recorded once and the owner hears one back post; both are
|
|
133
|
+
// times and counts only — the episode's last_error never reaches chat or ledger.
|
|
134
|
+
appendMetric(cfg, limitMetric(state, now));
|
|
135
|
+
adapterLog(cfg, `RATE-LIMIT back: provider limit over (back at ${rateClock(state.back_at)}); new turn sent`);
|
|
136
|
+
void postReply(backPost(state), cfg).then(results => {
|
|
137
|
+
for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
|
|
138
|
+
});
|
|
139
|
+
pi.sendUserMessage(`main-guard: the provider limit is over (back at ${rateClock(state.back_at)}). Continue the queue where you stopped.`);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (now < state.next_probe_at) return;
|
|
143
|
+
(c.spawnLimitProbe ?? (() => spawnLimitProbeChild(cfg)))();
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const armLimitTick = (c: HostCtx): void => {
|
|
147
|
+
stopTick();
|
|
148
|
+
limitTickArmed = true;
|
|
149
|
+
const t: unknown = c.setInterval ? c.setInterval(() => limitTickFire(c), LIMIT_TICK_MS) : setInterval(() => limitTickFire(c), LIMIT_TICK_MS);
|
|
150
|
+
if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
|
|
151
|
+
limitTick = t as NodeJS.Timeout;
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const onRateLimitedStop = (c: HostCtx, namedResetMs: number | null, errorText: string, model: string): void => {
|
|
155
|
+
const cfg = getCfg();
|
|
156
|
+
const prev = readLimitState(cfg);
|
|
157
|
+
const timing = timingOf(cfg);
|
|
158
|
+
const state = onLimited(prev, namedResetMs, errorText, Date.now(), model, timing);
|
|
159
|
+
try {
|
|
160
|
+
writeLimitState(cfg, state);
|
|
161
|
+
} catch (err) {
|
|
162
|
+
adapterLog(cfg, `RATE-LIMIT state write failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
adapterLog(cfg, `RATE-LIMIT stop: ${state.reset_named ? "named reset" : "probe"} at ${rateClock(state.next_probe_at)} (probes ${state.probes} of ${timing.max_probes})`);
|
|
166
|
+
if (prev === null) {
|
|
167
|
+
adapterLog(cfg, "notify: posted (rate-limit)");
|
|
168
|
+
void postReply(limitedPost(state, timing.probe_interval_s), cfg).then(results => {
|
|
169
|
+
for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
armLimitTick(c);
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const rateLimitOf = (reply: EventReply | null): { untilMs: number } | null => {
|
|
176
|
+
const rl = getCfg().guards.rate_limit;
|
|
177
|
+
const hit = rateLimited(reply?.stopReason ?? null, reply?.errorMessage ?? null, rl);
|
|
178
|
+
if (!hit) return null;
|
|
179
|
+
const waitMs = (hit.retryAfterMs ?? rl.probe_interval_s * 1000) + rl.slack_s * 1000;
|
|
180
|
+
return { untilMs: Date.now() + waitMs };
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
const onOwnerPrompt = (): void => {
|
|
184
|
+
if (!limitTickArmed) return;
|
|
185
|
+
stopTick();
|
|
186
|
+
adapterLog(getCfg(), "RATE-LIMIT tick cancelled: owner message (probe count kept)");
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
stopTick,
|
|
191
|
+
disarmEpisode,
|
|
192
|
+
onOwnerPrompt,
|
|
193
|
+
rateLimitOf,
|
|
194
|
+
onRateLimitedStop,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
// Session rollover state machine (src/core/rollover.ts): size/version snapshot, note requests,
|
|
2
|
+
// relaunch requests, exit-grace fallback timer, and in-process rollover.
|
|
3
|
+
|
|
4
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { dirname } from "node:path";
|
|
6
|
+
import type { Config } from "../../core/config.ts";
|
|
7
|
+
import { mainStateDir } from "../../core/guards.ts";
|
|
8
|
+
import { readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
|
|
9
|
+
import { mainStartText } from "../../core/main-start.ts";
|
|
10
|
+
import * as q from "../../core/queue/lib.ts";
|
|
11
|
+
import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, relaunchPath, rolloverState, unansweredOwnerMessages, type RolloverState } from "../../core/rollover.ts";
|
|
12
|
+
import { adapterLog, runCliDoctor } from "./launch.ts";
|
|
13
|
+
import { packageJsonPath, packageVersion } from "./package-root.ts";
|
|
14
|
+
import { ompProviders } from "./providers.ts";
|
|
15
|
+
import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
|
|
16
|
+
import { asRecord, asRolloverCtx, asString, isMain, type ExtensionHost, type RolloverCtx } from "./types.ts";
|
|
17
|
+
|
|
18
|
+
const WAIT_NOTICE_MS = 15 * 60_000;
|
|
19
|
+
|
|
20
|
+
function mtimeOf(path: string): number | null {
|
|
21
|
+
try {
|
|
22
|
+
return statSync(path).mtimeMs;
|
|
23
|
+
} catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function sizeOf(path: string): number {
|
|
29
|
+
try {
|
|
30
|
+
return statSync(path).size;
|
|
31
|
+
} catch {
|
|
32
|
+
return 0;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface RolloverSnapshot {
|
|
37
|
+
state: RolloverState;
|
|
38
|
+
noteMtimeMs: number | null;
|
|
39
|
+
stale: boolean;
|
|
40
|
+
liveVersion: string | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface RolloverController {
|
|
44
|
+
isRelaunched(): boolean;
|
|
45
|
+
snapshot(c: RolloverCtx): RolloverSnapshot;
|
|
46
|
+
noteRequestFor(c: RolloverCtx, snap: { stale: boolean; liveVersion: string | null }): string;
|
|
47
|
+
requestRelaunch(c: RolloverCtx, note: string, draft?: string): boolean;
|
|
48
|
+
onSizeCheck(kind: "tool_result" | "agent_end", e: unknown, ctx: unknown): void;
|
|
49
|
+
notice(ctx: unknown): string | null;
|
|
50
|
+
clearGrace(): void;
|
|
51
|
+
clearState(): void;
|
|
52
|
+
handleInput(event: unknown, ctx: unknown): { handled: true } | undefined;
|
|
53
|
+
registerCommand(): void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface RolloverControllerOptions {
|
|
57
|
+
/** Optional doctor output supplier for `mainStartText` during in-process rollover fallback (default: `runCliDoctor`). */
|
|
58
|
+
doctor?: () => Promise<string> | string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Creates the per-adapter session rollover controller handling session size/version checks,
|
|
63
|
+
* handoff note requests, launcher relaunch requests, and exit-grace in-process fallback.
|
|
64
|
+
*
|
|
65
|
+
* Args:
|
|
66
|
+
* pi (ExtensionHost): Active extension host
|
|
67
|
+
* getCfg (() => Config): Accessor returning the adapter's current config
|
|
68
|
+
* opts (RolloverControllerOptions): Optional seams (such as `doctor` for tests)
|
|
69
|
+
*
|
|
70
|
+
* Returns:
|
|
71
|
+
* RolloverController: Controller bound to this adapter instance
|
|
72
|
+
*/
|
|
73
|
+
export function createRolloverController(pi: ExtensionHost, getCfg: () => Config, opts: RolloverControllerOptions = {}): RolloverController {
|
|
74
|
+
const doctor = opts.doctor ?? runCliDoctor;
|
|
75
|
+
// The version this process loaded at start: the plugin code that is actually running.
|
|
76
|
+
const loadedVersion = packageVersion(packageJsonPath());
|
|
77
|
+
let crossed: { file: string; atMs: number } | null = null;
|
|
78
|
+
// The note request already sent, keyed by session file + note mtime at send time ("none" when
|
|
79
|
+
// no note exists): a note that expires while jobs run falls back to need-note with a key no
|
|
80
|
+
// request was sent for, so it gets exactly one new request and never a loop.
|
|
81
|
+
let asked: string | null = null;
|
|
82
|
+
let waitNoticeMs = 0;
|
|
83
|
+
|
|
84
|
+
const snapshot = (c: RolloverCtx): RolloverSnapshot => {
|
|
85
|
+
const cfg = getCfg();
|
|
86
|
+
const nowMs = Date.now();
|
|
87
|
+
const bytes = sizeOf(c.sessionFile);
|
|
88
|
+
const maxMb = cfg.rollover.max_session_mb;
|
|
89
|
+
const noteMtimeMs = mtimeOf(notePath(c.sessionId, mainStateDir(cfg)));
|
|
90
|
+
const liveVersion = packageVersion(packageJsonPath());
|
|
91
|
+
const stale = liveVersion === null || loadedVersion === null || liveVersion !== loadedVersion;
|
|
92
|
+
if (stale) {
|
|
93
|
+
// Note freshness is measured against the crossing: a stale session counts as crossed
|
|
94
|
+
// from the first check that saw it, whatever its size.
|
|
95
|
+
if (crossed?.file !== c.sessionFile) crossed = { file: c.sessionFile, atMs: nowMs };
|
|
96
|
+
} else if (bytes < maxMb * 1024 * 1024) crossed = null;
|
|
97
|
+
else if (crossed?.file !== c.sessionFile) crossed = { file: c.sessionFile, atMs: nowMs };
|
|
98
|
+
return {
|
|
99
|
+
state: rolloverState({
|
|
100
|
+
sessionBytes: bytes,
|
|
101
|
+
maxMb,
|
|
102
|
+
runningJobs: c.runningJobs(),
|
|
103
|
+
crossedAtMs: crossed?.atMs ?? null,
|
|
104
|
+
noteMtimeMs,
|
|
105
|
+
nowMs,
|
|
106
|
+
stale,
|
|
107
|
+
}),
|
|
108
|
+
noteMtimeMs,
|
|
109
|
+
stale,
|
|
110
|
+
liveVersion,
|
|
111
|
+
};
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
// The note request for a state. A stale install names both versions in place of the size line.
|
|
115
|
+
const noteRequestFor = (c: RolloverCtx, snap: { stale: boolean; liveVersion: string | null }): string => {
|
|
116
|
+
const cfg = getCfg();
|
|
117
|
+
const reason = snap.stale ? `neurastream on disk is ${snap.liveVersion ?? "unknown"}, this session runs ${loadedVersion ?? "unknown"}` : undefined;
|
|
118
|
+
return noteRequest(notePath(c.sessionId, mainStateDir(cfg)), reason);
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
let relaunched = false;
|
|
122
|
+
// omp 18.11.1 defers an extension shutdown: it re-checks only when shutdown() is called again or
|
|
123
|
+
// an owner submission finishes, so a refused exit once left a dead UI that swallowed every owner
|
|
124
|
+
// message (I-20261024-4). One unref'd timer per request: if omp still has not exited
|
|
125
|
+
// rollover.exit_grace_s after the request, the adapter rolls over in-process. The timer keeps its
|
|
126
|
+
// own clearer: session_shutdown cancels the fallback when omp really exits.
|
|
127
|
+
let clearGraceFn: (() => void) | null = null;
|
|
128
|
+
// One in-process rollover at a time: while it waits for idle, the size check must not start
|
|
129
|
+
// a relaunch over it.
|
|
130
|
+
let flight: string[] | null = null;
|
|
131
|
+
|
|
132
|
+
// The one in-process rollover, the exit-grace fallback: gather the generated state, wait for
|
|
133
|
+
// idle, then start a fresh session whose first message is the handoff. A state change during
|
|
134
|
+
// the wait sends the owner's text to this session as an ordinary message.
|
|
135
|
+
const rolloverInProcess = async (c: RolloverCtx, owner: string[], noticeText: string): Promise<void> => {
|
|
136
|
+
const cfg = getCfg();
|
|
137
|
+
const previous = c.sessionFile;
|
|
138
|
+
const path = notePath(c.sessionId, mainStateDir(cfg));
|
|
139
|
+
flight = owner;
|
|
140
|
+
try {
|
|
141
|
+
c.notify(noticeText);
|
|
142
|
+
const generated = [
|
|
143
|
+
await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg), providers: ompProviders(cfg), doctor }),
|
|
144
|
+
holdsBlock(q.ownerHolds(cfg.paths)),
|
|
145
|
+
].join("\n");
|
|
146
|
+
const note = readFileSync(path, "utf8");
|
|
147
|
+
adapterLog(cfg, `rollover: new session from ${previous}; note ${path}`);
|
|
148
|
+
await c.waitForIdle();
|
|
149
|
+
const again = snapshot(c).state;
|
|
150
|
+
if (relaunched || again !== "ready") {
|
|
151
|
+
c.notify(`main-rollover: the state changed while waiting for idle (${relaunched ? "relaunch requested" : again}); no new session.`);
|
|
152
|
+
// The owner's text is not lost: it goes to this session as an ordinary message.
|
|
153
|
+
const pending = owner.filter(s => s !== "").join("\n");
|
|
154
|
+
if (pending !== "") pi.sendUserMessage(pending);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const r = asRecord(await c.newSession({ parentSession: previous }));
|
|
158
|
+
if (r.cancelled === true) return;
|
|
159
|
+
// Read after the await: owner messages that arrived during newSession are part of the handoff.
|
|
160
|
+
const handoff = buildHandoff({
|
|
161
|
+
generated,
|
|
162
|
+
note,
|
|
163
|
+
previousSessionFile: previous,
|
|
164
|
+
ownerMessage: owner.filter(s => s !== "").join("\n"),
|
|
165
|
+
unanswered: unansweredOwnerMessages(readOwnerMessages(cfg.paths), readOwnerAnswers(cfg.paths)),
|
|
166
|
+
});
|
|
167
|
+
pi.sendUserMessage(handoff);
|
|
168
|
+
} finally {
|
|
169
|
+
flight = null;
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
// The grace elapsed without a session_shutdown: omp refused the exit. Read the request's draft,
|
|
174
|
+
// drop the request and roll over here, so the owner's messages reach a live session instead of a
|
|
175
|
+
// dead UI. The owner-away text stands in when nothing was typed.
|
|
176
|
+
const exitGraceElapsed = (c: RolloverCtx): void => {
|
|
177
|
+
const cfg = getCfg();
|
|
178
|
+
adapterLog(cfg, `rollover: omp did not exit within ${cfg.rollover.exit_grace_s}s; rolling over in-process`);
|
|
179
|
+
const reqFile = relaunchPath(mainStateDir(cfg));
|
|
180
|
+
let draft = "";
|
|
181
|
+
try {
|
|
182
|
+
draft = asString(asRecord(JSON.parse(readFileSync(reqFile, "utf8"))).draft);
|
|
183
|
+
} catch {}
|
|
184
|
+
rmSync(reqFile, { force: true });
|
|
185
|
+
relaunched = false;
|
|
186
|
+
rolloverInProcess(c, [draft.trim() === "" ? OWNER_AWAY : draft], "rollover: omp did not restart; continuing in a new session here").catch((err: unknown) => {
|
|
187
|
+
adapterLog(cfg, `rollover: in-process rollover failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
188
|
+
});
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
const armGraceTimer = (c: RolloverCtx): void => {
|
|
192
|
+
const cfg = getCfg();
|
|
193
|
+
clearGraceFn?.();
|
|
194
|
+
const t = setTimeout(() => {
|
|
195
|
+
clearGraceFn = null;
|
|
196
|
+
exitGraceElapsed(c);
|
|
197
|
+
}, cfg.rollover.exit_grace_s * 1000);
|
|
198
|
+
if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
|
|
199
|
+
clearGraceFn = () => {
|
|
200
|
+
clearTimeout(t);
|
|
201
|
+
clearGraceFn = null;
|
|
202
|
+
};
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
// The launcher restarts omp: the request file carries the note and the editor draft, and omp
|
|
206
|
+
// shuts down only after the file is written. A failed write keeps the session running.
|
|
207
|
+
// Returns whether the request was written.
|
|
208
|
+
const requestRelaunch = (c: RolloverCtx, note: string, draft = c.draft()): boolean => {
|
|
209
|
+
const cfg = getCfg();
|
|
210
|
+
const reqFile = relaunchPath(mainStateDir(cfg));
|
|
211
|
+
try {
|
|
212
|
+
mkdirSync(dirname(reqFile), { recursive: true });
|
|
213
|
+
writeFileSync(reqFile, `${JSON.stringify({ previousSessionFile: c.sessionFile, notePath: note, draft })}\n`);
|
|
214
|
+
} catch (err) {
|
|
215
|
+
adapterLog(cfg, `rollover: relaunch request not written: ${String(err)}`);
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
relaunched = true;
|
|
219
|
+
adapterLog(cfg, `rollover: relaunch requested from ${c.sessionFile}`);
|
|
220
|
+
c.shutdown();
|
|
221
|
+
armGraceTimer(c);
|
|
222
|
+
return true;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// An owner message typed while the relaunch is pending joins the request's draft, in order; the
|
|
226
|
+
// launcher's handoff carries it. The rewrite is atomic, so the launcher never reads a partial file.
|
|
227
|
+
const appendToRelaunch = (text: string): boolean => {
|
|
228
|
+
const cfg = getCfg();
|
|
229
|
+
const reqFile = relaunchPath(mainStateDir(cfg));
|
|
230
|
+
try {
|
|
231
|
+
const req = asRecord(JSON.parse(readFileSync(reqFile, "utf8")));
|
|
232
|
+
const draft = [asString(req.draft), text].filter(s => s !== "").join("\n");
|
|
233
|
+
const tmp = `${reqFile}.tmp`;
|
|
234
|
+
writeFileSync(tmp, `${JSON.stringify({ ...req, draft })}\n`);
|
|
235
|
+
renameSync(tmp, reqFile);
|
|
236
|
+
return true;
|
|
237
|
+
} catch (err) {
|
|
238
|
+
adapterLog(cfg, `rollover: owner message not added to the relaunch request: ${String(err)}`);
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
const onSizeCheck = (kind: "tool_result" | "agent_end", e: unknown, ctx: unknown): void => {
|
|
244
|
+
const cfg = getCfg();
|
|
245
|
+
const c = asRolloverCtx(ctx);
|
|
246
|
+
if (!cfg.rollover.enabled || !c || !isMain(ctx)) return;
|
|
247
|
+
const snap = snapshot(c);
|
|
248
|
+
const key = `${c.sessionFile}:${snap.noteMtimeMs ?? "none"}`;
|
|
249
|
+
// A terminal run end: omp 18.11.1 sets willContinue on a non-terminal agent_end.
|
|
250
|
+
const terminal = kind === "agent_end" && asRecord(e).willContinue !== true;
|
|
251
|
+
if (snap.state === "need-note" && asked !== key) {
|
|
252
|
+
asked = key;
|
|
253
|
+
pi.sendMessage(
|
|
254
|
+
{ customType: "main-guard.rollover", content: noteRequestFor(c, snap), display: false },
|
|
255
|
+
{ triggerTurn: true, deliverAs: "nextTurn" },
|
|
256
|
+
);
|
|
257
|
+
} else if (terminal && snap.state === "ready" && !relaunched && flight === null) {
|
|
258
|
+
// flight !== null: an in-process rollover (the fallback) owns this session's end.
|
|
259
|
+
requestRelaunch(c, notePath(c.sessionId, mainStateDir(cfg)));
|
|
260
|
+
} else if (terminal && relaunched) {
|
|
261
|
+
// A tool result mid-run never restarts the session (I-20261024-4), and omp's interactive
|
|
262
|
+
// mode re-runs its deferred exit check only when shutdown() is called again: re-arm at
|
|
263
|
+
// every later terminal run end instead of waiting for an owner message.
|
|
264
|
+
c.shutdown();
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
/** Wait-jobs notice for Main's next turn, throttled; null otherwise. The note request goes out at turn end. */
|
|
269
|
+
const notice = (ctx: unknown): string | null => {
|
|
270
|
+
const cfg = getCfg();
|
|
271
|
+
const c = asRolloverCtx(ctx);
|
|
272
|
+
if (!cfg.rollover.enabled || !c) return null;
|
|
273
|
+
const state = snapshot(c).state;
|
|
274
|
+
if (state === "wait-jobs" && Date.now() - waitNoticeMs >= WAIT_NOTICE_MS) {
|
|
275
|
+
waitNoticeMs = Date.now();
|
|
276
|
+
const jobs = c.runningJobs().join(", ");
|
|
277
|
+
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.`;
|
|
278
|
+
}
|
|
279
|
+
return null;
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
// The relaunch is the only rollover path: a plain interactive message in the ready state
|
|
283
|
+
// requests it, and every such message joins the pending request's draft, in order.
|
|
284
|
+
const handleInput = (event: unknown, ctx: unknown): { handled: true } | undefined => {
|
|
285
|
+
const cfg = getCfg();
|
|
286
|
+
const e = asRecord(event);
|
|
287
|
+
const c = asRolloverCtx(ctx);
|
|
288
|
+
const text = asString(e.text);
|
|
289
|
+
if (!cfg.rollover.enabled || !c || !isMain(ctx)) return undefined;
|
|
290
|
+
if (asString(e.source) !== "interactive" || text === "" || text.startsWith("/")) return undefined;
|
|
291
|
+
if (!relaunched) {
|
|
292
|
+
if (snapshot(c).state !== "ready") return undefined;
|
|
293
|
+
// The message is the request's first owner text, so the editor draft is not carried.
|
|
294
|
+
if (!requestRelaunch(c, notePath(c.sessionId, mainStateDir(cfg)), "")) return undefined;
|
|
295
|
+
}
|
|
296
|
+
if (appendToRelaunch(text)) c.notify("rollover in progress: your message goes to the new session");
|
|
297
|
+
else c.notify("rollover in progress: your message could not be saved and was not sent; send it again after the rollover");
|
|
298
|
+
// omp re-checks its deferred exit only when shutdown() is called again: re-arm per message.
|
|
299
|
+
c.shutdown();
|
|
300
|
+
return { handled: true };
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
// The rollover starts on its own (size + idle), and the owner's next message joins the
|
|
304
|
+
// pending relaunch; the command only says so.
|
|
305
|
+
const registerCommand = (): void => {
|
|
306
|
+
pi.registerCommand("main-rollover", {
|
|
307
|
+
description: "Start a fresh session from Main's handoff note; the rest of the message is the owner's first message",
|
|
308
|
+
handler: async (_args: unknown, ctx: unknown) => {
|
|
309
|
+
const c = asRolloverCtx(ctx);
|
|
310
|
+
if (!c) return;
|
|
311
|
+
c.notify("main-rollover: under neurastream main the rollover starts from your next message, not from this command.");
|
|
312
|
+
},
|
|
313
|
+
});
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
isRelaunched: () => relaunched,
|
|
318
|
+
snapshot,
|
|
319
|
+
noteRequestFor,
|
|
320
|
+
requestRelaunch,
|
|
321
|
+
onSizeCheck,
|
|
322
|
+
notice,
|
|
323
|
+
clearGrace: () => {
|
|
324
|
+
clearGraceFn?.();
|
|
325
|
+
},
|
|
326
|
+
clearState: () => {
|
|
327
|
+
clearGraceFn?.();
|
|
328
|
+
relaunched = false;
|
|
329
|
+
flight = null;
|
|
330
|
+
},
|
|
331
|
+
handleInput,
|
|
332
|
+
registerCommand,
|
|
333
|
+
};
|
|
334
|
+
}
|