@hicaru/pi-rlm 0.3.0 → 0.3.2

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 (45) hide show
  1. package/README.md +52 -5
  2. package/README.ru.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/package.json +1 -1
  5. package/src/bridge/handlers/await.ts +148 -0
  6. package/src/bridge/handlers/completion.ts +72 -0
  7. package/src/bridge/handlers/emitting.ts +104 -0
  8. package/src/bridge/handlers/finish.ts +45 -0
  9. package/src/bridge/handlers/index.ts +48 -0
  10. package/src/bridge/handlers/llm-query.ts +130 -0
  11. package/src/bridge/handlers/rlm-query.ts +227 -0
  12. package/src/bridge/handlers/task-registry.ts +202 -0
  13. package/src/bridge/handlers/types.ts +136 -0
  14. package/src/commands/rlm-config.ts +33 -14
  15. package/src/context/listing.ts +2 -2
  16. package/src/context/refresh.ts +141 -0
  17. package/src/core/engine.ts +16 -18
  18. package/src/core/types.ts +1 -3
  19. package/src/index.ts +95 -38
  20. package/src/mode/native-guards.ts +4 -4
  21. package/src/mode/subagent.ts +68 -0
  22. package/src/prompts/glossary.ts +71 -74
  23. package/src/prompts/native.ts +127 -85
  24. package/src/prompts/system.ts +29 -15
  25. package/src/sandbox/interrupts.ts +258 -68
  26. package/src/sandbox/protocol.ts +53 -30
  27. package/src/sandbox/py/__pycache__/guards.cpython-314.pyc +0 -0
  28. package/src/sandbox/py/__pycache__/hostio.cpython-314.pyc +0 -0
  29. package/src/sandbox/py/__pycache__/retrieval.cpython-314.pyc +0 -0
  30. package/src/sandbox/py/__pycache__/tasks.cpython-314.pyc +0 -0
  31. package/src/sandbox/py/guards.py +15 -5
  32. package/src/sandbox/py/hostio.py +57 -0
  33. package/src/sandbox/py/retrieval.py +17 -8
  34. package/src/sandbox/py/tasks.py +1 -1
  35. package/src/sandbox/py/worker.py +109 -83
  36. package/src/sandbox/sandbox-manager.ts +26 -1
  37. package/src/sandbox/sandbox.ts +9 -2
  38. package/src/tool/background-tasks.ts +1 -1
  39. package/src/tool/repl-result.ts +2 -2
  40. package/src/tool/repl-tool.ts +13 -14
  41. package/src/ui/config-panel.ts +1 -1
  42. package/src/ui/intro.ts +1 -4
  43. package/src/ui/model-picker.ts +28 -2
  44. package/src/util/concurrency.ts +1 -1
  45. package/src/bridge/subcall-handlers.ts +0 -382
@@ -39,7 +39,7 @@ export async function showConfigPanel(ctx: ExtensionContext, config: RlmConfig):
39
39
  item("maxDepth", "Max recursion depth", String(config.maxDepth), CHOICES.maxDepth, "rlm_query past this depth degrades to plain llm_query (1 = no recursion)."),
40
40
  item("maxIterations", "Max iterations", String(config.maxIterations), CHOICES.maxIterations, "Maximum root REPL turns before RLM asks the model for a final answer."),
41
41
  item("execTimeoutS", "REPL block timeout (s)", String(config.execTimeoutS), CHOICES.execTimeoutS, "Wall-clock limit for one model-authored Python REPL block."),
42
- item("maxConcurrentSubcalls", "Max concurrent sub-calls", String(config.maxConcurrentSubcalls), CHOICES.maxConcurrentSubcalls, "Concurrency pool size for llm_query_batched and rlm_query_batched."),
42
+ item("maxConcurrentSubcalls", "Max concurrent sub-calls", String(config.maxConcurrentSubcalls), CHOICES.maxConcurrentSubcalls, "Concurrency pool size for llm_batch and rlm_batch."),
43
43
  item("maxConcurrentChildren", "Max concurrent children", String(config.maxConcurrentChildren), CHOICES.maxConcurrentChildren, "Concurrent rlm_query child engines per depth. Each is a Python process holding its own copy of the inherited context."),
44
44
  item("maxTimeoutMs", "Wall-clock ceiling (min)", config.maxTimeoutMs != null ? String(Math.round(config.maxTimeoutMs / 60_000)) : "none", CHOICES.maxTimeoutMs, "Total runtime cap for the whole recursive tree; none disables the cap."),
45
45
  item("maxTokens", "Token ceiling", config.maxTokens != null ? String(config.maxTokens) : "none", CHOICES.maxTokens, "Total input+output token cap for the whole recursive tree."),
package/src/ui/intro.ts CHANGED
@@ -12,10 +12,7 @@ export const RLM_GUIDE = `# RLM mode
12
12
 
13
13
  - \`/rlm\` — toggle RLM mode (shortcut: Ctrl+Shift+R). Turning it OFF also stops a running query.
14
14
  - \`/rlm-config\` — choose models, reasoning, and run limits
15
- - \`/rlm-stop\` — cancel the current run but stay in RLM mode (use /rlm or Ctrl+Shift+R to leave)
16
-
17
- When RLM mode is ON, \`read\`/\`grep\` are disabled and the agent reads the repository through the
18
- \`repl\` tool, delegating bulk analysis to sub-LLMs. The footer/status line shows the current state.`;
15
+ - \`/rlm-stop\` — cancel the current run but stay in RLM mode (use /rlm or Ctrl+Shift+R to leave)`;
19
16
 
20
17
  export function postRlmGuide(pi: ExtensionAPI, controller: RlmController): void {
21
18
  const content = RLM_GUIDE.replace("{state}", formatRlmStateLine(controller));
@@ -15,7 +15,8 @@ export interface ModelSelection {
15
15
  const LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"] as const;
16
16
  type SelectableThinkingLevel = (typeof LEVELS)[number];
17
17
 
18
- const CHEAPEST_VALUE = "__rlm_cheapest__";
18
+ /** Sentinel SelectList value for "always use cheapest available". */
19
+ export const CHEAPEST_VALUE = "__rlm_cheapest__";
19
20
 
20
21
  /**
21
22
  * Models Pi itself would offer for this session, cheapest-first.
@@ -53,6 +54,24 @@ function items(models: readonly Model<Api>[], includeCheapest: boolean): SelectI
53
54
  ];
54
55
  }
55
56
 
57
+ /**
58
+ * Index to pre-select in the model list (with cheapest row at 0 when included).
59
+ * Without this, the list always opens on "cheapest (auto)" and Enter silently unpins.
60
+ */
61
+ export function initialModelPickerIndex(
62
+ models: readonly Model<Api>[],
63
+ current?: Model<Api>,
64
+ currentRef?: string,
65
+ includeCheapest = true,
66
+ ): number {
67
+ const offset = includeCheapest ? 1 : 0;
68
+ const ref = current ? `${current.provider}/${current.id}` : currentRef;
69
+ if (!ref) return 0;
70
+ const idx = models.findIndex((m) => `${m.provider}/${m.id}` === ref);
71
+ if (idx < 0) return 0;
72
+ return idx + offset;
73
+ }
74
+
56
75
  function supportedThinkingLevels(model: Model<Api>): SelectableThinkingLevel[] {
57
76
  if (!model.reasoning) return [];
58
77
  const map = model.thinkingLevelMap;
@@ -106,6 +125,7 @@ export async function selectModel(
106
125
  models: readonly Model<Api>[],
107
126
  current?: Model<Api>,
108
127
  currentThinking?: ThinkingLevel,
128
+ currentRef?: string,
109
129
  ): Promise<ModelSelection | null | undefined> {
110
130
  if (models.length === 0) {
111
131
  ctx.ui.notify("RLM: no models available (add a provider key in Pi, or widen --models / enabledModels)", "warning");
@@ -114,7 +134,11 @@ export async function selectModel(
114
134
  if (ctx.mode !== "tui") {
115
135
  const fallback = models[0];
116
136
  if (!fallback) return undefined;
117
- const model = current ?? fallback;
137
+ // Prefer an explicit pin (resolved model or saved ref) over "first = cheapest".
138
+ const fromRef = currentRef
139
+ ? models.find((m) => `${m.provider}/${m.id}` === currentRef)
140
+ : undefined;
141
+ const model = current ?? fromRef ?? fallback;
118
142
  return { model, thinkingLevel: await selectThinkingLevel(ctx, model, currentThinking) };
119
143
  }
120
144
 
@@ -134,6 +158,8 @@ export async function selectModel(
134
158
  scrollInfo: (t) => theme.fg("dim", t),
135
159
  noMatch: (t) => theme.fg("warning", t),
136
160
  });
161
+ const initial = initialModelPickerIndex(models, current, currentRef, true);
162
+ if (initial > 0) list.setSelectedIndex(initial);
137
163
  const isFilterText = (s: string): boolean => {
138
164
  const sanitized = s.replace(/ /g, "");
139
165
  return sanitized.length > 0 && Array.from(sanitized).every((char) => char >= " " && char !== "\x7f");
@@ -73,7 +73,7 @@ export class DepthGates {
73
73
 
74
74
  /** Session-wide sub-call admission. Construct once; pass explicitly — never default one in. */
75
75
  export interface SubcallGates {
76
- /** llm_query / llm_query_batched completions — terminal, so one shared gate. */
76
+ /** llm_query / llm_batch completions — terminal, so one shared gate. */
77
77
  readonly leaf: Semaphore;
78
78
  /** Recursive child engines — one gate per depth, see DepthGates. */
79
79
  readonly rlm: DepthGates;
@@ -1,382 +0,0 @@
1
- /**
2
- * The single implementation of the sub-LLM handler set (llm_query, llm_query_batched,
3
- * rlm_query, rlm_query_batched).
4
- *
5
- * Resolves AGENTS.md DRY #1–#5, which previously lived twice: once in `createLlmBridge` /
6
- * `createRlmHandlers` for the headless engine, once in `NativeBridgeState` for the repl()
7
- * tool. The two callers only ever differed in how they answer one question — "which emitter,
8
- * limits and parent node does THIS interrupt belong to?" — so that is the only thing they
9
- * still supply, as `resolve`. The engine binds one Invocation for a whole run; the repl()
10
- * tool swaps one per turn and routes `spawn()`ed work to its session registry.
11
- *
12
- * Concurrency: every leaf completion passes through `gates.leaf`, every child engine through
13
- * `gates.rlm.at(depth)`, so a sandbox that puts 25 batches on the wire at once is still
14
- * bounded session-wide. See util/concurrency.ts for why the rlm gate is per-depth.
15
- */
16
-
17
- import type { Api, Model, Usage } from "@earendil-works/pi-ai";
18
- import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
19
- import { displayModelRef, modelRef, resolveModelId } from "../config/settings.ts";
20
- import { type ChatMsg, modelComplete } from "./model.ts";
21
- import { previewText } from "../text/preview.ts";
22
- import { checkResourceLimits } from "../core/resource-limits.ts";
23
- import { filterContextByPaths } from "../context/merge.ts";
24
- import type { RlmInput, RlmResult, Sampling } from "../core/types.ts";
25
- import type { SubcallGates } from "../util/concurrency.ts";
26
- import type { SubcallOpts, SubLlmHandlers } from "../sandbox/sandbox.ts";
27
- import type { RlmEmitter } from "../tool/rlm-events.ts";
28
- import { errorMessage, formatError, isErrorText } from "../util/errors.ts";
29
-
30
- /**
31
- * The slice of LimitGuard these handlers need. Narrow on purpose: the headless bridge is
32
- * constructed from a remaining-timeout callback rather than owning a guard, and both
33
- * shapes satisfy this.
34
- */
35
- export interface InvocationLimits {
36
- remainingTimeoutMs(): number | undefined;
37
- addUsage(usage: Usage): void;
38
- addRaw(costUsd: number, inputTokens: number, outputTokens: number): void;
39
- }
40
-
41
- /**
42
- * Adapt a "how much is left?" callback to InvocationLimits.
43
- *
44
- * The headless engine owns the real LimitGuard and folds usage in through `onUsage` /
45
- * `onChildUsage`, so the accounting methods here are deliberately inert.
46
- */
47
- export function limitsFromRemaining(
48
- remaining?: () => { readonly timeoutMs?: number },
49
- ): InvocationLimits {
50
- return {
51
- remainingTimeoutMs: () => remaining?.().timeoutMs,
52
- addUsage: () => {},
53
- addRaw: () => {},
54
- };
55
- }
56
-
57
- /**
58
- * Where one interrupt's reporting and accounting go.
59
- *
60
- * Captured at interrupt entry and threaded down, never re-read: once handlers can outlive
61
- * their exec, re-reading mutable tool state after an await would attribute a sub-call to
62
- * whichever turn happens to be current when it settles.
63
- */
64
- export interface Invocation {
65
- readonly emitter: RlmEmitter;
66
- readonly parentId: string | undefined;
67
- readonly depth: number;
68
- readonly limits: InvocationLimits;
69
- }
70
-
71
- /**
72
- * The config slice these handlers read. Structurally satisfied by `RlmConfig`, and re-read on
73
- * every call so `/rlm-config` changes take effect without rebuilding the sandbox.
74
- */
75
- export interface SubcallConfig {
76
- readonly maxPromptChars: number;
77
- readonly maxDepth: number;
78
- readonly subSampling?: Sampling;
79
- readonly subSystemPrompt?: string;
80
- }
81
-
82
- export interface SubcallHandlerDeps {
83
- /**
84
- * Pick the Invocation for this interrupt. `null` ⇒ the bridge is not wired yet.
85
- *
86
- * `depth` is the depth the sandbox reported. The headless engine trusts it (its handlers
87
- * serve one sandbox per depth); the repl() tool overrides it with its own turn depth.
88
- */
89
- readonly resolve: (opts: SubcallOpts, depth: number) => Invocation | null;
90
- /** Session-wide admission control. Required — a per-caller default would silently unbound it. */
91
- readonly gates: SubcallGates;
92
- readonly registry: ModelRegistry;
93
- readonly getLlmModel: () => Model<Api>;
94
- /** Live accessor — `/rlm-config` replaces the config object, so never capture the value. */
95
- readonly getConfig: () => SubcallConfig;
96
- readonly signal?: AbortSignal;
97
- readonly onUsage?: (usage: Usage, role: "sub") => void;
98
-
99
- // ── recursion (omit all three to get llm-only handlers) ──
100
- /**
101
- * Spawns a child RLM for rlm_query.
102
- *
103
- * Receives the parent's Invocation so the child can report on the same emitter its
104
- * parent subcall node lives on — a child of detached work must not emit to a turn
105
- * emitter that will be shut down before it finishes, and keeping parent and child on
106
- * one emitter is what lets the session registry drain the subtree intact.
107
- */
108
- readonly runChild?: (input: RlmInput, inv: Invocation) => Promise<RlmResult>;
109
- /**
110
- * The parent's live context, read at spawn time and never captured: a library loaded on turn 3
111
- * must reach a child spawned on turn 4. `undefined`/`null` ⇒ no inheritance, and the child falls
112
- * back to prompt-as-context.
113
- *
114
- * This is the ONLY inheritance seam. Adding a second construction path for a child's world
115
- * would re-open issue #4 on whichever path forgets to grow.
116
- */
117
- readonly getChildContext?: () => unknown;
118
- readonly getModel?: () => Model<Api>;
119
- /**
120
- * What rlm_query degrades to at the depth cap. A child RLM there would just be an LM, so
121
- * both callers hand in their own one-shot path rather than re-deriving one here.
122
- */
123
- readonly degrade?: (prompt: string, model: string | null, depth: number) => Promise<string>;
124
- /** Called with a child run's totals so a caller-side guard can debit them too. */
125
- readonly onChildUsage?: (costUsd: number, inputTokens: number, outputTokens: number) => void;
126
- /** Wraps detached work so a session registry can count what is still in flight. */
127
- readonly trackDetached?: <T>(run: () => Promise<T>) => Promise<T>;
128
- }
129
-
130
- /** DRY #4 — the batch failure summary, previously written out in both copies. */
131
- export function summarizeBatch(out: readonly string[]): { readonly failed: number; readonly error?: string } {
132
- let failed = 0;
133
- for (const item of out) if (isErrorText(item)) failed += 1;
134
- if (failed === 0) return { failed: 0 };
135
- const error = failed === out.length
136
- ? `all ${out.length} sub-calls failed — reduce batch size or try llm_query individually`
137
- : `${failed}/${out.length} sub-calls failed`;
138
- return { failed, error };
139
- }
140
-
141
- export type SubcallHandlers = Pick<
142
- SubLlmHandlers,
143
- "llmQuery" | "llmQueryBatched" | "rlmQuery" | "rlmQueryBatched"
144
- >;
145
-
146
- const UNWIRED = formatError("RLM bridge not wired for this invocation");
147
-
148
- function emptyResult(answer: string): RlmResult {
149
- return { answer, iterations: 0, costUsd: 0, inputTokens: 0, outputTokens: 0, durationMs: 0 };
150
- }
151
-
152
- /** What a child RLM will see, plus any `paths=` prefix that selected nothing. */
153
- interface ChildContext {
154
- readonly context: unknown;
155
- readonly unmatched: readonly string[];
156
- }
157
-
158
- const NO_UNMATCHED: readonly string[] = Object.freeze([]);
159
-
160
- export function createSubcallHandlers(deps: SubcallHandlerDeps): SubcallHandlers {
161
- /** DRY #3 — the one display-model resolution. */
162
- const displayModel = (model: string | null): string =>
163
- displayModelRef(deps.registry, model, deps.getLlmModel());
164
-
165
- /** Detached work is counted by the session registry; attached work runs as-is. */
166
- const detachable = <T>(opts: SubcallOpts, run: () => Promise<T>): Promise<T> =>
167
- opts.detached && deps.trackDetached !== undefined ? deps.trackDetached(run) : run();
168
-
169
- /** One leaf completion. Reports cost/tokens via `track`; never throws. */
170
- async function complete1(
171
- inv: Invocation,
172
- prompt: string,
173
- model: string | null,
174
- track: (usage: Usage) => void,
175
- ): Promise<string> {
176
- const config = deps.getConfig();
177
- const limitError = checkResourceLimits({
178
- timeoutMs: inv.limits.remainingTimeoutMs(),
179
- });
180
- if (limitError !== undefined) return limitError;
181
- if (prompt.length > config.maxPromptChars) {
182
- return formatError(
183
- `sub-LLM prompt exceeded the size limit (${prompt.length.toLocaleString()} chars > ` +
184
- `${config.maxPromptChars.toLocaleString()}). Shorten or chunk the prompt before calling llm_query.`,
185
- );
186
- }
187
- const resolved = model ? resolveModelId(deps.registry, model) : undefined;
188
- if (model && !resolved) return formatError(`unknown model override '${model}'`);
189
- try {
190
- const messages: ChatMsg[] = [{ role: "user", content: prompt }];
191
- const res = await deps.gates.leaf.run(() => modelComplete(messages, {
192
- model: resolved ?? deps.getLlmModel(),
193
- registry: deps.registry,
194
- system: config.subSystemPrompt,
195
- maxTokens: config.subSampling?.maxTokens,
196
- temperature: config.subSampling?.temperature,
197
- reasoning: config.subSampling?.reasoning,
198
- signal: deps.signal,
199
- }));
200
- inv.limits.addUsage(res.usage);
201
- deps.onUsage?.(res.usage, "sub");
202
- track(res.usage);
203
- return res.text;
204
- } catch (err) {
205
- const msg = errorMessage(err);
206
- const hint = /credit|402|payment|quota|rate.limit/i.test(msg)
207
- ? " — try smaller batches or individual llm_query calls"
208
- : "";
209
- return formatError(`${msg}${hint}`);
210
- }
211
- }
212
-
213
- /**
214
- * DRY #5 — the create → execute → update emit pattern for leaf sub-calls, in one place.
215
- * rlm_query does NOT use this: its node is created inside `childRun`, and a wrapper here
216
- * would double-report it.
217
- */
218
- async function emitting<T>(
219
- opts: SubcallOpts,
220
- depth: number,
221
- init: { kind: "llm" | "batch"; label: string; model: string | null; args: string },
222
- run: (inv: Invocation, track: (usage: Usage) => void) => Promise<T>,
223
- summarize: (out: T) => {
224
- readonly preview: string;
225
- readonly error?: string;
226
- readonly failed?: number;
227
- readonly total?: number;
228
- },
229
- unwired: () => T,
230
- ): Promise<T> {
231
- const inv = deps.resolve(opts, depth);
232
- if (inv === null) return unwired();
233
- const id = inv.emitter.emitSubcallCreated({
234
- kind: init.kind, parentId: inv.parentId, label: init.label,
235
- model: displayModel(init.model), args: init.args, depth: inv.depth,
236
- });
237
- let costUsd = 0;
238
- let tokens = 0;
239
- const track = (usage: Usage): void => { costUsd += usage.cost.total; tokens += usage.totalTokens; };
240
- const out = await detachable(opts, () => run(inv, track));
241
- const summary = summarize(out);
242
- inv.emitter.emitSubcallUpdated({
243
- id,
244
- status: summary.error !== undefined ? "error" : "done",
245
- costUsd, tokens,
246
- resultPreview: summary.preview,
247
- detail: summary.error,
248
- failedCount: summary.failed,
249
- totalCount: summary.total,
250
- });
251
- return out;
252
- }
253
-
254
- /**
255
- * Resolve the child's world: the parent's live context, optionally narrowed by path prefixes.
256
- *
257
- * Falls back to prompt-as-context when nothing is wired, and to the FULL context when `paths`
258
- * matched nothing — a silently blind child is exactly the bug this fixes, so a bad prefix
259
- * degrades loudly (see the note childRun folds into rootPrompt) rather than quietly.
260
- */
261
- function childContextFor(prompt: string, paths: readonly string[] | undefined): ChildContext {
262
- const inherited = deps.getChildContext?.();
263
- if (inherited === undefined || inherited === null) {
264
- return Object.freeze({ context: prompt, unmatched: NO_UNMATCHED });
265
- }
266
- if (paths === undefined || paths.length === 0) {
267
- return Object.freeze({ context: inherited, unmatched: NO_UNMATCHED });
268
- }
269
- const filtered = filterContextByPaths(inherited, paths);
270
- return Object.freeze({
271
- context: filtered.files.length > 0 ? filtered.files : inherited,
272
- unmatched: filtered.unmatched,
273
- });
274
- }
275
-
276
- /**
277
- * One child RLM run: depth cap → resource guard → spawn engine → debit parent.
278
- * Emits its own subcall node, so callers must not wrap it in another.
279
- */
280
- async function childRun(
281
- inv: Invocation,
282
- prompt: string,
283
- model: string | null,
284
- paths: readonly string[] | undefined,
285
- ): Promise<RlmResult> {
286
- const childDepth = inv.depth + 1;
287
- const run = deps.runChild;
288
- const maxDepth = deps.getConfig().maxDepth;
289
-
290
- // At the cap a child RLM would just be an LM — short-circuit to the caller's one-shot path.
291
- if (run === undefined || childDepth >= maxDepth) {
292
- const degrade = deps.degrade;
293
- const answer = degrade !== undefined
294
- ? await degrade(prompt, model, inv.depth)
295
- : await complete1(inv, prompt, model, () => {});
296
- return emptyResult(answer);
297
- }
298
-
299
- const remTimeout = inv.limits.remainingTimeoutMs();
300
- const limitError = checkResourceLimits({ timeoutMs: remTimeout });
301
- if (limitError) return emptyResult(limitError);
302
-
303
- const rootModel = deps.getModel?.();
304
- const resolvedOverride = model ? resolveModelId(deps.registry, model) : undefined;
305
- const modelLabel = model
306
- ? (modelRef(resolvedOverride) ?? `unknown/${model}`)
307
- : (rootModel === undefined ? undefined : (modelRef(rootModel) ?? rootModel.id));
308
- const subId = inv.emitter.emitSubcallCreated({
309
- kind: "rlm", parentId: inv.parentId, label: "rlm_query",
310
- model: modelLabel, detail: prompt.slice(0, 60), depth: childDepth,
311
- });
312
- // The child's context is the parent's world, not the prompt text. The prompt becomes the
313
- // child's rootPrompt, exactly as a depth-0 run takes the user's question.
314
- const child = childContextFor(prompt, paths);
315
- const rootPrompt = child.unmatched.length === 0
316
- ? prompt
317
- : `${prompt}\n\n[rlm] paths=${child.unmatched.join(", ")} matched no files; you received the full context.`;
318
- try {
319
- const res = await deps.gates.rlm.at(childDepth).run(() => run({
320
- rootPrompt,
321
- context: child.context,
322
- depth: childDepth,
323
- parentNodeId: subId,
324
- modelOverride: model ?? undefined,
325
- remainingTimeoutMs: remTimeout,
326
- }, inv));
327
- inv.limits.addRaw(res.costUsd, res.inputTokens, res.outputTokens);
328
- deps.onChildUsage?.(res.costUsd, res.inputTokens, res.outputTokens);
329
- // The child emits live usage deltas on the shared emitter, so no aggregate cost here
330
- // — adding it would double-count against SubcallStore's running totals.
331
- inv.emitter.emitSubcallUpdated({ id: subId, status: "done", resultPreview: res.answer.slice(0, 200) });
332
- return res;
333
- } catch (err) {
334
- const msg = errorMessage(err);
335
- inv.emitter.emitSubcallUpdated({ id: subId, status: "error", detail: msg });
336
- return emptyResult(formatError(`child RLM failed - ${msg}`));
337
- }
338
- }
339
-
340
- return {
341
- llmQuery: (prompt, model, depth, opts) => emitting(
342
- opts, depth,
343
- { kind: "llm", label: "llm_query", model, args: `prompt: ${previewText(prompt)}` },
344
- (inv, track) => complete1(inv, prompt, model, track),
345
- (out) => ({ preview: previewText(out), error: isErrorText(out) ? out : undefined }),
346
- () => UNWIRED,
347
- ),
348
-
349
- llmQueryBatched: (prompts, model, depth, opts) => emitting(
350
- opts, depth,
351
- { kind: "batch", label: `llm_query ×${prompts.length}`, model, args: `prompt: ${previewText(prompts[0] ?? "")}` },
352
- // NO outer gate. `complete1` already takes the single `leaf` slot each prompt needs;
353
- // an outer `gates.leaf.map` here deadlocked every batch of >= limit prompts.
354
- (inv, track) => Promise.all(prompts.map((p) => complete1(inv, p, model, track))),
355
- (out) => {
356
- const { failed, error } = summarizeBatch(out);
357
- const first = previewText(out[0] ?? "");
358
- return {
359
- preview: out.length > 1 ? `${first} (+${out.length - 1} more)` : first,
360
- error, failed, total: out.length,
361
- };
362
- },
363
- () => prompts.map(() => UNWIRED),
364
- ),
365
-
366
- async rlmQuery(prompt, model, depth, opts) {
367
- const inv = deps.resolve(opts, depth);
368
- if (inv === null) return UNWIRED;
369
- return detachable(opts, async () => (await childRun(inv, prompt, model, opts.paths)).answer);
370
- },
371
-
372
- async rlmQueryBatched(prompts, model, depth, opts) {
373
- const inv = deps.resolve(opts, depth);
374
- if (inv === null) return prompts.map(() => UNWIRED);
375
- // Bounded by the per-depth rlm gate inside childRun, not by an outer pool.
376
- return detachable(opts, async () => {
377
- const results = await Promise.all(prompts.map((p) => childRun(inv, p, model, opts.paths)));
378
- return results.map((r) => r.answer);
379
- });
380
- },
381
- };
382
- }