@hicaru/pi-rlm 0.2.1 → 0.3.0

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 (79) hide show
  1. package/README.md +28 -47
  2. package/README.ru.md +18 -23
  3. package/README.zh-CN.md +17 -28
  4. package/package.json +22 -19
  5. package/src/bridge/add-context.ts +322 -0
  6. package/src/bridge/subcall-handlers.ts +63 -17
  7. package/src/commands/rlm-config.ts +47 -18
  8. package/src/commands/rlm.ts +3 -152
  9. package/src/config/defaults.ts +8 -18
  10. package/src/config/settings.ts +13 -34
  11. package/src/context/anydoc.ts +67 -0
  12. package/src/context/listing.ts +70 -0
  13. package/src/context/md-cache.ts +112 -0
  14. package/src/context/merge.ts +97 -0
  15. package/src/context/namespace.ts +180 -0
  16. package/src/context/resolve.ts +122 -0
  17. package/src/context/source-dir.ts +166 -0
  18. package/src/context/source-doc.ts +71 -0
  19. package/src/context/source-git.ts +51 -0
  20. package/src/context/source-text.ts +45 -0
  21. package/src/context/types.ts +88 -0
  22. package/src/context/walk.ts +250 -0
  23. package/src/core/engine.ts +61 -345
  24. package/src/core/history.ts +1 -1
  25. package/src/core/limits.ts +5 -12
  26. package/src/core/resource-limits.ts +0 -2
  27. package/src/core/types.ts +10 -38
  28. package/src/index.ts +92 -54
  29. package/src/mode/llm-model.ts +54 -0
  30. package/src/mode/rlm-mode.ts +28 -58
  31. package/src/prompts/glossary.ts +290 -0
  32. package/src/prompts/native.ts +127 -0
  33. package/src/prompts/system.ts +15 -408
  34. package/src/sandbox/context-file.ts +154 -0
  35. package/src/sandbox/interrupts.ts +160 -0
  36. package/src/sandbox/protocol.ts +20 -75
  37. package/src/sandbox/py/__pycache__/guards.cpython-314.pyc +0 -0
  38. package/src/sandbox/py/__pycache__/retrieval.cpython-314.pyc +0 -0
  39. package/src/sandbox/py/__pycache__/tasks.cpython-314.pyc +0 -0
  40. package/src/sandbox/py/guards.py +150 -0
  41. package/src/sandbox/py/retrieval.py +265 -0
  42. package/src/sandbox/py/tasks.py +129 -0
  43. package/src/sandbox/py/worker.py +856 -0
  44. package/src/sandbox/sandbox-manager.ts +24 -9
  45. package/src/sandbox/sandbox.ts +99 -193
  46. package/src/text/tokens.ts +31 -5
  47. package/src/tool/repl-details.ts +2 -2
  48. package/src/tool/repl-render.ts +58 -0
  49. package/src/tool/repl-result.ts +70 -0
  50. package/src/tool/repl-tool.ts +60 -170
  51. package/src/tool/rlm-aggregator.ts +2 -10
  52. package/src/tool/rlm-details.ts +0 -2
  53. package/src/tool/rlm-events.ts +0 -14
  54. package/src/tool/rlm-tool.ts +2 -13
  55. package/src/ui/config-panel.ts +12 -20
  56. package/src/ui/intro.ts +1 -2
  57. package/src/ui/model-picker.ts +34 -10
  58. package/src/ui/status.ts +3 -7
  59. package/src/util/concurrency.ts +9 -5
  60. package/src/bridge/fallback-todo.ts +0 -148
  61. package/src/bridge/interactive.ts +0 -65
  62. package/src/bridge/library.ts +0 -155
  63. package/src/bridge/pi-interactive.ts +0 -41
  64. package/src/context/library-context.ts +0 -266
  65. package/src/context/repomix-context.ts +0 -204
  66. package/src/core/artifacts.ts +0 -89
  67. package/src/core/critique.ts +0 -92
  68. package/src/core/gates.ts +0 -301
  69. package/src/core/pipeline-handlers.ts +0 -319
  70. package/src/core/pipeline.ts +0 -268
  71. package/src/prompts/phases.ts +0 -104
  72. package/src/sandbox/worker.py +0 -1456
  73. package/src/state/index.ts +0 -24
  74. package/src/state/internal.ts +0 -46
  75. package/src/state/paths.ts +0 -44
  76. package/src/state/reads.ts +0 -133
  77. package/src/state/resume.ts +0 -173
  78. package/src/state/rows.ts +0 -123
  79. package/src/state/writes.ts +0 -58
@@ -0,0 +1,856 @@
1
+ """RLM sandbox worker: a persistent Python REPL driven over a JSONL stdio protocol.
2
+
3
+ Executes model-authored Python with secrets stripped from the environment.
4
+ This is NOT a security sandbox: __import__ and open are available, so code can import networking modules
5
+ (socket, urllib, subprocess) and read/write local files. Trust the root model's code.
6
+
7
+ Protocol (parent -> worker): {"id","type":"exec"|"load_context"|"shutdown", ...}
8
+ Protocol (worker -> parent): {"id","ok",...result} # response to a request
9
+ {"type":"llm_query"|"llm_query_batched"|"rlm_query"|
10
+ "rlm_query_batched"|"add_context","rid",...}
11
+ # mid-exec helper request
12
+ When sandbox code calls llm_query/rlm_query/add_context, the worker writes a
13
+ request line and BLOCKS reading stdin until the matching {"type":"llm_reply","rid",...} arrives.
14
+ The parent services the request in-process (it holds API keys).
15
+
16
+ Requests and replies are decoupled: `_post` writes a request and returns its rid without
17
+ waiting, and replies are parked in `_inbox` keyed by rid until something asks for them. That
18
+ is what makes `spawn()` / `rlm_await()` / `rlm_await_all()` possible — many requests can be
19
+ in flight at once (the parent already services interrupts concurrently), and a task may be
20
+ awaited in a LATER exec than the one that started it.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import io
26
+ import json
27
+ import os
28
+ import signal
29
+ import sys
30
+ import time
31
+ import traceback
32
+ from contextlib import contextmanager
33
+ from typing import Any
34
+
35
+ # Sibling modules: Python puts this file's directory on sys.path[0], so these resolve without
36
+ # any packaging step. They ship inside `src/` like everything else.
37
+ from guards import (
38
+ _SAFE_BUILTINS,
39
+ _CONTEXT_NAME,
40
+ _send,
41
+ _stall_alarm,
42
+ _surfaced_error,
43
+ RESERVED,
44
+ REAL_STDERR as _REAL_STDERR,
45
+ REAL_STDIN as _REAL_STDIN,
46
+ )
47
+ from retrieval import (
48
+ _Bm25Index,
49
+ _chunk_text,
50
+ _context_entries,
51
+ _CHUNK_HEADER_OVERHEAD,
52
+ _MAX_CHUNK_BATCH,
53
+ _MAX_CHUNKS,
54
+ _NUDGE_CHARS,
55
+ grep_context as _grep_context_impl,
56
+ outline as _outline_impl,
57
+ search as _search_impl,
58
+ )
59
+ from tasks import (
60
+ _clean_paths,
61
+ _reduce_batch,
62
+ _reduce_chunked,
63
+ _reduce_map_files,
64
+ _reduce_one,
65
+ _spawnable,
66
+ Task,
67
+ )
68
+
69
+ class _AnswerDict(dict):
70
+ """`answer` dict; flipping `ready` True captures the final answer for the parent."""
71
+
72
+ def __init__(self, on_ready):
73
+ super().__init__()
74
+ super().__setitem__("content", "")
75
+ super().__setitem__("ready", False)
76
+ self._on_ready = on_ready
77
+
78
+ def __setitem__(self, key, value):
79
+ super().__setitem__(key, value)
80
+ if key == "ready" and value:
81
+ self._on_ready(self.get("content", ""))
82
+
83
+
84
+
85
+ class Worker:
86
+ def __init__(
87
+ self,
88
+ depth: int,
89
+ exec_timeout_s: float,
90
+ max_prompt_chars: int,
91
+ await_timeout_s: float = 600.0,
92
+ ):
93
+ self.depth = depth
94
+ self.exec_timeout_s = exec_timeout_s
95
+ self.max_prompt_chars = max_prompt_chars
96
+ self.await_timeout_s = await_timeout_s
97
+ self._rid = 0
98
+ self._final_answer: str | None = None
99
+ # Replies parked by rid until something awaits them. Unbounded by design: a task
100
+ # the model spawns and never awaits keeps its entry for the life of the process.
101
+ # Bounded in practice by session length; evicting would silently hang a later
102
+ # rlm_await, which is strictly worse than the memory.
103
+ self.inbox: dict[str, dict[str, Any]] = {}
104
+ self._inflight: set[str] = set()
105
+ # Requests (exec/shutdown) that arrived mid-exec; main() replays them.
106
+ self._deferred: list[Any] = []
107
+ # True only while spawn() runs a builder — marks requests that may outlive this exec.
108
+ self._detached = False
109
+ self.ns: dict[str, Any] = {}
110
+ self._setup()
111
+
112
+ def _setup(self) -> None:
113
+ builtins = _SAFE_BUILTINS.copy()
114
+ builtins["open"] = open
115
+ self.ns = {"__builtins__": builtins, "__name__": "__main__"}
116
+ self._context_payload: Any = [] # empty list — the only starting value that needs no bootstrap branch
117
+ self._nudged: set[str] = set()
118
+ self._index: _Bm25Index | None = None
119
+ self._index_stamp: tuple[int, int] | None = None # (id(context), len(context))
120
+ self._restore_scaffold()
121
+
122
+ def _capture_answer(self, content: Any) -> None:
123
+ self._final_answer = str(content)
124
+
125
+ def _restore_scaffold(self) -> None:
126
+ # Re-inject any scaffolding the user code clobbered.
127
+ ns = self.ns
128
+ ns["llm_query"] = self._llm_query
129
+ ns["llm_query_batched"] = self._llm_query_batched
130
+ ns["llm_query_chunked"] = self._llm_query_chunked
131
+ ns["rlm_query"] = self._rlm_query
132
+ ns["rlm_query_batched"] = self._rlm_query_batched
133
+ ns["spawn"] = self._spawn
134
+ ns["rlm_await"] = self._await_task
135
+ ns["rlm_await_all"] = self._await_all
136
+ ns["map_files"] = self._map_files
137
+ ns["llm_map_reduce"] = self._llm_map_reduce
138
+ ns["search"] = self._search
139
+ ns["grep_context"] = self._grep_context
140
+ ns["outline"] = self._outline
141
+ # env_tips memo (paper App. C.3): "If a value isn't in `answers`, it doesn't exist."
142
+ # Re-created only when deleted — contents must survive every turn.
143
+ if not isinstance(ns.get("answers"), dict):
144
+ ns["answers"] = {}
145
+ if not isinstance(ns.get("plan"), dict):
146
+ ns["plan"] = {}
147
+ ns["add_context"] = self._add_context
148
+ ns["SHOW_VARS"] = self._show_vars
149
+ if not isinstance(ns.get("answer"), _AnswerDict):
150
+ cur = ns.get("answer")
151
+ ans = _AnswerDict(self._capture_answer)
152
+ if isinstance(cur, dict):
153
+ for k, v in cur.items():
154
+ dict.__setitem__(ans, k, v)
155
+ if cur.get("ready") and self._final_answer is None:
156
+ self._final_answer = str(cur.get("content", ""))
157
+ ns["answer"] = ans
158
+ # Single context variable (RLM paper: the context lives in the environment and
159
+ # the model may transform it in place). Re-inject only if the model deleted the
160
+ # name entirely; mutations and re-binds persist within the run. Always a list.
161
+ ns.setdefault("context", self._context_payload)
162
+ # Scrub any legacy context_N names so the model never sees multi-slot APIs.
163
+ for k in list(ns.keys()):
164
+ if k != "context" and _CONTEXT_NAME.match(k):
165
+ del ns[k]
166
+
167
+ def _user_var_names(self) -> list[str]:
168
+ """User-created variable names — filters builtins, scaffold, and `context`.
169
+
170
+ Shared by SHOW_VARS() and the exec result so both expose the same namespace view.
171
+ This is the cheap orientation hint that goes into history instead of full stdout.
172
+ """
173
+ return [
174
+ k for k in self.ns
175
+ if not k.startswith("_")
176
+ and not _CONTEXT_NAME.match(k)
177
+ and k not in RESERVED
178
+ ]
179
+
180
+ def _show_vars(self) -> str:
181
+ avail = {k: type(self.ns[k]).__name__ for k in self._user_var_names()}
182
+ return f"Available variables: {avail}" if avail else "No variables created yet."
183
+
184
+ # ---- sub-LLM bridge over stdio --------------------------------------------------------
185
+
186
+ def _post(self, kind: str, payload: dict[str, Any]) -> str:
187
+ """Write one parent request and return its rid WITHOUT waiting for the reply."""
188
+ self._rid += 1
189
+ rid = f"q{self._rid}"
190
+ # Register only after the write succeeds — a broken pipe must not leave an
191
+ # _inflight entry that nothing will ever settle.
192
+ _send({"type": kind, "rid": rid, "depth": self.depth,
193
+ "detached": self._detached, **payload})
194
+ self._inflight.add(rid)
195
+ return rid
196
+
197
+ def park_reply(self, msg: Any) -> bool:
198
+ """File an llm_reply against its rid. True when the frame was a reply.
199
+
200
+ Public because main() needs it too: a spawned task can settle while the worker
201
+ sits idle between execs, and that reply must not fall through to "unknown type".
202
+ """
203
+ if not isinstance(msg, dict) or msg.get("type") != "llm_reply":
204
+ return False
205
+ rid = msg.get("rid")
206
+ if isinstance(rid, str) and rid in self._inflight:
207
+ self._inflight.discard(rid)
208
+ self.inbox[rid] = msg
209
+ else:
210
+ # Late reply to an abandoned rid (e.g. a request from a discarded sandbox).
211
+ print(f"[rlm-sandbox] dropping reply for unknown rid: {rid!r}", file=_REAL_STDERR)
212
+ return True
213
+
214
+ def take_deferred(self) -> Any | None:
215
+ """Pop a request that arrived mid-exec, for main() to replay. None when empty."""
216
+ return self._deferred.pop(0) if self._deferred else None
217
+
218
+ def _pump(self) -> bool:
219
+ """Read one frame from the parent into the inbox. False when the pipe closed."""
220
+ line = _REAL_STDIN.readline()
221
+ if not line:
222
+ return False
223
+ try:
224
+ msg = json.loads(line)
225
+ except ValueError:
226
+ print(f"[rlm-sandbox] skipping non-JSON parent frame: {line[:200]}", file=_REAL_STDERR)
227
+ return True
228
+ if self.park_reply(msg):
229
+ return True
230
+ # A request (exec/shutdown) arriving mid-exec: main() replays it.
231
+ self._deferred.append(msg)
232
+ return True
233
+
234
+ def _drain_until(self, rids) -> None:
235
+ """Block until every rid in `rids` has its reply parked in the inbox.
236
+
237
+ Bounded: a host that goes silent raises inside the ```repl``` block instead of hanging
238
+ the session forever.
239
+ """
240
+ if all(r in self.inbox for r in rids):
241
+ return
242
+ with _stall_alarm(self.exec_timeout_s, self.await_timeout_s) as rearm:
243
+ while not all(r in self.inbox for r in rids):
244
+ if not self._pump():
245
+ raise RuntimeError("parent closed the pipe during a sub-LLM request")
246
+ rearm()
247
+
248
+ def _take(self, rids) -> list[dict[str, Any]]:
249
+ return [self.inbox.pop(r) for r in rids]
250
+
251
+ def _rpc(self, kind: str, payload: dict[str, Any]) -> dict[str, Any]:
252
+ """Post one request and block for its reply — the synchronous single-shot path."""
253
+ rid = self._post(kind, payload)
254
+ self._drain_until((rid,))
255
+ return self._take((rid,))[0]
256
+
257
+ # ---- spawn / await ---------------------------------------------------------------------
258
+
259
+ def _start_prompt(self, kind: str, prompt, model, paths=None) -> Task:
260
+ text = str(prompt)
261
+ # A sub-LLM asked nothing answers something: the confabulation then sits in `answers`
262
+ # looking exactly like data. Refuse instead of spending a call on it.
263
+ if not text.strip():
264
+ return Task.resolved(self, kind, _surfaced_error(
265
+ f"{kind}() got an empty prompt — a sub-LLM would confabulate an answer to nothing"))
266
+ payload: dict[str, Any] = {"prompt": text, "model": model}
267
+ clean = _clean_paths(paths)
268
+ if clean is not None:
269
+ payload["paths"] = clean
270
+ rid = self._post(kind, payload)
271
+ return Task(self, kind, (rid,), _reduce_one, text[:40])
272
+
273
+ def _start_prompts(self, kind: str, prompts, model, paths=None) -> Task:
274
+ prompts = [str(p) for p in prompts]
275
+ if not prompts:
276
+ return Task.resolved(self, kind, [])
277
+ # Only the all-blank case: one blank prompt among twenty is the caller's business.
278
+ if not any(p.strip() for p in prompts):
279
+ return Task.resolved(self, kind, [
280
+ _surfaced_error(f"{kind}() got only empty prompts")
281
+ ] * len(prompts))
282
+ payload: dict[str, Any] = {"prompts": prompts, "model": model}
283
+ # One prefix set for the whole batch: a per-prompt aligned list is an API nobody uses
284
+ # correctly, and every prompt in a batch is asking about the same slice anyway.
285
+ clean = _clean_paths(paths)
286
+ if clean is not None:
287
+ payload["paths"] = clean
288
+ rid = self._post(kind, payload)
289
+ return Task(self, kind, (rid,), _reduce_batch(len(prompts)), f"×{len(prompts)}")
290
+
291
+ def _start_llm_query(self, prompt, model: str | None = None) -> Task:
292
+ return self._start_prompt("llm_query", prompt, model)
293
+
294
+ def _start_rlm_query(self, prompt, model: str | None = None, paths=None) -> Task:
295
+ return self._start_prompt("rlm_query", prompt, model, paths)
296
+
297
+ def _start_llm_query_batched(self, prompts, model: str | None = None) -> Task:
298
+ return self._start_prompts("llm_query_batched", prompts, model)
299
+
300
+ def _start_rlm_query_batched(self, prompts, model: str | None = None, paths=None) -> Task:
301
+ return self._start_prompts("rlm_query_batched", prompts, model, paths)
302
+
303
+ def _start_llm_query_chunked(self, text, prompt: str, model: str | None = None) -> Task:
304
+ """Split oversized text into cap-sized chunks and post EVERY batch at once.
305
+
306
+ One answer per chunk, order preserved. No exceptions escape: errors come back as
307
+ "Error: ..." strings per chunk (same contract as llm_query_batched). Because all
308
+ batches go on the wire together, a large input costs one round-trip of latency
309
+ rather than one per 20 chunks.
310
+
311
+ NOTE: budget uses Python code-point length (len) while the parent-side cap check counts
312
+ UTF-16 units (JS string.length); astral/emoji-heavy text may be marginally larger on the
313
+ parent and get per-chunk rejected. Acceptable trade-off for typical code/log/profile text.
314
+ """
315
+ text, prompt = str(text), str(prompt)
316
+ if not text:
317
+ return Task.resolved(self, "llm_query_chunked", [])
318
+ budget = self.max_prompt_chars - len(prompt) - _CHUNK_HEADER_OVERHEAD
319
+ if budget < 1_000:
320
+ return Task.resolved(self, "llm_query_chunked", [
321
+ f"Error: prompt leaves under 1,000 chars per chunk (cap {self.max_prompt_chars:,}) — shorten the instruction"
322
+ ])
323
+ chunks = _chunk_text(text, budget)
324
+ total = len(chunks)
325
+ if total > _MAX_CHUNKS:
326
+ return Task.resolved(self, "llm_query_chunked", [
327
+ f"Error: {total} chunks would be needed — filter/slice the text in Python first"
328
+ ])
329
+ rids: list[str] = []
330
+ sizes: list[int] = []
331
+ for i in range(0, total, _MAX_CHUNK_BATCH):
332
+ batch = [
333
+ f"{prompt}\n\n[chunk {i + j + 1}/{total} of the input]\n{c}"
334
+ for j, c in enumerate(chunks[i:i + _MAX_CHUNK_BATCH])
335
+ ]
336
+ rids.append(self._post("llm_query_batched", {"prompts": batch, "model": model}))
337
+ sizes.append(len(batch))
338
+ return Task(self, "llm_query_chunked", tuple(rids), _reduce_chunked(sizes), f"{total} chunks")
339
+
340
+ def _builder_for(self, name: str):
341
+ # llm_map_reduce is deliberately absent: its reduce step is a SECOND sub-LLM call that
342
+ # depends on its own map results, so it cannot be one (rids, pure reduce) Task.
343
+ return {
344
+ "llm_query": self._start_llm_query,
345
+ "llm_query_batched": self._start_llm_query_batched,
346
+ "llm_query_chunked": self._start_llm_query_chunked,
347
+ "map_files": self._start_map_files,
348
+ "rlm_query": self._start_rlm_query,
349
+ "rlm_query_batched": self._start_rlm_query_batched,
350
+ }.get(name)
351
+
352
+ def _spawn(self, fn, *args, **kwargs) -> Task:
353
+ """Start a sub-call without waiting for it. `fn` is the scaffold function itself.
354
+
355
+ Returns a Task for rlm_await / rlm_await_all, possibly in a later ```repl``` block.
356
+ Misuse returns an already-resolved error Task rather than raising, matching the
357
+ "Error: ..." contract of the synchronous helpers.
358
+ """
359
+ name = getattr(fn, "_rlm_name", None)
360
+ builder = self._builder_for(name) if isinstance(name, str) else None
361
+ if builder is None:
362
+ return Task.resolved(self, "spawn", _surfaced_error(
363
+ "spawn() takes llm_query, llm_query_batched, llm_query_chunked, map_files, "
364
+ "rlm_query or rlm_query_batched — not llm_map_reduce, whose reduce step depends "
365
+ "on its own map results and so cannot be a single Task"))
366
+ # Mark every request this builder posts as detached: the parent routes them to its
367
+ # session-scoped registry, since they may outlive the exec that started them.
368
+ self._detached = True
369
+ try:
370
+ return builder(*args, **kwargs)
371
+ except TypeError as e:
372
+ return Task.resolved(self, "spawn", _surfaced_error(f"bad spawn arguments — {e}"))
373
+ finally:
374
+ self._detached = False
375
+
376
+ def _await_task(self, task) -> Any:
377
+ """Block until `task` has its result. Idempotent — the value is memoized."""
378
+ if not isinstance(task, Task):
379
+ return _surfaced_error(
380
+ f"rlm_await expects a Task from spawn(), got {type(task).__name__}"
381
+ )
382
+ if not task._settled:
383
+ self._drain_until(task._rids)
384
+ task._value = task._reduce(self._take(task._rids))
385
+ task._settled = True
386
+ return task._value
387
+
388
+ def _await_all(self, tasks) -> list:
389
+ """Block until every task has its result. Order matches the input."""
390
+ tasks = list(tasks)
391
+ # One union drain so the tasks overlap instead of settling one after another.
392
+ union: list[str] = []
393
+ seen: set[str] = set()
394
+ for t in tasks:
395
+ if not isinstance(t, Task) or t._settled:
396
+ continue
397
+ for rid in t._rids:
398
+ if rid not in seen:
399
+ seen.add(rid)
400
+ union.append(rid)
401
+ if union:
402
+ self._drain_until(union)
403
+ return [self._await_task(t) for t in tasks]
404
+
405
+ # ---- deterministic retrieval (no sub-LLM calls, no root tokens) -----------------------
406
+
407
+ def _entries(self) -> list[tuple[str, str]]:
408
+ return _context_entries(self.ns.get("context"))
409
+
410
+ def _get_index(self) -> _Bm25Index:
411
+ """Build the BM25 index on first use; rebuild when `context` was replaced or resized.
412
+
413
+ Identity+length is a cheap stamp that catches the two ways context actually changes:
414
+ add_context() extending the list, and the model re-binding the name. In-place edits
415
+ that preserve length are not detected — documented, and rare in practice.
416
+ """
417
+ ctx = self.ns.get("context")
418
+ stamp = (id(ctx), len(ctx) if isinstance(ctx, (list, str)) else 0)
419
+ if self._index is None or self._index_stamp != stamp:
420
+ self._index = _Bm25Index(self._entries())
421
+ self._index_stamp = stamp
422
+ return self._index
423
+
424
+ def _search(self, query: str, k: int = 10, path_glob: str | None = None) -> list[dict[str, Any]]:
425
+ """Rank `context` windows against a natural-language query (BM25).
426
+
427
+ Returns [{path, line, score, snippet}] — pointers, not bodies.
428
+ """
429
+ return _search_impl(self._entries(), self._get_index(), query, k, path_glob)
430
+
431
+ def _grep_context(
432
+ self,
433
+ pattern: str,
434
+ k: int = 50,
435
+ path_glob: str | None = None,
436
+ before: int = 0,
437
+ after: int = 0,
438
+ ) -> dict[str, Any]:
439
+ """Regex over `context`, capped and shaped. See retrieval.grep_context."""
440
+ return _grep_context_impl(self._entries(), pattern, k, path_glob, before, after)
441
+
442
+ def _outline(self, path: str) -> str:
443
+ """Definition/heading skeleton of one context file. See retrieval.outline."""
444
+ return _outline_impl(self._entries(), path)
445
+
446
+ # ---- one-line delegation (structural: orchestrating must be easier than solving) -------
447
+
448
+ def _start_map_files(self, files: Any, prompt: str, model: str | None = None) -> Task:
449
+ """Post every batch map_files needs, WITHOUT waiting. Contract: see _map_files.
450
+
451
+ All batches go on the wire together, so a 100-file map costs one round-trip of latency
452
+ rather than one per 20 files.
453
+ """
454
+ prompt = str(prompt)
455
+ by_path: list[tuple[str, str]] = []
456
+ lookup: dict[str, str] | None = None
457
+ for item in files if isinstance(files, (list, tuple)) else [files]:
458
+ if isinstance(item, dict):
459
+ content = item.get("content", "")
460
+ by_path.append((str(item.get("path", "?")), content if isinstance(content, str) else str(content)))
461
+ elif isinstance(item, str):
462
+ if lookup is None:
463
+ lookup = {p: c for p, c in self._entries()}
464
+ if item in lookup:
465
+ by_path.append((item, lookup[item]))
466
+ else:
467
+ by_path.append((item, ""))
468
+ if not by_path:
469
+ return Task.resolved(self, "map_files", {})
470
+
471
+ # Per-file prompt budget; anything larger is chunked and its answers concatenated.
472
+ budget = self.max_prompt_chars - len(prompt) - _CHUNK_HEADER_OVERHEAD - 256
473
+ if budget < 1_000:
474
+ return Task.resolved(self, "map_files", {
475
+ p: "Error: prompt too long to leave room for file content" for p, _ in by_path
476
+ })
477
+
478
+ requests: list[str] = []
479
+ spans: list[tuple[str, int]] = [] # (path, number of chunks contributed)
480
+ for path, content in by_path:
481
+ chunks = _chunk_text(content, budget) if len(content) > budget else [content]
482
+ spans.append((path, len(chunks)))
483
+ for j, chunk in enumerate(chunks):
484
+ header = f"[file {path}" + (f", part {j + 1}/{len(chunks)}]" if len(chunks) > 1 else "]")
485
+ requests.append(f"{prompt}\n\n{header}\n{chunk}")
486
+
487
+ rids: list[str] = []
488
+ sizes: list[int] = []
489
+ for i in range(0, len(requests), _MAX_CHUNK_BATCH):
490
+ batch = requests[i:i + _MAX_CHUNK_BATCH]
491
+ rids.append(self._post("llm_query_batched", {"prompts": batch, "model": model}))
492
+ sizes.append(len(batch))
493
+ return Task(self, "map_files", tuple(rids),
494
+ _reduce_map_files(sizes, spans), f"{len(by_path)} files")
495
+
496
+ @_spawnable("map_files")
497
+ def _map_files(self, files: Any, prompt: str, model: str | None = None) -> dict[str, str]:
498
+ """Ask `prompt` of every given file, batched, and return {path: answer}.
499
+
500
+ `files` accepts context entries (dicts), paths (strings), or a mix — the whole
501
+ chunk/batch/collect loop the system prompt used to spell out, as one call.
502
+ Oversized files are split and their per-chunk answers joined.
503
+ """
504
+ return self._await_task(self._start_map_files(files, prompt, model))
505
+
506
+ def _llm_map_reduce(
507
+ self,
508
+ items: Any,
509
+ map_prompt: str,
510
+ reduce_prompt: str,
511
+ model: str | None = None,
512
+ ) -> str:
513
+ """Map `map_prompt` over `items` in one batch, then reduce the answers with one call.
514
+
515
+ The paper's canonical strategy ("query an LLM per chunk ... then query an LLM with all
516
+ the buffers") as a single call, so the root never hand-rolls the loop.
517
+ """
518
+ map_prompt, reduce_prompt = str(map_prompt), str(reduce_prompt)
519
+ seq = list(items) if isinstance(items, (list, tuple)) else [items]
520
+ if not seq:
521
+ return "Error: llm_map_reduce got no items"
522
+ texts = [
523
+ (str(it.get("content", "")) if isinstance(it, dict) else str(it))
524
+ for it in seq
525
+ ]
526
+ labels = [
527
+ (str(it.get("path", f"item {i + 1}")) if isinstance(it, dict) else f"item {i + 1}")
528
+ for i, it in enumerate(seq)
529
+ ]
530
+ mapped: list[str] = []
531
+ for i in range(0, len(texts), _MAX_CHUNK_BATCH):
532
+ batch = [
533
+ f"{map_prompt}\n\n[{labels[i + j]}]\n{t}"
534
+ for j, t in enumerate(texts[i:i + _MAX_CHUNK_BATCH])
535
+ ]
536
+ mapped.extend(self._llm_query_batched(batch, model))
537
+ joined = "\n\n".join(f"[{labels[i]}]\n{a}" for i, a in enumerate(mapped))
538
+ return self._llm_query(f"{reduce_prompt}\n\nPartial answers:\n{joined}", model)
539
+
540
+ # ---- sync helpers: await(start(...)), so there is exactly one code path -----------------
541
+
542
+ @_spawnable("llm_query")
543
+ def _llm_query(self, prompt: str, model: str | None = None) -> str:
544
+ return self._await_task(self._start_llm_query(prompt, model))
545
+
546
+ @_spawnable("llm_query_batched")
547
+ def _llm_query_batched(self, prompts, model: str | None = None) -> list[str]:
548
+ return self._await_task(self._start_llm_query_batched(prompts, model))
549
+
550
+ @_spawnable("llm_query_chunked")
551
+ def _llm_query_chunked(self, text, prompt: str, model: str | None = None) -> list[str]:
552
+ return self._await_task(self._start_llm_query_chunked(text, prompt, model))
553
+
554
+ @_spawnable("rlm_query")
555
+ def _rlm_query(self, prompt: str, model: str | None = None, paths=None) -> str:
556
+ return self._await_task(self._start_rlm_query(prompt, model, paths))
557
+
558
+ def _add_context(self, source: str) -> dict[str, Any] | str:
559
+ """Pack an external dir/file/git-URL on the host and append it into `context`.
560
+
561
+ Paths are namespaced under ctx/<source_id>/ (host). Content is always in the
562
+ single `context` list — never a new context_N variable.
563
+ Host-side idempotency may return already_loaded without a payload path.
564
+ Documents (PDF/DOCX/…) are converted to Markdown on the host.
565
+ """
566
+ r = self._rpc("add_context", {"source": str(source)})
567
+ if r.get("error"):
568
+ return f"Error: {r['error']}"
569
+ if r.get("already_loaded"):
570
+ source_id = r.get("source_id") if isinstance(r.get("source_id"), str) else "ctx"
571
+ path_prefix = r.get("path_prefix") if isinstance(r.get("path_prefix"), str) else f"ctx/{source_id}/"
572
+ ctx = self.ns.get("context")
573
+ ctx_len = len(ctx) if isinstance(ctx, list) else 0
574
+ print(
575
+ f"[rlm] add_context: already loaded {source_id} "
576
+ f"(paths under {path_prefix}, context len={ctx_len})"
577
+ )
578
+ return {
579
+ "source": str(source),
580
+ "source_id": source_id,
581
+ "path_prefix": path_prefix,
582
+ "files": 0,
583
+ "chars": r.get("chars"),
584
+ "context_len": ctx_len,
585
+ "already_loaded": True,
586
+ "documents": 0,
587
+ "converted": 0,
588
+ "skipped": [],
589
+ }
590
+ path = r.get("path")
591
+ if not isinstance(path, str):
592
+ return "Error: malformed add_context reply (no path)"
593
+ try:
594
+ with io.open(path, "r") as f:
595
+ payload = json.load(f) if r.get("json") else f.read()
596
+ finally:
597
+ try:
598
+ os.remove(path) # worker owns temp-file cleanup (host does NOT unlink)
599
+ except OSError:
600
+ pass
601
+ return self._append_context(str(source), payload, r)
602
+
603
+ def _append_context(self, source: str, payload: Any, meta: dict[str, Any]) -> dict[str, Any] | str:
604
+ """Append host-packed files into `context` (idempotent by path prefix).
605
+
606
+ The two refusals below are pre-flighted host-side by LIST_CONTEXT_REQUIRED /
607
+ NO_FILES_PRODUCED in src/bridge/add-context.ts, so the host never commits a
608
+ loaded-prefix for an append that fails here. Reaching either one means host and worker
609
+ disagree about `context`; keep the wording identical to its twin.
610
+ """
611
+ ctx = self.ns.get("context")
612
+ if not isinstance(ctx, list):
613
+ kind = type(ctx).__name__ if ctx is not None else "None"
614
+ return f"Error: add_context requires list context (file bundle); got {kind}"
615
+
616
+ source_id = meta.get("source_id")
617
+ if not isinstance(source_id, str) or not source_id:
618
+ source_id = "ctx"
619
+ path_prefix = meta.get("path_prefix")
620
+ if not isinstance(path_prefix, str):
621
+ path_prefix = f"ctx/{source_id}/"
622
+ # Empty path_prefix is valid (cwd seed) but add_context always sends a non-empty ctx/ prefix.
623
+ # Guard startsWith on empty prefix: "anything".startswith("") is always True.
624
+ check_prefix = path_prefix if path_prefix != "" else None
625
+
626
+ # Idempotent: already present if any path uses this prefix.
627
+ if check_prefix is not None:
628
+ for item in ctx:
629
+ if isinstance(item, dict) and str(item.get("path", "")).startswith(check_prefix):
630
+ print(
631
+ f"[rlm] add_context: already loaded {source_id} "
632
+ f"(paths under {path_prefix}, context len={len(ctx)})"
633
+ )
634
+ return {
635
+ "source": source,
636
+ "source_id": source_id,
637
+ "path_prefix": path_prefix,
638
+ "files": 0,
639
+ "chars": meta.get("chars"),
640
+ "context_len": len(ctx),
641
+ "already_loaded": True,
642
+ "documents": 0,
643
+ "converted": 0,
644
+ "skipped": [],
645
+ }
646
+
647
+ files = self._context_file_entries(payload, path_prefix)
648
+ if not files:
649
+ return "Error: add_context produced no files"
650
+
651
+ ctx.extend(files)
652
+ # Keep restore payload in sync with the live list.
653
+ self._context_payload = ctx
654
+ self.ns["context"] = ctx
655
+
656
+ documents = meta.get("documents") if isinstance(meta.get("documents"), int) else 0
657
+ converted = meta.get("converted") if isinstance(meta.get("converted"), int) else 0
658
+ skipped = meta.get("skipped") if isinstance(meta.get("skipped"), list) else []
659
+ skip_n = len(skipped)
660
+ extra = ""
661
+ if documents or converted or skip_n:
662
+ extra = f"; documents={documents}, converted={converted}, skipped={skip_n}"
663
+ print(
664
+ f"[rlm] add_context: +{len(files)} files into context "
665
+ f"(len={len(ctx)}); paths under {path_prefix}{extra}"
666
+ )
667
+ return {
668
+ "source": source,
669
+ "source_id": source_id,
670
+ "path_prefix": path_prefix,
671
+ "files": len(files),
672
+ "chars": meta.get("chars"),
673
+ "context_len": len(ctx),
674
+ "already_loaded": False,
675
+ "documents": documents,
676
+ "converted": converted,
677
+ "skipped": skipped,
678
+ }
679
+
680
+ @staticmethod
681
+ def _context_file_entries(payload: Any, path_prefix: str) -> list[dict[str, Any]]:
682
+ """Normalize host payload to list[dict]. Host already namespaces; string is fallback."""
683
+ if isinstance(payload, str):
684
+ return [{
685
+ "path": f"{path_prefix}content" if path_prefix else "content",
686
+ "content": payload,
687
+ "tokens": max(1, (len(payload) + 3) // 4),
688
+ }]
689
+ if not isinstance(payload, list):
690
+ return []
691
+ out: list[dict[str, Any]] = []
692
+ for item in payload:
693
+ if isinstance(item, dict) and "path" in item and "content" in item:
694
+ out.append(item)
695
+ return out
696
+
697
+ @_spawnable("rlm_query_batched")
698
+ def _rlm_query_batched(self, prompts, model: str | None = None, paths=None) -> list[str]:
699
+ return self._await_task(self._start_rlm_query_batched(prompts, model, paths))
700
+
701
+ # ---- context + execution --------------------------------------------------------------
702
+
703
+ def load_context(self, path: str, index: int | None = None, is_json: bool = False) -> int:
704
+ """Load the packed world into the single REPL variable `context`.
705
+
706
+ `index` is accepted for protocol compatibility but ignored — there is only
707
+ one context slot. Sources are merged on the host (or via add_context).
708
+ """
709
+ with open(path, "r") as f:
710
+ payload = json.load(f) if is_json else f.read()
711
+ self._context_payload = payload
712
+ self.ns["context"] = payload
713
+ # Drop legacy multi-slot names if present.
714
+ for k in list(self.ns.keys()):
715
+ if k != "context" and _CONTEXT_NAME.match(k):
716
+ del self.ns[k]
717
+ return 0
718
+
719
+ @contextmanager
720
+ def _capture(self):
721
+ out, err = io.StringIO(), io.StringIO()
722
+ old_out, old_err = sys.stdout, sys.stderr
723
+ sys.stdout, sys.stderr = out, err
724
+ try:
725
+ yield out, err
726
+ finally:
727
+ sys.stdout, sys.stderr = old_out, old_err
728
+
729
+ def _exec(self, code: str, ns: dict[str, Any]) -> None:
730
+ t = self.exec_timeout_s
731
+ if t <= 0 or not hasattr(signal, "SIGALRM"):
732
+ exec(compile(code, "<repl>", "exec"), ns, ns) # noqa: S102
733
+ return
734
+
735
+ def _alarm(signum, frame): # noqa: ARG001
736
+ raise TimeoutError(f"```repl``` block exceeded {t:g}s timeout")
737
+
738
+ old = signal.signal(signal.SIGALRM, _alarm)
739
+ signal.setitimer(signal.ITIMER_REAL, t)
740
+ try:
741
+ exec(compile(code, "<repl>", "exec"), ns, ns) # noqa: S102
742
+ finally:
743
+ signal.setitimer(signal.ITIMER_REAL, 0)
744
+ signal.signal(signal.SIGALRM, old)
745
+
746
+ def _nudge_lines(self) -> list[str]:
747
+ """One-time hint for newly created huge raw-text variables (single line).
748
+
749
+ Collapses to one line so it survives headless stdout elision (head 200 + tail 200).
750
+ """
751
+ names: list[str] = []
752
+ for k in self._user_var_names():
753
+ v = self.ns.get(k)
754
+ if isinstance(v, (str, bytes)) and len(v) > _NUDGE_CHARS and k not in self._nudged:
755
+ self._nudged.add(k)
756
+ names.append(f"{k} ({len(v):,} chars)")
757
+ if not names:
758
+ return []
759
+ return [
760
+ f"[rlm] huge raw-text variable(s): {', '.join(names)} — do NOT analyze them yourself; "
761
+ 'delegate with llm_query_chunked(name, "your question") or slice + llm_query_batched.'
762
+ ]
763
+
764
+ def execute(self, code: str) -> dict[str, Any]:
765
+ start = time.perf_counter()
766
+ raised = False
767
+ with self._capture() as (out, err):
768
+ try:
769
+ self._restore_scaffold()
770
+ self._exec(code, self.ns)
771
+ self._restore_scaffold()
772
+ stdout, stderr = out.getvalue(), err.getvalue()
773
+ except BaseException as e: # noqa: BLE001
774
+ raised = True
775
+ self._restore_scaffold()
776
+ stdout = out.getvalue()
777
+ stderr = err.getvalue() + f"\n{type(e).__name__}: {e}\n" + traceback.format_exc()
778
+ final, self._final_answer = self._final_answer, None
779
+ answer = self.ns.get("answer")
780
+ answer_content = answer.get("content", "") if isinstance(answer, dict) else ""
781
+ # ready may have been flipped with empty content before content was assigned later
782
+ # in the same block; the dict's current content is the real submission.
783
+ if final is not None and not final.strip() and str(answer_content).strip():
784
+ final = str(answer_content)
785
+ nudges = self._nudge_lines()
786
+ if nudges:
787
+ parts = [stdout] if stdout else []
788
+ parts.extend(nudges)
789
+ stdout = "\n".join(parts) + "\n"
790
+ return {
791
+ "stdout": stdout,
792
+ "stderr": stderr,
793
+ "final_answer": final,
794
+ "answer_content": str(answer_content),
795
+ "raised": raised,
796
+ "execution_time": time.perf_counter() - start,
797
+ "var_names": self._user_var_names(),
798
+ }
799
+
800
+
801
+ def main() -> None:
802
+ ap = argparse.ArgumentParser()
803
+ ap.add_argument("--depth", type=int, default=int(os.environ.get("RLM_DEPTH", "1")))
804
+ ap.add_argument("--timeout", type=float, default=float(os.environ.get("RLM_EXEC_TIMEOUT_S", "600")))
805
+ ap.add_argument("--await-timeout", type=float,
806
+ default=float(os.environ.get("RLM_AWAIT_TIMEOUT_S", "600")))
807
+ ap.add_argument("--max-prompt-chars", type=int,
808
+ default=int(os.environ.get("RLM_MAX_PROMPT_CHARS", "400000")))
809
+ args = ap.parse_args()
810
+
811
+ worker = Worker(depth=args.depth, exec_timeout_s=args.timeout,
812
+ max_prompt_chars=args.max_prompt_chars,
813
+ await_timeout_s=args.await_timeout)
814
+ _send({"id": "_init", "ok": True})
815
+
816
+ while True:
817
+ # Requests that arrived mid-exec were parked by _pump; replay them before reading.
818
+ req = worker.take_deferred()
819
+ if req is None:
820
+ line = _REAL_STDIN.readline()
821
+ if not line:
822
+ return
823
+ raw = line.strip()
824
+ if not raw:
825
+ continue
826
+ try:
827
+ req = json.loads(raw)
828
+ except json.JSONDecodeError as e:
829
+ _send({"id": "?", "ok": False, "error": f"bad json: {e}"})
830
+ continue
831
+ # A task spawned in an earlier exec settling while the worker is idle. Park it for
832
+ # a later rlm_await; without this it would fall through to "unknown type" and the
833
+ # result would be lost.
834
+ if worker.park_reply(req):
835
+ continue
836
+ if not isinstance(req, dict):
837
+ _send({"id": "?", "ok": False, "error": f"expected an object, got {type(req).__name__}"})
838
+ continue
839
+ rid, kind = req.get("id", "?"), req.get("type")
840
+ try:
841
+ if kind == "exec":
842
+ _send({"id": rid, "ok": True, **worker.execute(req.get("code", ""))})
843
+ elif kind == "load_context":
844
+ idx = worker.load_context(req.get("path"), req.get("index"), req.get("json"))
845
+ _send({"id": rid, "ok": True, "index": idx})
846
+ elif kind == "shutdown":
847
+ _send({"id": rid, "ok": True})
848
+ return
849
+ else:
850
+ _send({"id": rid, "ok": False, "error": f"unknown type: {kind!r}"})
851
+ except BaseException as e: # noqa: BLE001
852
+ _send({"id": rid, "ok": False, "error": f"{type(e).__name__}: {e}\n{traceback.format_exc()}"})
853
+
854
+
855
+ if __name__ == "__main__":
856
+ main()