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
@@ -0,0 +1,143 @@
1
+ // Shared omp extension host types and runtime-checked payload accessors.
2
+
3
+ import type { Decision } from "../../core/adapter.ts";
4
+
5
+ /** Subset of the harness extension host the adapter needs. */
6
+ export interface ExtensionHost {
7
+ on(event: string, cb: (...args: unknown[]) => unknown): void;
8
+ registerCommand(name: string, opts: { description?: string; handler: (args: unknown, ctx: unknown) => unknown }): void;
9
+ sendUserMessage(content: string | ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[]): void;
10
+ sendMessage(message: { customType: string; content: string; display: boolean }, options: { triggerTurn: boolean; deliverAs: "nextTurn" }): void;
11
+ }
12
+
13
+ /** The parts of a harness call context the handlers look at. */
14
+ export interface HostCtx {
15
+ hasAgent: boolean;
16
+ kind?: string;
17
+ id?: string;
18
+ cwd?: string;
19
+ setInterval?: (cb: () => void, ms: number) => unknown;
20
+ spawnLimitProbe?: () => void;
21
+ }
22
+
23
+ /** The last assistant message of an omp event's `messages` array, as the adapter needs it: its
24
+ * joined text-block text and the shape that tells a real hand-back from a mid-run continuation
25
+ * (plan 20261025_0130). omp sends the reply in `session_stop.last_assistant_message` (falling
26
+ * back to the last assistant entry of `messages`) and in `agent_end.messages`; reading the
27
+ * session file instead lags a whole turn because session_stop fires BEFORE agent_end. */
28
+ export interface EventReply {
29
+ text: string;
30
+ stopReason: string | null;
31
+ toolCalls: number;
32
+ /** The provider's error text on a turn that ended on one (`429 … retry-after-ms=…`); null otherwise. */
33
+ errorMessage: string | null;
34
+ /** The provider and model fields of the assistant message, when the event carries them; the provider-out recording keys on the provider. */
35
+ provider: string | null;
36
+ model: string | null;
37
+ }
38
+
39
+ export interface RolloverCtx {
40
+ sessionId: string;
41
+ sessionFile: string;
42
+ runningJobs(): string[];
43
+ waitForIdle(): unknown;
44
+ newSession(opts: { parentSession: string }): unknown;
45
+ notify(message: string): void;
46
+ draft(): string;
47
+ shutdown(): void;
48
+ }
49
+
50
+ export function asRecord(v: unknown): Record<string, unknown> {
51
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
52
+ }
53
+
54
+ export function asString(v: unknown, fallback = ""): string {
55
+ return typeof v === "string" ? v : fallback;
56
+ }
57
+
58
+ /** Call a method on a harness object by name; undefined when it is not a function. */
59
+ export function call(obj: Record<string, unknown>, key: string, args: unknown[] = []): unknown {
60
+ const fn = obj[key];
61
+ return typeof fn === "function" ? Reflect.apply(fn, obj, args) : undefined;
62
+ }
63
+
64
+ export function lastAssistantIn(messages: unknown): EventReply | null {
65
+ const arr = Array.isArray(messages) ? messages : [];
66
+ for (let i = arr.length - 1; i >= 0; i--) {
67
+ const m = asRecord(arr[i]);
68
+ if (m.role !== "assistant") continue;
69
+ const content = Array.isArray(m.content) ? m.content : [];
70
+ const text = content
71
+ .filter(c => asRecord(c).type === "text")
72
+ .map(c => asString(asRecord(c).text))
73
+ .join("\n")
74
+ .trim();
75
+ return {
76
+ text,
77
+ stopReason: typeof m.stopReason === "string" ? m.stopReason : null,
78
+ toolCalls: content.filter(c => asRecord(c).type === "toolCall").length,
79
+ errorMessage: typeof m.errorMessage === "string" ? m.errorMessage : null,
80
+ provider: typeof m.provider === "string" ? m.provider : null,
81
+ model: typeof m.model === "string" ? m.model : null,
82
+ };
83
+ }
84
+ return null;
85
+ }
86
+
87
+ export function asCtx(v: unknown): HostCtx {
88
+ const r = asRecord(v);
89
+ // The agent envelope only ever carries kind/id strings (original extensions read just those);
90
+ // cast fixes the envelope, every field below is checked before use.
91
+ const agent = r.agent as { kind?: unknown; id?: unknown } | null | undefined;
92
+ const out: HostCtx = { hasAgent: agent !== null && agent !== undefined };
93
+ if (agent) {
94
+ if (typeof agent.kind === "string") out.kind = agent.kind;
95
+ if (typeof agent.id === "string") out.id = agent.id;
96
+ }
97
+ if (typeof r.cwd === "string") out.cwd = r.cwd;
98
+ // Harness-injected timer with the original main-guard signature (ctx.setInterval).
99
+ const interval = r.setInterval as ((cb: () => void, ms: number) => unknown) | undefined;
100
+ if (typeof interval === "function") out.setInterval = interval;
101
+ // Harness-injected probe spawner (tests); the default starts the niced probe child.
102
+ const probe = r.spawnLimitProbe as (() => void) | undefined;
103
+ if (typeof probe === "function") out.spawnLimitProbe = probe;
104
+ return out;
105
+ }
106
+
107
+ export function asRolloverCtx(v: unknown): RolloverCtx | null {
108
+ const r = asRecord(v);
109
+ const sm = asRecord(r.sessionManager);
110
+ const sessionId = call(sm, "getSessionId");
111
+ const sessionFile = call(sm, "getSessionFile");
112
+ if (typeof sessionId !== "string" || typeof sessionFile !== "string") return null;
113
+ return {
114
+ sessionId,
115
+ sessionFile,
116
+ runningJobs: () => {
117
+ const running = asRecord(call(r, "getAsyncJobSnapshot")).running;
118
+ return Array.isArray(running) ? running.map(j => asString(asRecord(j).label, "job")) : [];
119
+ },
120
+ waitForIdle: () => call(r, "waitForIdle"),
121
+ newSession: opts => call(r, "newSession", [opts]),
122
+ notify: message => call(asRecord(r.ui), "notify", [message]),
123
+ draft: () => {
124
+ const text = call(asRecord(r.ui), "getEditorText");
125
+ return typeof text === "string" ? text : "";
126
+ },
127
+ shutdown: () => {
128
+ call(r, "shutdown");
129
+ },
130
+ };
131
+ }
132
+
133
+ export function isMain(ctx: unknown): boolean {
134
+ const c = asCtx(ctx);
135
+ return !c.hasAgent || c.kind === "main";
136
+ }
137
+
138
+ /** Map a core decision onto the extension return shapes. */
139
+ export function toExtensionResult(d: Decision): Record<string, unknown> {
140
+ if (!d.allow) return { block: true, reason: d.reason, decision: "block" };
141
+ if (d.inject) return { additionalContext: d.inject };
142
+ return {};
143
+ }
@@ -1,3 +1,6 @@
1
+ import { spawn } from "node:child_process";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
1
4
  import { agentLedger } from "../core/agent-ledger.ts";
2
5
  import { agentScore } from "../core/agent-score.ts";
3
6
  import { briefLint } from "../core/brief-lint.ts";
@@ -48,6 +51,34 @@ export const PORTED = [
48
51
  "heavy-run",
49
52
  ] as const;
50
53
 
54
+ const CLI_MAIN = join(dirname(fileURLToPath(import.meta.url)), "main.ts");
55
+
56
+ /**
57
+ * Runs the CLI `doctor` command asynchronously and returns its combined stdout and stderr.
58
+ *
59
+ * Returns:
60
+ * Promise<string>: Output produced by `neurastream doctor`, including any spawn error message
61
+ */
62
+ function runCliDoctor(): Promise<string> {
63
+ const { promise, resolve } = Promise.withResolvers<string>();
64
+ const child = spawn(CLI_MAIN, ["doctor"], { stdio: ["ignore", "pipe", "pipe"] });
65
+ let stdout = "";
66
+ let stderr = "";
67
+ child.stdout?.setEncoding("utf8").on("data", (chunk: string) => {
68
+ stdout += chunk;
69
+ });
70
+ child.stderr?.setEncoding("utf8").on("data", (chunk: string) => {
71
+ stderr += chunk;
72
+ });
73
+ child.on("error", err => {
74
+ const text = `${stdout}${stderr}`;
75
+ const body = text.endsWith("\n") || text === "" ? text : `${text}\n`;
76
+ resolve(`${body}${err.message}\n`);
77
+ });
78
+ child.on("close", () => resolve(`${stdout}${stderr}`));
79
+ return promise;
80
+ }
81
+
51
82
  export async function runMain(args: string[]): Promise<number> {
52
83
  const cfg = runtime().cfg;
53
84
  return getAdapter(cfg).launchMain(args, cfg);
@@ -87,10 +118,10 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
87
118
  return claimCli(args, rt.cfg);
88
119
  case "main-start": {
89
120
  const a = getAdapter(rt.cfg);
90
- return mainStart(args, rt.cfg, { source: a.runSource(rt.cfg), results: a.completedResults(rt.cfg), providers: a.providers(rt.cfg), episodesFor: cutoff => a.episodes(rt.cfg, cutoff) });
121
+ return mainStart(args, rt.cfg, { source: a.runSource(rt.cfg), results: a.completedResults(rt.cfg), providers: a.providers(rt.cfg), episodesFor: cutoff => a.episodes(rt.cfg, cutoff), doctor: runCliDoctor });
91
122
  }
92
123
  case "machine-guard":
93
- return machineGuard(args, rt.cfg);
124
+ return machineGuard(args, rt.cfg, { heavyMain: CLI_MAIN, heavyStatus: process.execPath });
94
125
  case "quota-reset":
95
126
  return quotaReset(args, rt.cfg);
96
127
  case "priority-watch":
@@ -31,7 +31,7 @@ import { watchOn, watchOff } from "./watch-setup.ts";
31
31
  import { runWip } from "./wip.ts";
32
32
  import { runUninstall } from "../core/uninstall.ts";
33
33
  import { queueMigrate } from "../core/queue-migrate.ts";
34
- import { activePlans, allowedAgents, enforceReadOnlyIndex, gitTop, readIndex, writeIndex } from "../core/queue/lib.ts";
34
+ import { activePlans, allowedAgents, enforceReadOnlyIndex, gitTop, parseIndex, updateIndex } from "../core/queue/lib.ts";
35
35
  import { defaultRunner } from "../core/mr-sweep.ts";
36
36
  import { allowAgents, denyAgents, invalidSlugs } from "../core/subagents.ts";
37
37
  import { runLabels } from "./labels.ts";
@@ -339,15 +339,27 @@ function runQueueAdd(args: string[], cfg: Config): number {
339
339
  return 1;
340
340
  }
341
341
  const index = cfg.paths.queue_index;
342
- const lines = readIndex(index);
343
- if (lines.includes(abs)) {
344
- console.error(`queue add: ${abs} is already listed at rank ${lines.indexOf(abs) + 1} (queue move reorders it)`);
342
+ let existingRank = -1;
343
+ let insertedAt = -1;
344
+ let total = 0;
345
+ const wrote = updateIndex(index, undefined, (currentText) => {
346
+ const lines = parseIndex(currentText);
347
+ const found = lines.indexOf(abs);
348
+ if (found !== -1) {
349
+ existingRank = found + 1;
350
+ return null;
351
+ }
352
+ const at = rank === null ? lines.length : Math.min(rank - 1, lines.length);
353
+ lines.splice(at, 0, abs);
354
+ insertedAt = at + 1;
355
+ total = lines.length;
356
+ return lines;
357
+ });
358
+ if (!wrote) {
359
+ console.error(`queue add: ${abs} is already listed at rank ${existingRank} (queue move reorders it)`);
345
360
  return 1;
346
361
  }
347
- const at = rank === null ? lines.length : Math.min(rank - 1, lines.length);
348
- lines.splice(at, 0, abs);
349
- writeIndex(lines, undefined, index);
350
- console.log(`queue add: ${abs} at rank ${at + 1} of ${lines.length} in ${index}`);
362
+ console.log(`queue add: ${abs} at rank ${insertedAt} of ${total} in ${index}`);
351
363
  return 0;
352
364
  }
353
365
 
@@ -361,17 +373,26 @@ function runQueueMove(args: string[], cfg: Config): number {
361
373
  }
362
374
  const abs = path.resolve(fileArg!);
363
375
  const index = cfg.paths.queue_index;
364
- const lines = readIndex(index);
365
- const from = lines.indexOf(abs);
366
- if (from === -1) {
376
+ let fromRank = -1;
377
+ let toRank = -1;
378
+ let total = 0;
379
+ const wrote = updateIndex(index, undefined, (currentText) => {
380
+ const lines = parseIndex(currentText);
381
+ const from = lines.indexOf(abs);
382
+ if (from === -1) return null;
383
+ lines.splice(from, 1);
384
+ const to = Math.min(rank - 1, lines.length);
385
+ lines.splice(to, 0, abs);
386
+ fromRank = from + 1;
387
+ toRank = to + 1;
388
+ total = lines.length;
389
+ return lines;
390
+ });
391
+ if (!wrote) {
367
392
  console.error(`queue move: ${abs} is not in ${index}`);
368
393
  return 1;
369
394
  }
370
- lines.splice(from, 1);
371
- const to = Math.min(rank - 1, lines.length);
372
- lines.splice(to, 0, abs);
373
- writeIndex(lines, undefined, index);
374
- console.log(`queue move: ${abs} rank ${from + 1} → ${to + 1} of ${lines.length} in ${index}`);
395
+ console.log(`queue move: ${abs} rank ${fromRank} → ${toRank} of ${total} in ${index}`);
375
396
  return 0;
376
397
  }
377
398
 
package/src/cli/recall.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // `neurastream recall`: searches the owner's messages and Main's answers (the recall log, see
2
2
  // core/owner-log.ts) and shows an entry with the entry it pairs with. Read-only.
3
3
 
4
- import { getAdapter, ompComplete } from "../adapters/index.ts";
4
+ import { getAdapter } from "../adapters/index.ts";
5
5
  import { nowSec } from "../core/clock.ts";
6
6
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
7
7
  import { helpDoc, printText } from "../core/help.ts";
@@ -116,7 +116,8 @@ async function topicsCli(args: string[], cfg: Config): Promise<number> {
116
116
  return 2;
117
117
  }
118
118
  try {
119
- const run: TopicsRun = await runTopics(cfg, ompComplete, { close: args.includes("--close") });
119
+ const adapter = getAdapter(cfg);
120
+ const run: TopicsRun = await runTopics(cfg, req => adapter.complete(req), { close: args.includes("--close") });
120
121
  for (const line of run.lines) console.log(line);
121
122
  return run.failures === 0 ? 0 : 1;
122
123
  } catch {
@@ -1,4 +1,4 @@
1
- // The owner page's Results build, run as its own process by spawnResultsBuild (src/core/owner-ui.ts):
1
+ // The owner page's Results build, run as its own process by spawnResultsBuild (src/cli/workspace.ts):
2
2
  // it parses months of sessions (over a minute, GBs of memory), which froze the page when the server
3
3
  // did it itself (I-20261030-121). Writes the numbers to resultsCachePath(); the page only reads them.
4
4
 
@@ -14,7 +14,7 @@ import { homedir } from "node:os";
14
14
  import { getAdapter } from "../adapters/index.ts";
15
15
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
16
16
  import { beat, errorLine } from "../core/heartbeat.ts";
17
- import { startOwnerUi, type OwnerUiOptions, type OwnerUiServer } from "../core/owner-ui.ts";
17
+ import { startOwnerUi, type OwnerUiOptions, type OwnerUiServer, type ResultsBuild } from "../core/owner-ui.ts";
18
18
  import { realTailscale, type Tailscale, untilIp4Changes } from "../core/tailscale.ts";
19
19
  import { TEAM_NAME_HINT, TEAM_NAME_RE } from "../core/team-labels.ts";
20
20
  import { addTeamMember, listTeamMembers, removeTeamMember, startTeamServer, type TeamServer, type TeamServerConfig, type TeamServerOptions } from "../core/team-server.ts";
@@ -92,6 +92,17 @@ function runWorkspaceSetup(args: string[], deps: WorkspaceDeps): number {
92
92
  return uiOn({ ...setup, login, admin, repos, port, terminal });
93
93
  }
94
94
 
95
+ /**
96
+ * Spawns the standalone Results cache builder process at low CPU priority and notifies `done` on exit.
97
+ *
98
+ * Args:
99
+ * done (() => void): Callback invoked when the child build process finishes or fails
100
+ */
101
+ export const spawnResultsBuild: ResultsBuild = done => {
102
+ const proc = Bun.spawn(["nice", "-n", "19", process.execPath, `${import.meta.dir}/results-build.ts`], { stdout: "ignore", stderr: "inherit" });
103
+ void proc.exited.then(done, done);
104
+ };
105
+
95
106
  export async function runWorkspace(args: string[] = [], deps: WorkspaceDeps = {}): Promise<number> {
96
107
  if (args[0] === "on" || args[0] === "off") return runWorkspaceSetup(args, deps);
97
108
  if (args[0] === "members") return runMembers(args.slice(1), deps);
@@ -120,7 +131,7 @@ export async function runWorkspace(args: string[] = [], deps: WorkspaceDeps = {}
120
131
  const tailscale = deps.tailscale ?? realTailscale;
121
132
  let server: OwnerUiServer;
122
133
  try {
123
- server = (deps.start ?? startOwnerUi)({ cfg, tailscale, source: getAdapter(cfg).runSource(cfg) });
134
+ server = (deps.start ?? startOwnerUi)({ cfg, tailscale, source: getAdapter(cfg).runSource(cfg), resultsBuild: spawnResultsBuild });
124
135
  } catch (e) {
125
136
  beat(cfg, "workspace", { ok: false, detail: errorLine(e) });
126
137
  throw e;
@@ -185,6 +185,22 @@ export interface TaskResult {
185
185
  ts: number;
186
186
  }
187
187
 
188
+ /** One completion request sent through the active harness adapter's completion gateway. */
189
+ export interface CompleteRequest {
190
+ model: string;
191
+ system: string;
192
+ prompt: string;
193
+ maxTokens: number;
194
+ /** Reasoning effort for the model ("" or absent = none). */
195
+ effort?: string;
196
+ }
197
+
198
+ /** Plain-text result and token usage returned by a harness adapter's completion call. */
199
+ export interface CompleteResult {
200
+ text: string;
201
+ usage: { prompt_tokens: number; completion_tokens: number };
202
+ }
203
+
188
204
  /** Options for launching the harness binary; tests inject another path and a failing generator. */
189
205
  export interface LaunchOptions {
190
206
  harness?: string;