neurastream 0.3.26 → 0.3.27
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/agy/adapter.ts +649 -0
- package/src/adapters/claude/adapter.ts +545 -0
- package/src/adapters/codex/adapter.ts +588 -0
- package/src/adapters/hook-bridge.ts +429 -0
- package/src/adapters/index.ts +23 -0
- package/src/adapters/omp/adapter.ts +8 -0
- package/src/adapters/omp/index.ts +19 -7
- package/src/adapters/omp/launch.ts +5 -1
- package/src/adapters/omp/limit-wake.ts +4 -18
- package/src/adapters/omp/sessions.ts +6 -2
- package/src/adapters/omp/types.ts +19 -2
- package/src/adapters/shared.ts +1039 -0
- package/src/cli/commands.ts +109 -6
- package/src/cli/config-set.ts +26 -4
- package/src/cli/dispatch.ts +80 -7
- package/src/cli/recall.ts +5 -2
- package/src/cli/spawn.ts +616 -0
- package/src/core/adapter.ts +53 -0
- package/src/core/config-edit.ts +9 -1
- package/src/core/config.ts +79 -0
- package/src/core/guards/spawn.ts +46 -9
- package/src/core/guards/state.ts +23 -0
- package/src/core/guards/stop.ts +4 -4
- package/src/core/provider-state.ts +406 -19
- package/src/core/runner.ts +223 -0
- package/src/runners/herdr/index.ts +293 -0
- package/src/runners/index.ts +36 -0
- package/templates/AGENTS.md +1 -0
- package/templates/config.yml +10 -1
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
// Shared helpers for per-harness hook bridges and hook-config installers under src/adapters/.
|
|
2
|
+
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import { MultiRunSource, type RunSource } from "../core/adapter.ts";
|
|
6
|
+
import { renderBlock } from "../core/agents-md.ts";
|
|
7
|
+
import { nowSec } from "../core/clock.ts";
|
|
8
|
+
import type { Config } from "../core/config.ts";
|
|
9
|
+
import { checkInject } from "../core/guards.ts";
|
|
10
|
+
import { providersLine, reachableAgentsLine } from "../core/provider-state.ts";
|
|
11
|
+
import { burdenRule, repoRules } from "../core/repo-rules.ts";
|
|
12
|
+
import { allAdapters, type HarnessAdapter } from "./index.ts";
|
|
13
|
+
|
|
14
|
+
/** Legacy pre-tool command replaced by `neurastream adapter hook <name> pre-tool`. */
|
|
15
|
+
export const LEGACY_PRE_TOOL_CMD = "neurastream guard pre-tool --json";
|
|
16
|
+
|
|
17
|
+
/** Legacy stop command replaced by `neurastream adapter hook <name> stop`. */
|
|
18
|
+
export const LEGACY_STOP_CMD = "neurastream guard stop --json";
|
|
19
|
+
|
|
20
|
+
interface HookLeaf {
|
|
21
|
+
type?: string;
|
|
22
|
+
command?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface HookRule {
|
|
26
|
+
matcher?: string;
|
|
27
|
+
command?: string;
|
|
28
|
+
hooks?: HookLeaf[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function asObj(v: unknown): Record<string, unknown> | null {
|
|
32
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Returns true when running inside a guarded neurastream session (`NEURASTREAM_ROLE=sub` or `NEURASTREAM_MAIN_LAUNCHER=1`).
|
|
37
|
+
*
|
|
38
|
+
* Args:
|
|
39
|
+
* env (NodeJS.ProcessEnv): Environment variables to inspect
|
|
40
|
+
*
|
|
41
|
+
* Returns:
|
|
42
|
+
* boolean: Whether neurastream hooks are active for this process
|
|
43
|
+
*/
|
|
44
|
+
export function isHookActive(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
45
|
+
return env.NEURASTREAM_ROLE === "sub" || env.NEURASTREAM_MAIN_LAUNCHER === "1";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Parses a JSON object from hook stdin text, returning an empty object on empty or invalid input.
|
|
50
|
+
*
|
|
51
|
+
* Args:
|
|
52
|
+
* stdinText (string): Raw JSON text read from stdin
|
|
53
|
+
*
|
|
54
|
+
* Returns:
|
|
55
|
+
* Record<string, unknown>: Parsed object payload or `{}`
|
|
56
|
+
*/
|
|
57
|
+
export function parseHookPayload(stdinText: string): Record<string, unknown> {
|
|
58
|
+
if (!stdinText.trim()) return {};
|
|
59
|
+
try {
|
|
60
|
+
return asObj(JSON.parse(stdinText)) ?? {};
|
|
61
|
+
} catch {
|
|
62
|
+
return {};
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Determines the guard agent role (`"sub"` or `"main"`) from environment variables.
|
|
68
|
+
*
|
|
69
|
+
* Args:
|
|
70
|
+
* env (NodeJS.ProcessEnv): Environment variables to inspect
|
|
71
|
+
*
|
|
72
|
+
* Returns:
|
|
73
|
+
* "main" | "sub": Active guard role
|
|
74
|
+
*/
|
|
75
|
+
export function hookAgent(env: NodeJS.ProcessEnv = process.env): "main" | "sub" {
|
|
76
|
+
return env.NEURASTREAM_ROLE === "sub" ? "sub" : "main";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Resolves the agent identifier from `NEURASTREAM_AGENT_ID`, falling back to session/conversation id or default.
|
|
81
|
+
*
|
|
82
|
+
* Args:
|
|
83
|
+
* env (NodeJS.ProcessEnv): Environment variables to inspect
|
|
84
|
+
* fallback (string | undefined): Harness-provided session or conversation identifier
|
|
85
|
+
* defaultId (string): Default identifier when neither env nor fallback is set
|
|
86
|
+
*
|
|
87
|
+
* Returns:
|
|
88
|
+
* string: Resolved agent identifier
|
|
89
|
+
*/
|
|
90
|
+
export function hookAgentId(env: NodeJS.ProcessEnv, fallback?: string, defaultId = "main"): string {
|
|
91
|
+
return env.NEURASTREAM_AGENT_ID || (fallback && fallback.trim() ? fallback : defaultId);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Resolves non-empty string path arguments relative to `cwd` into deduplicated absolute paths.
|
|
96
|
+
*
|
|
97
|
+
* Args:
|
|
98
|
+
* values (unknown[]): Candidate path values extracted from tool input
|
|
99
|
+
* cwd (string): Working directory used to resolve relative paths
|
|
100
|
+
*
|
|
101
|
+
* Returns:
|
|
102
|
+
* string[]: Deduplicated resolved paths
|
|
103
|
+
*/
|
|
104
|
+
export function resolveHookPaths(values: unknown[], cwd: string): string[] {
|
|
105
|
+
const out: string[] = [];
|
|
106
|
+
for (const v of values) {
|
|
107
|
+
if (typeof v !== "string") continue;
|
|
108
|
+
const trimmed = v.trim();
|
|
109
|
+
if (!trimmed) continue;
|
|
110
|
+
const abs = resolve(cwd, trimmed);
|
|
111
|
+
if (!out.includes(abs)) out.push(abs);
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Maps a harness-native tool name onto neurastream's canonical guard tool name unless already configured directly.
|
|
118
|
+
*
|
|
119
|
+
* Args:
|
|
120
|
+
* rawTool (string): Native tool name emitted by the harness
|
|
121
|
+
* cfg (Config): Loaded neurastream configuration
|
|
122
|
+
* map (Record<string, string>): Harness-specific alias map to canonical tool names
|
|
123
|
+
*
|
|
124
|
+
* Returns:
|
|
125
|
+
* string: Canonical or configured tool name for `checkTool`
|
|
126
|
+
*/
|
|
127
|
+
export function canonicalHookTool(rawTool: string, cfg: Config, map: Record<string, string>): string {
|
|
128
|
+
if (
|
|
129
|
+
cfg.guards.read_tools.includes(rawTool) ||
|
|
130
|
+
cfg.guards.write_tools.includes(rawTool) ||
|
|
131
|
+
cfg.guards.shell_tools.includes(rawTool) ||
|
|
132
|
+
cfg.guards.skip_tools.includes(rawTool)
|
|
133
|
+
) {
|
|
134
|
+
return rawTool;
|
|
135
|
+
}
|
|
136
|
+
return map[rawTool] ?? rawTool;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Extracts file paths referenced in unified `apply_patch` payloads (`*** Update/Add/Delete File: <path>`).
|
|
141
|
+
*
|
|
142
|
+
* Args:
|
|
143
|
+
* input (Record<string, unknown>): Tool input arguments object
|
|
144
|
+
*
|
|
145
|
+
* Returns:
|
|
146
|
+
* string[]: Raw file path strings extracted from patch text
|
|
147
|
+
*/
|
|
148
|
+
export function extractPatchPaths(input: Record<string, unknown>): string[] {
|
|
149
|
+
const text = typeof input.patch === "string" ? input.patch : typeof input.input === "string" ? input.input : "";
|
|
150
|
+
if (!text) return [];
|
|
151
|
+
const out: string[] = [];
|
|
152
|
+
for (const m of text.matchAll(/^\*{3}\s+(?:Update|Add|Delete)\s+File:\s+(.+)$/gm)) {
|
|
153
|
+
const target = m[1]?.trim();
|
|
154
|
+
if (target) out.push(target);
|
|
155
|
+
}
|
|
156
|
+
return out;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Checks whether `entries` already wires `command` in either flat `{ command }` or grouped `{ hooks: [...] }` form.
|
|
161
|
+
*
|
|
162
|
+
* Args:
|
|
163
|
+
* entries (unknown[]): Array of hook entries from a harness config file
|
|
164
|
+
* command (string): Exact hook command string to look for
|
|
165
|
+
*
|
|
166
|
+
* Returns:
|
|
167
|
+
* boolean: True if `command` is wired in `entries`
|
|
168
|
+
*/
|
|
169
|
+
export function hasHookCommand(entries: unknown[], command: string): boolean {
|
|
170
|
+
for (const item of entries) {
|
|
171
|
+
const rule = asObj(item) as HookRule | null;
|
|
172
|
+
if (!rule) continue;
|
|
173
|
+
if (rule.command === command) return true;
|
|
174
|
+
if (Array.isArray(rule.hooks) && rule.hooks.some((h) => asObj(h)?.command === command)) {
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Idempotently ensures `newCmd` is wired in `entries` while upgrading or removing any `legacyCmds`
|
|
183
|
+
* and preserving all unrelated user/plugin hook entries.
|
|
184
|
+
*
|
|
185
|
+
* Args:
|
|
186
|
+
* entries (unknown[]): Existing hook entries array
|
|
187
|
+
* opts ({ legacyCmds: string[]; newCmd: string; grouped: boolean; matcher?: string }): Upgrade and format options
|
|
188
|
+
*
|
|
189
|
+
* Returns:
|
|
190
|
+
* { next: unknown[]; changed: boolean }: Updated entries array and whether a change occurred
|
|
191
|
+
*/
|
|
192
|
+
export function upgradeHookEntries(
|
|
193
|
+
entries: unknown[],
|
|
194
|
+
opts: { legacyCmds: string[]; newCmd: string; grouped: boolean; matcher?: string },
|
|
195
|
+
): { next: unknown[]; changed: boolean } {
|
|
196
|
+
const hasNew = hasHookCommand(entries, opts.newCmd);
|
|
197
|
+
let placedNew = hasNew;
|
|
198
|
+
let changed = false;
|
|
199
|
+
const next: unknown[] = [];
|
|
200
|
+
|
|
201
|
+
const makeEntry = (): Record<string, unknown> =>
|
|
202
|
+
opts.grouped
|
|
203
|
+
? { ...(opts.matcher ? { matcher: opts.matcher } : {}), hooks: [{ type: "command", command: opts.newCmd }] }
|
|
204
|
+
: { type: "command", command: opts.newCmd };
|
|
205
|
+
|
|
206
|
+
for (const item of entries) {
|
|
207
|
+
const rule = asObj(item) as HookRule | null;
|
|
208
|
+
if (rule && typeof rule.command === "string" && opts.legacyCmds.includes(rule.command)) {
|
|
209
|
+
changed = true;
|
|
210
|
+
if (!placedNew) {
|
|
211
|
+
placedNew = true;
|
|
212
|
+
next.push(opts.grouped ? makeEntry() : { ...rule, command: opts.newCmd });
|
|
213
|
+
}
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (rule && Array.isArray(rule.hooks)) {
|
|
217
|
+
let ruleChanged = false;
|
|
218
|
+
const nextLeaves: unknown[] = [];
|
|
219
|
+
for (const leaf of rule.hooks) {
|
|
220
|
+
const leafObj = asObj(leaf) as HookLeaf | null;
|
|
221
|
+
if (leafObj && typeof leafObj.command === "string" && opts.legacyCmds.includes(leafObj.command)) {
|
|
222
|
+
changed = true;
|
|
223
|
+
ruleChanged = true;
|
|
224
|
+
if (!placedNew && opts.grouped) {
|
|
225
|
+
placedNew = true;
|
|
226
|
+
nextLeaves.push({ ...leafObj, command: opts.newCmd });
|
|
227
|
+
}
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
nextLeaves.push(leaf);
|
|
231
|
+
}
|
|
232
|
+
if (ruleChanged) {
|
|
233
|
+
if (nextLeaves.length > 0 || rule.hooks.length === 0) {
|
|
234
|
+
next.push({ ...rule, hooks: nextLeaves });
|
|
235
|
+
}
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
next.push(item);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (!placedNew) {
|
|
243
|
+
changed = true;
|
|
244
|
+
next.push(makeEntry());
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
return { next, changed };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const CONTINUITY_WINDOW_SEC = 6 * 3600;
|
|
251
|
+
const MAX_LIVE_PANES = 10;
|
|
252
|
+
const MAX_RECENT_RUNS = 10;
|
|
253
|
+
const MAX_RECENT_TURNS = 4;
|
|
254
|
+
const MAX_TURN_CHARS = 240;
|
|
255
|
+
|
|
256
|
+
/** Normalized live pane summary extracted from `herdr agent list`. */
|
|
257
|
+
export interface LivePaneInfo {
|
|
258
|
+
name: string;
|
|
259
|
+
kind: string;
|
|
260
|
+
state: string;
|
|
261
|
+
paneId: string;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Injectable seams for `buildContinuitySnapshot` and `buildSessionStartContext`. */
|
|
265
|
+
export interface ContinuitySnapshotOptions {
|
|
266
|
+
nowSec?: number;
|
|
267
|
+
listLivePanes?: (env: NodeJS.ProcessEnv) => LivePaneInfo[];
|
|
268
|
+
adapters?: readonly Pick<HarnessAdapter, "runSource" | "ownerTurns">[];
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function nonEmptyStr(v: unknown): string | undefined {
|
|
272
|
+
return typeof v === "string" && v.trim() !== "" ? v.trim() : undefined;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function defaultListLivePanes(env: NodeJS.ProcessEnv): LivePaneInfo[] {
|
|
276
|
+
try {
|
|
277
|
+
const res = spawnSync("herdr", ["agent", "list"], { timeout: 1500, encoding: "utf8", env });
|
|
278
|
+
if (res.error || res.status !== 0 || typeof res.stdout !== "string" || !res.stdout.trim()) return [];
|
|
279
|
+
const parsed = asObj(JSON.parse(res.stdout));
|
|
280
|
+
const result = asObj(parsed?.result);
|
|
281
|
+
const agentsRaw = Array.isArray(result?.agents) ? result.agents : Array.isArray(parsed?.agents) ? parsed.agents : [];
|
|
282
|
+
const out: LivePaneInfo[] = [];
|
|
283
|
+
for (const item of agentsRaw) {
|
|
284
|
+
const row = asObj(item);
|
|
285
|
+
if (!row) continue;
|
|
286
|
+
const paneId = nonEmptyStr(row.pane_id) ?? nonEmptyStr(row.paneId) ?? "?";
|
|
287
|
+
const name = nonEmptyStr(row.name) ?? paneId;
|
|
288
|
+
const kind = nonEmptyStr(row.agent) ?? nonEmptyStr(row.display_agent) ?? nonEmptyStr(row.kind) ?? "unknown";
|
|
289
|
+
const state = nonEmptyStr(row.agent_status) ?? nonEmptyStr(row.status) ?? nonEmptyStr(row.state) ?? "unknown";
|
|
290
|
+
out.push({ name, kind, state, paneId });
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
} catch {
|
|
294
|
+
return [];
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function clipText(text: string, maxChars: number): string {
|
|
299
|
+
return text.length > maxChars ? `${text.slice(0, maxChars - 1)}…` : text;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Builds a tightly capped cross-harness continuity snapshot for a starting Main session:
|
|
304
|
+
* live provider availability (`providersLine`) and role-grouped reachable agents (`reachableAgentsLine`)
|
|
305
|
+
* when available, live `herdr` panes (when `HERDR_ENV=1`), up to 10 recent subagent runs (last 6h
|
|
306
|
+
* across all adapters), and up to 4 recent owner/Main turns (last 6h, max 240 chars each).
|
|
307
|
+
* Returns `""` when all sections are empty.
|
|
308
|
+
*
|
|
309
|
+
* Args:
|
|
310
|
+
* cfg (Config): Loaded neurastream configuration
|
|
311
|
+
* env (NodeJS.ProcessEnv): Process environment variables
|
|
312
|
+
* opts (ContinuitySnapshotOptions): Optional clock, live-pane, and adapter overrides
|
|
313
|
+
*
|
|
314
|
+
* Returns:
|
|
315
|
+
* string: Compact continuity snapshot text, or `""` when idle
|
|
316
|
+
*/
|
|
317
|
+
export function buildContinuitySnapshot(
|
|
318
|
+
cfg: Config,
|
|
319
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
320
|
+
opts: ContinuitySnapshotOptions = {},
|
|
321
|
+
): string {
|
|
322
|
+
const now = opts.nowSec ?? nowSec();
|
|
323
|
+
const since = now - CONTINUITY_WINDOW_SEC;
|
|
324
|
+
const adapters = opts.adapters ?? allAdapters();
|
|
325
|
+
|
|
326
|
+
let panes: LivePaneInfo[] = [];
|
|
327
|
+
if (env.HERDR_ENV === "1") {
|
|
328
|
+
try {
|
|
329
|
+
panes = (opts.listLivePanes ?? defaultListLivePanes)(env).slice(0, MAX_LIVE_PANES);
|
|
330
|
+
} catch {
|
|
331
|
+
panes = [];
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const safeSources: RunSource[] = adapters.map((adapter) => ({
|
|
336
|
+
listRuns(s) {
|
|
337
|
+
try {
|
|
338
|
+
return adapter.runSource(cfg).listRuns(s);
|
|
339
|
+
} catch {
|
|
340
|
+
return [];
|
|
341
|
+
}
|
|
342
|
+
},
|
|
343
|
+
mainSession() {
|
|
344
|
+
return null;
|
|
345
|
+
},
|
|
346
|
+
}));
|
|
347
|
+
const runs = new MultiRunSource(safeSources)
|
|
348
|
+
.listRuns(since)
|
|
349
|
+
.filter((r) => r.kind === "sub")
|
|
350
|
+
.slice(0, MAX_RECENT_RUNS);
|
|
351
|
+
|
|
352
|
+
const turns = adapters
|
|
353
|
+
.flatMap((adapter) => {
|
|
354
|
+
try {
|
|
355
|
+
return adapter.ownerTurns(cfg, since);
|
|
356
|
+
} catch {
|
|
357
|
+
return [];
|
|
358
|
+
}
|
|
359
|
+
})
|
|
360
|
+
.map((t) => ({ ...t, text: t.text.replace(/\s+/g, " ").trim() }))
|
|
361
|
+
.filter((t) => t.at >= since && t.text.length > 0)
|
|
362
|
+
.sort((a, b) => a.at - b.at)
|
|
363
|
+
.slice(-MAX_RECENT_TURNS);
|
|
364
|
+
|
|
365
|
+
const providers = providersLine(cfg, now);
|
|
366
|
+
const reachable = reachableAgentsLine(cfg, now);
|
|
367
|
+
|
|
368
|
+
if (panes.length === 0 && runs.length === 0 && turns.length === 0 && providers === null && reachable === null) return "";
|
|
369
|
+
|
|
370
|
+
const sections: string[] = ["## Cross-Harness Continuity Snapshot"];
|
|
371
|
+
if (providers) sections.push(providers);
|
|
372
|
+
if (reachable) sections.push(reachable);
|
|
373
|
+
if (panes.length > 0) {
|
|
374
|
+
sections.push(`Live panes:\n${panes.map((p) => `- ${p.name} (${p.kind}, ${p.state}, pane ${p.paneId})`).join("\n")}`);
|
|
375
|
+
}
|
|
376
|
+
if (runs.length > 0) {
|
|
377
|
+
sections.push(`Recent subagents (6h):\n${runs.map((r) => `- ${r.id} [${r.status}] ${r.model} (${r.calls} calls)`).join("\n")}`);
|
|
378
|
+
}
|
|
379
|
+
if (turns.length > 0) {
|
|
380
|
+
sections.push(`Recent turns (6h):\n${turns.map((t) => `- [${t.role}] ${clipText(t.text, MAX_TURN_CHARS)}`).join("\n")}`);
|
|
381
|
+
}
|
|
382
|
+
return sections.join("\n");
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Builds the `SessionStart` context injected into native harnesses (`agy`, `claude`, `codex`):
|
|
387
|
+
* - `NEURASTREAM_ROLE=sub` with `NEURASTREAM_PLAN`: repo rules for the plan plus the owner's burden rule (best-effort).
|
|
388
|
+
* - `NEURASTREAM_MAIN_LAUNCHER=1`: Main's managed rules (`renderBlock`), initial queue summary (`checkInject`),
|
|
389
|
+
* and non-empty cross-harness continuity snapshot (`buildContinuitySnapshot`).
|
|
390
|
+
* - Inactive plain sessions: `""`.
|
|
391
|
+
*
|
|
392
|
+
* Args:
|
|
393
|
+
* cfg (Config): Loaded neurastream configuration
|
|
394
|
+
* env (NodeJS.ProcessEnv): Process environment variables
|
|
395
|
+
* opts (ContinuitySnapshotOptions): Optional snapshot overrides for testing
|
|
396
|
+
*
|
|
397
|
+
* Returns:
|
|
398
|
+
* string: Context text to inject, or `""` when inactive or unavailable
|
|
399
|
+
*/
|
|
400
|
+
export function buildSessionStartContext(
|
|
401
|
+
cfg: Config,
|
|
402
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
403
|
+
opts?: ContinuitySnapshotOptions,
|
|
404
|
+
): string {
|
|
405
|
+
if (env.NEURASTREAM_ROLE === "sub") {
|
|
406
|
+
const plan = env.NEURASTREAM_PLAN?.trim();
|
|
407
|
+
if (!plan) return "";
|
|
408
|
+
try {
|
|
409
|
+
const parts: string[] = [];
|
|
410
|
+
const rules = repoRules(cfg, plan);
|
|
411
|
+
if (rules) parts.push(`Repo rules (${rules.path}):\n${rules.text}`);
|
|
412
|
+
const rule = burdenRule();
|
|
413
|
+
if (rule) parts.push(rule);
|
|
414
|
+
return parts.join("\n\n");
|
|
415
|
+
} catch {
|
|
416
|
+
return "";
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
if (env.NEURASTREAM_MAIN_LAUNCHER === "1") {
|
|
420
|
+
return [
|
|
421
|
+
renderBlock(cfg),
|
|
422
|
+
checkInject({ inject: "", agent: "main" }, cfg).inject,
|
|
423
|
+
buildContinuitySnapshot(cfg, env, opts),
|
|
424
|
+
]
|
|
425
|
+
.filter(Boolean)
|
|
426
|
+
.join("\n\n");
|
|
427
|
+
}
|
|
428
|
+
return "";
|
|
429
|
+
}
|
package/src/adapters/index.ts
CHANGED
|
@@ -5,10 +5,14 @@
|
|
|
5
5
|
|
|
6
6
|
import type { CompleteRequest, CompleteResult, DumpRef, LaunchOptions, OwnerTurn, RelatedTrace, RunSource, TaskResult, TraceRun, TraceSource } from "../core/adapter.ts";
|
|
7
7
|
import type { Config } from "../core/config.ts";
|
|
8
|
+
import type { SpawnProfile } from "../core/runner.ts";
|
|
8
9
|
import type { ProviderStatus } from "../core/provider-state.ts";
|
|
9
10
|
import type { Episode } from "../core/episodes.ts";
|
|
10
11
|
import type { DumpParts, DumpTokens } from "../core/trace-bloat.ts";
|
|
11
12
|
import type { SpawnBrief } from "../core/trace-briefs.ts";
|
|
13
|
+
import { agyAdapter } from "./agy/adapter.ts";
|
|
14
|
+
import { claudeAdapter } from "./claude/adapter.ts";
|
|
15
|
+
import { codexAdapter } from "./codex/adapter.ts";
|
|
12
16
|
import { ompAdapter } from "./omp/adapter.ts";
|
|
13
17
|
|
|
14
18
|
export interface HarnessAdapter {
|
|
@@ -51,10 +55,19 @@ export interface HarnessAdapter {
|
|
|
51
55
|
providers(cfg: Config): ProviderStatus[] | null;
|
|
52
56
|
/** One stateless text completion through the harness's configured gateway. */
|
|
53
57
|
complete(req: CompleteRequest): Promise<CompleteResult>;
|
|
58
|
+
/** Optional subagent launch specification when spawning through an external runner. */
|
|
59
|
+
subagentLaunchSpec?(profile: SpawnProfile): { kind: string; args: string[]; env?: Record<string, string> };
|
|
60
|
+
/** Optional workspace/CWD preparation before launching a subagent in `cwd` (e.g. folder trust). */
|
|
61
|
+
prepareSubagentCwd?(cwd: string, cfg: Config): void;
|
|
62
|
+
/** Optional native harness hook translator (`neurastream adapter hook <name> <event>`). */
|
|
63
|
+
handleHook?(event: string, stdinText: string, cfg: Config | undefined, env?: NodeJS.ProcessEnv): { code: number; stdout: string };
|
|
54
64
|
}
|
|
55
65
|
|
|
56
66
|
const ADAPTERS: Record<string, HarnessAdapter> = {
|
|
57
67
|
[ompAdapter.name]: ompAdapter,
|
|
68
|
+
[agyAdapter.name]: agyAdapter,
|
|
69
|
+
[claudeAdapter.name]: claudeAdapter,
|
|
70
|
+
[codexAdapter.name]: codexAdapter,
|
|
58
71
|
};
|
|
59
72
|
|
|
60
73
|
/** The adapter the config names (`harness:`; without a config, the shipped default). An unknown
|
|
@@ -70,3 +83,13 @@ export function getAdapter(cfg?: Pick<Config, "harness">): HarnessAdapter {
|
|
|
70
83
|
export function harnessBins(): Pick<HarnessAdapter, "name" | "bin">[] {
|
|
71
84
|
return Object.values(ADAPTERS);
|
|
72
85
|
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Returns every registered harness adapter instance.
|
|
89
|
+
*
|
|
90
|
+
* Returns:
|
|
91
|
+
* HarnessAdapter[]: All registered harness adapters
|
|
92
|
+
*/
|
|
93
|
+
export function allAdapters(): HarnessAdapter[] {
|
|
94
|
+
return Object.values(ADAPTERS);
|
|
95
|
+
}
|
|
@@ -31,4 +31,12 @@ export const ompAdapter: HarnessAdapter = {
|
|
|
31
31
|
doctor: runDoctor,
|
|
32
32
|
providers: ompProviders,
|
|
33
33
|
complete: ompComplete,
|
|
34
|
+
subagentLaunchSpec(profile) {
|
|
35
|
+
const args = profile.model ? ["--model", profile.model, ...profile.args] : [...profile.args];
|
|
36
|
+
return {
|
|
37
|
+
kind: "omp",
|
|
38
|
+
args,
|
|
39
|
+
...(Object.keys(profile.env).length > 0 ? { env: { ...profile.env } } : {}),
|
|
40
|
+
};
|
|
41
|
+
},
|
|
34
42
|
};
|
|
@@ -37,6 +37,7 @@ import { readPressure } from "../../core/pressure.ts";
|
|
|
37
37
|
import * as q from "../../core/queue/lib.ts";
|
|
38
38
|
import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
|
|
39
39
|
import { notePath, ownerText, spawnRefusal } from "../../core/rollover.ts";
|
|
40
|
+
import { resolveSpawnProfile } from "../../core/runner.ts";
|
|
40
41
|
import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
|
|
41
42
|
import { realTailscale } from "../../core/tailscale.ts";
|
|
42
43
|
import { remoteStoreFor } from "../../core/team-client.ts";
|
|
@@ -268,7 +269,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
|
|
|
268
269
|
// P2 d: the first seam — a mode fact another writer left behind is reverted before any handler runs.
|
|
269
270
|
cfg = freshPlannerConfig(freshConfig);
|
|
270
271
|
const getCfg = (): Config => cfg;
|
|
271
|
-
seedInboxFloor(cfg);
|
|
272
|
+
if (process.env.NEURASTREAM_ROLE !== "sub") seedInboxFloor(cfg);
|
|
272
273
|
// Main's rules ride its system prompt each turn; they are never written into the owner's AGENTS.md.
|
|
273
274
|
const mainRules = renderBlock(cfg);
|
|
274
275
|
|
|
@@ -527,7 +528,9 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
|
|
|
527
528
|
// A subagent's first turn is the only one carrying its brief, and the plan the brief
|
|
528
529
|
// names is the repo whose rules it needs — the same index match the plan gate makes.
|
|
529
530
|
const plans = q.readIndex(cfg.paths.queue_index);
|
|
530
|
-
const
|
|
531
|
+
const envPlan = process.env.NEURASTREAM_PLAN;
|
|
532
|
+
const matchedPlan = plans.find(file => prompt.includes(file)) ?? (envPlan && plans.includes(envPlan) ? envPlan : null);
|
|
533
|
+
const content = unhanded(asString(c.id) || "sub", matchedPlan);
|
|
531
534
|
return content ? { message: { customType: "main-guard.rules", content, display: false } } : undefined;
|
|
532
535
|
}
|
|
533
536
|
rateLimit.onOwnerPrompt();
|
|
@@ -570,6 +573,15 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
|
|
|
570
573
|
return { block: true, reason: `main-guard: agent "${agent}" is not in "## Allowed" of ${cfg.paths.subagents}.` };
|
|
571
574
|
if (kind !== "task")
|
|
572
575
|
return { block: true, reason: "main-guard: spawn implementers with the task tool (the plan gate checks its brief)." };
|
|
576
|
+
if (process.env.HERDR_ENV === "1") {
|
|
577
|
+
const profile = resolveSpawnProfile(agent, cfg);
|
|
578
|
+
if (profile.runner !== "native") {
|
|
579
|
+
return {
|
|
580
|
+
block: true,
|
|
581
|
+
reason: `main-guard: "${agent}" is configured for runner "${profile.runner}" (harness "${profile.harness}"). Spawn it via bash: neurastream spawn --agent ${agent} --plan <plan.md> --cwd <worktree> --brief "<brief>"`,
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
}
|
|
573
585
|
return undefined;
|
|
574
586
|
});
|
|
575
587
|
|
|
@@ -965,7 +977,8 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
|
|
|
965
977
|
});
|
|
966
978
|
|
|
967
979
|
pi.on("session_shutdown", (_e, ctx) => {
|
|
968
|
-
if (isMain(ctx)
|
|
980
|
+
if (!isMain(ctx)) return;
|
|
981
|
+
if (cfg.recall.topics_model !== "") {
|
|
969
982
|
spawnTopics(cfg, ctx, ["recall", "topics", "--close"]);
|
|
970
983
|
}
|
|
971
984
|
// omp is really shutting down: the exit-grace fallback must not fire. A clean shutdown is also
|
|
@@ -1008,10 +1021,9 @@ export function reset(): void {
|
|
|
1008
1021
|
|
|
1009
1022
|
/** package.json omp.extensions entry. */
|
|
1010
1023
|
export default function ompExtension(pi: ExtensionHost): void {
|
|
1011
|
-
// The
|
|
1012
|
-
//
|
|
1013
|
-
|
|
1014
|
-
if (process.env[MAIN_ENV] !== "1") return;
|
|
1024
|
+
// The switches: `neurastream main` sets MAIN_ENV=1, while an external runner spawning an omp
|
|
1025
|
+
// helper sets NEURASTREAM_ROLE=sub. Plain `omp` sets neither and runs nothing of neurastream.
|
|
1026
|
+
if (process.env[MAIN_ENV] !== "1" && process.env.NEURASTREAM_ROLE !== "sub") return;
|
|
1015
1027
|
const initial = loadConfig();
|
|
1016
1028
|
createOmpAdapter(pi, initial, reloadingConfig(initial, configFile(), () => loadConfig(), line => adapterLog(initial, line)));
|
|
1017
1029
|
}
|
|
@@ -232,7 +232,11 @@ export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchO
|
|
|
232
232
|
for (;;) {
|
|
233
233
|
const started = Date.now();
|
|
234
234
|
// The env, not a flag: the child inherits it, so an omp started from inside Main stays guarded.
|
|
235
|
-
const code = await runChild(proxy.cmd, [...proxy.prefix, ...runArgs], {
|
|
235
|
+
const code = await runChild(proxy.cmd, [...proxy.prefix, ...runArgs], {
|
|
236
|
+
...process.env,
|
|
237
|
+
[MAIN_ENV]: "1",
|
|
238
|
+
NEURASTREAM_HARNESS: "omp",
|
|
239
|
+
});
|
|
236
240
|
const req = readRequest(started, cfg);
|
|
237
241
|
if (req === null) return code;
|
|
238
242
|
const installed = packageVersion(packageJsonPath());
|
|
@@ -3,15 +3,13 @@
|
|
|
3
3
|
// until the owner speaks. The wake lives in memory only: a restart or reload drops it, and the
|
|
4
4
|
// next owner prompt or stop re-evaluates the limits anyway.
|
|
5
5
|
|
|
6
|
-
import { currentTier } from "../../core/autonomy.ts";
|
|
7
6
|
import type { Config } from "../../core/config.ts";
|
|
8
|
-
import {
|
|
7
|
+
import { nextLimitResetMs, openQueue } from "../../core/guards.ts";
|
|
8
|
+
import { LIMIT_WAKE_TEXT } from "../shared.ts";
|
|
9
9
|
import { adapterLog } from "./launch.ts";
|
|
10
10
|
import { LIMIT_TICK_MS } from "./rate-limit-controller.ts";
|
|
11
11
|
import type { ExtensionHost, HostCtx } from "./types.ts";
|
|
12
12
|
|
|
13
|
-
const WAKE_TEXT = "main-guard: the call/edit limit has reset — continue the queue where you stopped.";
|
|
14
|
-
|
|
15
13
|
export interface LimitWake {
|
|
16
14
|
/** At session_stop's allow: one tick at the latest reset still holding Main, when plans are open. */
|
|
17
15
|
arm(c: HostCtx): void;
|
|
@@ -19,18 +17,6 @@ export interface LimitWake {
|
|
|
19
17
|
cancel(): void;
|
|
20
18
|
}
|
|
21
19
|
|
|
22
|
-
/** The latest reset (ms since epoch) of a limit still holding Main at `now`; null when none does. */
|
|
23
|
-
function pendingResetMs(cfg: Config, now: number): number | null {
|
|
24
|
-
const w = readWindow(cfg.paths);
|
|
25
|
-
const tier = currentTier(cfg);
|
|
26
|
-
const resets: number[] = [];
|
|
27
|
-
const calls = mainCallsResetMs(w);
|
|
28
|
-
if (mainCallsCapOn(cfg, tier) && w.mainCalls >= cfg.guards.main_max_calls && calls !== null && calls > now) resets.push(calls);
|
|
29
|
-
const edits = editWindowEndMs(w, cfg);
|
|
30
|
-
if (w.used.length >= mainEditLimit(cfg, tier) && edits > now) resets.push(edits);
|
|
31
|
-
return resets.length > 0 ? Math.max(...resets) : null;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
20
|
/** Plans still open; none when the queue cannot be read (logged: the stop path reports that itself). */
|
|
35
21
|
function openPlans(cfg: Config): string[] {
|
|
36
22
|
try {
|
|
@@ -64,14 +50,14 @@ export function createLimitWake(pi: ExtensionHost, getCfg: () => Config): LimitW
|
|
|
64
50
|
return;
|
|
65
51
|
}
|
|
66
52
|
adapterLog(cfg, "LIMIT-WAKE sent: the limit reset with plans open");
|
|
67
|
-
pi.sendUserMessage(
|
|
53
|
+
pi.sendUserMessage(LIMIT_WAKE_TEXT);
|
|
68
54
|
};
|
|
69
55
|
|
|
70
56
|
return {
|
|
71
57
|
arm(c) {
|
|
72
58
|
cancel();
|
|
73
59
|
const cfg = getCfg();
|
|
74
|
-
const reset =
|
|
60
|
+
const reset = nextLimitResetMs(cfg, Date.now());
|
|
75
61
|
if (reset === null || openPlans(cfg).length === 0) return;
|
|
76
62
|
wakeAt = reset;
|
|
77
63
|
const t: unknown = c.setInterval ? c.setInterval(fire, LIMIT_TICK_MS) : setInterval(fire, LIMIT_TICK_MS);
|
|
@@ -376,8 +376,12 @@ export function ompRunSource(root: string, cfg: Config): RunSource {
|
|
|
376
376
|
};
|
|
377
377
|
}
|
|
378
378
|
|
|
379
|
+
function ompSessionsRoot(cfg: Config): string {
|
|
380
|
+
return ((!cfg.adapter?.name || cfg.adapter.name === "omp") && cfg.adapter?.sessions) || join(cfg.paths.home, ".omp", "agent", "sessions");
|
|
381
|
+
}
|
|
382
|
+
|
|
379
383
|
export function defaultRunSource(cfg: Config): RunSource {
|
|
380
|
-
return ompRunSource(
|
|
384
|
+
return ompRunSource(ompSessionsRoot(cfg), cfg);
|
|
381
385
|
}
|
|
382
386
|
|
|
383
387
|
/** The text of a user message: a string, or the text parts joined. */
|
|
@@ -444,7 +448,7 @@ export function ompOwnerTurns(root: string, since: number): OwnerTurn[] {
|
|
|
444
448
|
}
|
|
445
449
|
|
|
446
450
|
export function defaultOwnerTurns(cfg: Config, since: number): OwnerTurn[] {
|
|
447
|
-
return ompOwnerTurns(
|
|
451
|
+
return ompOwnerTurns(ompSessionsRoot(cfg), since);
|
|
448
452
|
}
|
|
449
453
|
|
|
450
454
|
/**
|
|
@@ -89,11 +89,17 @@ export function asCtx(v: unknown): HostCtx {
|
|
|
89
89
|
// The agent envelope only ever carries kind/id strings (original extensions read just those);
|
|
90
90
|
// cast fixes the envelope, every field below is checked before use.
|
|
91
91
|
const agent = r.agent as { kind?: unknown; id?: unknown } | null | undefined;
|
|
92
|
-
const
|
|
93
|
-
|
|
92
|
+
const hasEnvelope = agent !== null && agent !== undefined;
|
|
93
|
+
const subEnv = process.env.NEURASTREAM_ROLE === "sub";
|
|
94
|
+
const out: HostCtx = { hasAgent: hasEnvelope || subEnv };
|
|
95
|
+
if (hasEnvelope) {
|
|
94
96
|
if (typeof agent.kind === "string") out.kind = agent.kind;
|
|
95
97
|
if (typeof agent.id === "string") out.id = agent.id;
|
|
96
98
|
}
|
|
99
|
+
if (subEnv && (!hasEnvelope || out.kind === "main")) {
|
|
100
|
+
out.kind = "sub";
|
|
101
|
+
out.id = process.env.NEURASTREAM_AGENT_ID || "sub";
|
|
102
|
+
}
|
|
97
103
|
if (typeof r.cwd === "string") out.cwd = r.cwd;
|
|
98
104
|
// Harness-injected timer with the original main-guard signature (ctx.setInterval).
|
|
99
105
|
const interval = r.setInterval as ((cb: () => void, ms: number) => unknown) | undefined;
|
|
@@ -130,7 +136,18 @@ export function asRolloverCtx(v: unknown): RolloverCtx | null {
|
|
|
130
136
|
};
|
|
131
137
|
}
|
|
132
138
|
|
|
139
|
+
/**
|
|
140
|
+
* Returns whether the current call context belongs to Main rather than a subagent.
|
|
141
|
+
* Always returns false when `NEURASTREAM_ROLE=sub` is active in the environment.
|
|
142
|
+
*
|
|
143
|
+
* Args:
|
|
144
|
+
* ctx (unknown): Untyped harness call context
|
|
145
|
+
*
|
|
146
|
+
* Returns:
|
|
147
|
+
* boolean: True when acting as Main
|
|
148
|
+
*/
|
|
133
149
|
export function isMain(ctx: unknown): boolean {
|
|
150
|
+
if (process.env.NEURASTREAM_ROLE === "sub") return false;
|
|
134
151
|
const c = asCtx(ctx);
|
|
135
152
|
return !c.hasAgent || c.kind === "main";
|
|
136
153
|
}
|