pi-sleep-agent 0.8.4 → 0.8.6
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/README.md +11 -1
- package/package.json +1 -1
- package/sleepkit/cli.py +87 -0
- package/sleepkit/llm.py +210 -1
- package/sleepkit/store.py +48 -2
package/README.md
CHANGED
|
@@ -319,8 +319,17 @@ Run the two dream components separately when you want more control:
|
|
|
319
319
|
| `./sleep.py replay --run --limit 3` | Compare selected tasks with memory off and on |
|
|
320
320
|
| `./sleep.py mine --dry-run` | Find preferences repeated across sessions |
|
|
321
321
|
| `./sleep.py nightly --dry-run` | Preview the unattended nightly workflow |
|
|
322
|
-
| `./sleep.py doctor` | Find duplicate or overlapping memory records, flag contradicting candidates (same subject, one side carries a correction marker), flag provisional candidates not rediscovered for 4+ weeks, and report records parked in quarantine awaiting a human (report only
|
|
322
|
+
| `./sleep.py doctor` | Find duplicate or overlapping memory records, flag contradicting candidates (same subject, one side carries a correction marker) and print the `supersede <older> <newer>` command to run, flag provisional candidates not rediscovered for 4+ weeks, and report records parked in quarantine awaiting a human (report only: it never supersedes, drops, merges or un-parks anything itself) |
|
|
323
323
|
| `./sleep.py doctor --stale <value>` | Show which approved records still hold a stale value (e.g. a changed URL) |
|
|
324
|
+
| `./sleep.py doctor --contradictions` | Ask a model to adjudicate shortlisted pairs of provisional records for conflicts (`--budget`, default $0.25); report-only, and each finding carries the `supersede <older> <newer>` command to run |
|
|
325
|
+
|
|
326
|
+
The headless model call picks its transport by what exists on the machine, in this order:
|
|
327
|
+
the host agent's own `omo -p` (used when an `omo` binary is on PATH), then `claude
|
|
328
|
+
--bare --print`, then a direct HTTPS call to the endpoint in `~/.sleep/env` (needs both
|
|
329
|
+
`ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN`). Force one with
|
|
330
|
+
`SLEEP_LLM_TRANSPORT=omo|claude|http`. A transport that is not usable on this machine
|
|
331
|
+
raises instead of silently falling back, and omo is never handed the gateway's model
|
|
332
|
+
name: it routes through its own config, so only `SLEEP_MODEL` reaches it.
|
|
324
333
|
| `./sleep.py supersede <old> <new>` | Mark `<old>` invalid as of now and `<new>` valid as of now (`valid_until` / `valid_from`), so the window a memory was true is readable from the files |
|
|
325
334
|
| `./sleep.py inject --project "$PWD"` | Print provisional context for the current project, newest first, each line dated |
|
|
326
335
|
| `./sleep.py inject --project "$PWD" --query "..."` | Same, but rank records by overlap with the live request so the most relevant survive `--max` |
|
|
@@ -445,5 +454,6 @@ Run `./sleep.py show <id>` and check its `cwd`. Mixed-project batches are partit
|
|
|
445
454
|
|
|
446
455
|
- [Sleep: the reviewable-memory extension for coding agents](https://aydinnyunus.github.io/2026/11/01/sleep-agent-memory-extension/) (blog)
|
|
447
456
|
- [Measured evidence and validation history](docs/EVIDENCE.md)
|
|
457
|
+
- [Agent-memory landscape: what other tools do that sleep does not](docs/MEMORY-TOOLS-COMPARISON.md)
|
|
448
458
|
- [Sleep Framework analysis](sleep-framework.md)
|
|
449
459
|
- [Shared `/sleep` skill](shared-skill/sleep/SKILL.md)
|
package/package.json
CHANGED
package/sleepkit/cli.py
CHANGED
|
@@ -190,8 +190,90 @@ def cmd_prune(a) -> int:
|
|
|
190
190
|
return 0
|
|
191
191
|
|
|
192
192
|
|
|
193
|
+
def _doctor_shortlist() -> list:
|
|
194
|
+
"""(id, body, ts) for every provisional record, the input to candidate_pairs."""
|
|
195
|
+
out = []
|
|
196
|
+
for c in store.list_candidates(status="provisional", with_body=True):
|
|
197
|
+
out.append((c["id"], c.get("_body", "") or "", str(c.get("ts", ""))))
|
|
198
|
+
return out
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _llm_contradictions(pairs: list, budget: float, model: str | None) -> list:
|
|
202
|
+
"""Ask the model to adjudicate shortlisted pairs. Report-only: returns findings,
|
|
203
|
+
changes nothing. A failed or unparseable call yields [] so doctor still reports the
|
|
204
|
+
rest of its scan instead of dying on a model problem."""
|
|
205
|
+
if not pairs:
|
|
206
|
+
return []
|
|
207
|
+
# get_candidate returns (meta, body): the text lives in the SECOND element, never
|
|
208
|
+
# under meta["_body"] (that key only exists on the list_candidates path). Reading the
|
|
209
|
+
# wrong one sent the model three pairs of empty bodies, and it answered, correctly,
|
|
210
|
+
# that there was nothing to compare - a silently useless call, not a crash.
|
|
211
|
+
seen = {}
|
|
212
|
+
for cid in {c for pair in pairs for c in pair}:
|
|
213
|
+
got = store.get_candidate(cid)
|
|
214
|
+
seen[cid] = (got[0], got[1]) if got else ({}, "")
|
|
215
|
+
lines = []
|
|
216
|
+
for i, (older, newer) in enumerate(pairs, 1):
|
|
217
|
+
lines.append("Pair %d:" % i)
|
|
218
|
+
for cid in (older, newer):
|
|
219
|
+
meta, body = seen.get(cid, ({}, ""))
|
|
220
|
+
lines.append(" id=%s ts=%s body=%s" % (cid, meta.get("ts", "?"),
|
|
221
|
+
(body or "").replace("\n", " ").strip()))
|
|
222
|
+
user = ("Unreviewed provisional memory records, grouped into candidate pairs.\n"
|
|
223
|
+
"Adjudicate each pair per your instructions.\n\n" + "\n".join(lines))
|
|
224
|
+
pf = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "prompts",
|
|
225
|
+
"contradiction-check.md")
|
|
226
|
+
# The subprocess seam: tests replace llm.run with a fake so the adjudication path is
|
|
227
|
+
# exercisable with no model, no network and no budget (the real binary refuses to run
|
|
228
|
+
# nested inside another agent, which makes an in-session live call impossible).
|
|
229
|
+
res = llm.run(system_prompt_file=os.path.abspath(pf), user_prompt=user,
|
|
230
|
+
add_dirs=[], allowed_tools=llm.READONLY_TOOLS, model=model,
|
|
231
|
+
budget_usd=budget, output_format="json")
|
|
232
|
+
# The CLI's json output has shipped both as one object and as an array of turn
|
|
233
|
+
# objects (see llm.parse_json_output), and the model's answer is a JSON string it
|
|
234
|
+
# was asked to print. Accept every one of those shapes instead of assuming a dict.
|
|
235
|
+
raw = res.get("json")
|
|
236
|
+
if isinstance(raw, list):
|
|
237
|
+
for item in reversed(raw):
|
|
238
|
+
if isinstance(item, dict) and isinstance(item.get("result"), str):
|
|
239
|
+
raw = item
|
|
240
|
+
break
|
|
241
|
+
text = ""
|
|
242
|
+
if isinstance(raw, dict):
|
|
243
|
+
text = raw.get("result") or raw.get("text") or ""
|
|
244
|
+
if not isinstance(text, str) or not text.strip():
|
|
245
|
+
text = res.get("stdout") or ""
|
|
246
|
+
doc = None
|
|
247
|
+
for chunk in (text, res.get("stdout") or ""):
|
|
248
|
+
if not isinstance(chunk, str) or "{" not in chunk or "}" not in chunk:
|
|
249
|
+
continue
|
|
250
|
+
try:
|
|
251
|
+
doc = json.loads(chunk[chunk.index("{"):chunk.rindex("}") + 1])
|
|
252
|
+
break
|
|
253
|
+
except Exception:
|
|
254
|
+
doc = None
|
|
255
|
+
if not isinstance(doc, dict):
|
|
256
|
+
return []
|
|
257
|
+
found = []
|
|
258
|
+
for item in doc.get("pairs") or []:
|
|
259
|
+
if not isinstance(item, dict) or not item.get("contradiction"):
|
|
260
|
+
continue
|
|
261
|
+
try:
|
|
262
|
+
older, newer = pairs[int(item["pair"]) - 1]
|
|
263
|
+
except (KeyError, IndexError, ValueError, TypeError):
|
|
264
|
+
continue
|
|
265
|
+
found.append({"issue": "contradicting-candidates",
|
|
266
|
+
"pair": [older, newer], "older": older, "newer": newer,
|
|
267
|
+
"source": "model", "reason": str(item.get("reason", ""))[:200],
|
|
268
|
+
"suggest": "sleep.py supersede %s %s" % (older, newer)})
|
|
269
|
+
return found
|
|
270
|
+
|
|
271
|
+
|
|
193
272
|
def cmd_doctor(a) -> int:
|
|
194
273
|
issues = store.doctor(needle=a.stale)
|
|
274
|
+
if getattr(a, "contradictions", False):
|
|
275
|
+
pairs = store.candidate_pairs(_doctor_shortlist())
|
|
276
|
+
issues += _llm_contradictions(pairs, getattr(a, "budget", 0.25), getattr(a, "model", None))
|
|
195
277
|
if a.json:
|
|
196
278
|
_p(json.dumps(issues, indent=2, sort_keys=True, default=str))
|
|
197
279
|
elif not issues:
|
|
@@ -444,6 +526,11 @@ def main(argv=None) -> int:
|
|
|
444
526
|
dc.add_argument("--stale", default=None,
|
|
445
527
|
help="value (e.g. a URL) to scan approved T2 memory for; "
|
|
446
528
|
"reports which permanent records still hold it")
|
|
529
|
+
dc.add_argument("--contradictions", action="store_true",
|
|
530
|
+
help="also ask a model to adjudicate shortlisted record pairs for "
|
|
531
|
+
"conflicts (costs budget; report-only, supersedes nothing)")
|
|
532
|
+
dc.add_argument("--budget", type=float, default=0.25,
|
|
533
|
+
help="max USD for --contradictions (default 0.25)")
|
|
447
534
|
dc.set_defaults(fn=cmd_doctor)
|
|
448
535
|
|
|
449
536
|
rp = sub.add_parser("replay", help="layer 3: A/B measure provisional memory, report-only")
|
package/sleepkit/llm.py
CHANGED
|
@@ -41,6 +41,88 @@ def binary() -> str:
|
|
|
41
41
|
raise FileNotFoundError("claude binary not found; set CLAUDE_BIN")
|
|
42
42
|
|
|
43
43
|
|
|
44
|
+
# ---- transport selection ---------------------------------------------------------
|
|
45
|
+
# Three ways to reach a model, tried in a fixed order. Each one is only *eligible* when
|
|
46
|
+
# its binary and its configuration actually exist; the first eligible one wins, and
|
|
47
|
+
# SLEEP_LLM_TRANSPORT forces one for an operator who knows better.
|
|
48
|
+
#
|
|
49
|
+
# omo - the host agent's own headless mode (`omo -p`). Highest priority: it already
|
|
50
|
+
# carries this machine's routed credentials, and it works in places where a
|
|
51
|
+
# nested `claude` is refused outright (measured: `claude --version` dies with
|
|
52
|
+
# SIGKILL under the host, `omo -p 'reply with exactly: OK'` returns OK).
|
|
53
|
+
# claude - the historical path (`claude --bare --print`), kept because it is the one
|
|
54
|
+
# proven by ~/.claude-work/hooks/self-improve.sh and by every prior release.
|
|
55
|
+
# http - a direct POST to the Anthropic-shaped endpoint from ~/.sleep/env. It needs
|
|
56
|
+
# only ANTHROPIC_BASE_URL + ANTHROPIC_AUTH_TOKEN, so it survives a machine
|
|
57
|
+
# where no agent CLI is installed or allowed to nest, and it returns real
|
|
58
|
+
# token counts, which the CLI paths cannot.
|
|
59
|
+
TRANSPORTS = ("omo", "claude", "http")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _omo_binary() -> str | None:
|
|
63
|
+
for cand in (os.environ.get("OMO_BIN"), shutil.which("omo"),
|
|
64
|
+
os.path.expanduser("~/.local/bin/omo")):
|
|
65
|
+
if cand and os.path.isfile(cand) and os.access(cand, os.X_OK):
|
|
66
|
+
return cand
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _env_file_values() -> dict:
|
|
71
|
+
"""The ~/.sleep/env values, or {} when the file is absent or unreadable."""
|
|
72
|
+
try:
|
|
73
|
+
return env_overrides(paths.env_file())
|
|
74
|
+
except (OSError, ValueError):
|
|
75
|
+
return {}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _http_config() -> dict | None:
|
|
79
|
+
"""Base URL + token + model for the HTTP transport, or None when unusable.
|
|
80
|
+
|
|
81
|
+
The process environment is consulted first and *alone* is enough when it names both
|
|
82
|
+
values, so the transport can be configured without writing ~/.sleep/env (tests, CI, a
|
|
83
|
+
one-off shell). The env file is only merged for keys the process did not already set,
|
|
84
|
+
which is the same precedence auth_env() gives every other variable.
|
|
85
|
+
"""
|
|
86
|
+
env = auth_env()
|
|
87
|
+
base = (env.get("ANTHROPIC_BASE_URL") or "").strip()
|
|
88
|
+
token = (env.get("ANTHROPIC_AUTH_TOKEN") or "").strip()
|
|
89
|
+
if not base or not token:
|
|
90
|
+
return None
|
|
91
|
+
return {"base_url": base.rstrip("/"), "token": token,
|
|
92
|
+
"model": env.get("SLEEP_MODEL") or env.get("ANTHROPIC_MODEL") or FALLBACK_MODEL}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def resolve_transport(model_transport: str | None = None) -> str:
|
|
96
|
+
"""Pick the transport: explicit argument > SLEEP_LLM_TRANSPORT > first eligible.
|
|
97
|
+
|
|
98
|
+
Eligibility is a fact about this machine, read at call time: an omo binary on disk,
|
|
99
|
+
a claude binary on disk, or an env file that names an endpoint and a token. A
|
|
100
|
+
requested transport that is not eligible raises rather than silently falling back,
|
|
101
|
+
because an operator who pinned one wants to hear that it is not usable here.
|
|
102
|
+
"""
|
|
103
|
+
forced = (model_transport or os.environ.get("SLEEP_LLM_TRANSPORT") or "").strip().lower()
|
|
104
|
+
if forced:
|
|
105
|
+
if forced not in TRANSPORTS:
|
|
106
|
+
raise ValueError("unknown SLEEP_LLM_TRANSPORT %r (one of %s)"
|
|
107
|
+
% (forced, ", ".join(TRANSPORTS)))
|
|
108
|
+
return forced
|
|
109
|
+
# CLAUDE_BIN is a *decision*, not a hint: an operator or a test that points at a
|
|
110
|
+
# specific claude binary is saying which agent binary to run. Auto-detecting omo over
|
|
111
|
+
# that would ignore the choice (and silently turn every stubbed test into a live omo
|
|
112
|
+
# call). So an explicitly named claude binary outranks an auto-discovered omo.
|
|
113
|
+
claude_bin = os.environ.get("CLAUDE_BIN")
|
|
114
|
+
if claude_bin and os.path.isfile(claude_bin) and os.access(claude_bin, os.X_OK):
|
|
115
|
+
return "claude"
|
|
116
|
+
if _omo_binary():
|
|
117
|
+
return "omo"
|
|
118
|
+
for cand in (shutil.which("claude"), os.path.expanduser("~/.local/bin/claude")):
|
|
119
|
+
if cand and os.path.isfile(cand) and os.access(cand, os.X_OK):
|
|
120
|
+
return "claude"
|
|
121
|
+
if _http_config():
|
|
122
|
+
return "http"
|
|
123
|
+
return "claude" # nothing is eligible; let the claude path raise its own loud error
|
|
124
|
+
|
|
125
|
+
|
|
44
126
|
_KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
45
127
|
|
|
46
128
|
|
|
@@ -129,11 +211,138 @@ def parse_json_output(text: str):
|
|
|
129
211
|
return last
|
|
130
212
|
|
|
131
213
|
|
|
214
|
+
def omo_model(explicit: str | None = None) -> str | None:
|
|
215
|
+
"""The --model value omo should be given, or None to let omo pick its own.
|
|
216
|
+
|
|
217
|
+
omo routes through its own ~/.omo/agent configuration and rejects a model name that
|
|
218
|
+
belongs to a different vocabulary (measured: it exits 1 with no output when handed
|
|
219
|
+
the gateway's `deepseek/deepseek-v4.1-flash` from ~/.sleep/env, while the same call
|
|
220
|
+
with its own default answers). ANTHROPIC_MODEL therefore means nothing here; only an
|
|
221
|
+
operator's explicit SLEEP_MODEL (or the call's own argument) is passed through.
|
|
222
|
+
"""
|
|
223
|
+
if explicit:
|
|
224
|
+
return explicit
|
|
225
|
+
return os.environ.get("SLEEP_MODEL") or None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _run_omo(system_prompt_file: str, user_prompt: str, model: str | None,
|
|
229
|
+
timeout_s: int) -> dict:
|
|
230
|
+
"""`omo -p` with the system prompt inlined.
|
|
231
|
+
|
|
232
|
+
omo has no --append-system-prompt-file, so the file's text is prepended to the user
|
|
233
|
+
prompt as a delimited block. That keeps one call shape and no temp files, and the
|
|
234
|
+
delimiter makes the boundary explicit to the model instead of blurring two prompts
|
|
235
|
+
together.
|
|
236
|
+
"""
|
|
237
|
+
exe = _omo_binary()
|
|
238
|
+
if not exe:
|
|
239
|
+
return {"argv": [], "exit": 127, "stdout": "", "stderr": "omo binary not found", "json": None}
|
|
240
|
+
try:
|
|
241
|
+
system = open(system_prompt_file, encoding="utf-8").read()
|
|
242
|
+
except OSError as exc:
|
|
243
|
+
return {"argv": [], "exit": 2, "stdout": "", "stderr": "system prompt unreadable: %s" % exc, "json": None}
|
|
244
|
+
prompt = "<instructions>\n%s\n</instructions>\n\n%s" % (system.strip(), user_prompt)
|
|
245
|
+
# Measured argv shape on this machine: the prompt is positional and the flags may
|
|
246
|
+
# precede it. omo also warns on stderr about stdin, which is harmless here.
|
|
247
|
+
argv = [exe, "-p"]
|
|
248
|
+
if model:
|
|
249
|
+
argv += ["--model", model]
|
|
250
|
+
argv.append(prompt)
|
|
251
|
+
root = os.path.dirname(os.path.dirname(os.path.abspath(paths.__file__)))
|
|
252
|
+
env = auth_env()
|
|
253
|
+
env.setdefault("SLEEP_LLM_INVOKED", "1") # a nested call must not re-trigger sleep
|
|
254
|
+
try:
|
|
255
|
+
proc = subprocess.run(argv, capture_output=True, text=True, timeout=timeout_s,
|
|
256
|
+
env=env, cwd=root)
|
|
257
|
+
out, err, code = proc.stdout, proc.stderr, proc.returncode
|
|
258
|
+
except (subprocess.TimeoutExpired, OSError) as exc:
|
|
259
|
+
out, err, code = "", str(exc)[:400], 124
|
|
260
|
+
return {"argv": argv[:3], "exit": code, "stdout": out, "stderr": err, "json": None}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _run_http(system_prompt_file: str, user_prompt: str, model: str,
|
|
264
|
+
budget_usd: float, timeout_s: int,
|
|
265
|
+
output_format: str | None) -> dict:
|
|
266
|
+
"""Direct POST to the configured endpoint, with the system prompt in `system`.
|
|
267
|
+
|
|
268
|
+
Adds two things the CLI paths cannot: the response's token counts (so budget_usd is
|
|
269
|
+
checked against real usage) and a transport that needs no agent binary at all. Only
|
|
270
|
+
stdlib is used, so this stays a zero-dependency path.
|
|
271
|
+
"""
|
|
272
|
+
import urllib.error
|
|
273
|
+
import urllib.request
|
|
274
|
+
|
|
275
|
+
cfg = _http_config()
|
|
276
|
+
if not cfg:
|
|
277
|
+
return {"argv": [], "exit": 2, "stdout": "", "stderr": "no ANTHROPIC_BASE_URL/ANTHROPIC_AUTH_TOKEN configured", "json": None}
|
|
278
|
+
try:
|
|
279
|
+
system = open(system_prompt_file, encoding="utf-8").read()
|
|
280
|
+
except OSError as exc:
|
|
281
|
+
return {"argv": [], "exit": 2, "stdout": "", "stderr": "system prompt unreadable: %s" % exc, "json": None}
|
|
282
|
+
body = json.dumps({"model": model, "max_tokens": 2048, "system": system,
|
|
283
|
+
"messages": [{"role": "user", "content": user_prompt}]}).encode("utf-8")
|
|
284
|
+
req = urllib.request.Request(cfg["base_url"] + "/v1/messages", data=body,
|
|
285
|
+
headers={"content-type": "application/json",
|
|
286
|
+
"x-api-key": cfg["token"],
|
|
287
|
+
"anthropic-version": "2023-06-01"})
|
|
288
|
+
url = cfg["base_url"] + "/v1/messages"
|
|
289
|
+
try:
|
|
290
|
+
with urllib.request.urlopen(req, timeout=timeout_s) as resp:
|
|
291
|
+
raw = resp.read().decode("utf-8", "replace")
|
|
292
|
+
code = resp.status
|
|
293
|
+
except urllib.error.HTTPError as exc:
|
|
294
|
+
return {"argv": [url], "exit": exc.code, "stdout": exc.read().decode("utf-8", "replace")[:4000],
|
|
295
|
+
"stderr": "HTTP %s" % exc.code, "json": None}
|
|
296
|
+
except Exception as exc:
|
|
297
|
+
return {"argv": [url], "exit": 1, "stdout": "", "stderr": str(exc)[:400], "json": None}
|
|
298
|
+
|
|
299
|
+
# Anthropic shape: {"content":[{"type":"text","text":...}],"usage":{...}}. The
|
|
300
|
+
# gateway in front of this endpoint answers in the OpenAI shape as well, so both
|
|
301
|
+
# text carriers are read instead of assuming one.
|
|
302
|
+
doc, text, usage = None, "", {}
|
|
303
|
+
try:
|
|
304
|
+
doc = json.loads(raw)
|
|
305
|
+
except ValueError:
|
|
306
|
+
doc = None
|
|
307
|
+
if isinstance(doc, dict):
|
|
308
|
+
usage = doc.get("usage") or {}
|
|
309
|
+
for part in doc.get("content") or []:
|
|
310
|
+
if isinstance(part, dict) and part.get("type") == "text":
|
|
311
|
+
text += part.get("text") or ""
|
|
312
|
+
if not text:
|
|
313
|
+
for choice in doc.get("choices") or []:
|
|
314
|
+
msg = (choice or {}).get("message") or {}
|
|
315
|
+
if isinstance(msg, dict):
|
|
316
|
+
text += msg.get("content") or ""
|
|
317
|
+
out = text or raw
|
|
318
|
+
res = {"argv": [url], "exit": code, "stdout": out, "stderr": "", "json": None,
|
|
319
|
+
"usage": usage}
|
|
320
|
+
if output_format == "json":
|
|
321
|
+
# Callers that asked for JSON expect the same wrapper the CLI path produces, so
|
|
322
|
+
# the model's text is nested exactly where parse-json callers already look.
|
|
323
|
+
res["json"] = {"result": text}
|
|
324
|
+
return res
|
|
325
|
+
|
|
326
|
+
|
|
132
327
|
def run(system_prompt_file: str, user_prompt: str, add_dirs: list[str],
|
|
133
328
|
allowed_tools: str = WRITE_TOOLS, model: str | None = None,
|
|
134
329
|
budget_usd: float = 1.0, timeout_s: int = 900,
|
|
135
|
-
output_format: str | None = None, extra: list[str] | None = None
|
|
330
|
+
output_format: str | None = None, extra: list[str] | None = None,
|
|
331
|
+
model_transport: str | None = None) -> dict:
|
|
332
|
+
omo_model_arg = model # the caller's own choice, before gateway naming
|
|
136
333
|
model = resolve_model(model)
|
|
334
|
+
transport = resolve_transport(model_transport)
|
|
335
|
+
if transport == "omo":
|
|
336
|
+
# The resolved model is the gateway's name, which omo does not accept; only an
|
|
337
|
+
# explicit choice reaches it (see omo_model).
|
|
338
|
+
res = _run_omo(system_prompt_file, user_prompt,
|
|
339
|
+
omo_model(omo_model_arg), timeout_s)
|
|
340
|
+
if output_format == "json":
|
|
341
|
+
res["json"] = {"result": res.get("stdout") or ""}
|
|
342
|
+
return res
|
|
343
|
+
if transport == "http":
|
|
344
|
+
return _run_http(system_prompt_file, user_prompt, model, budget_usd,
|
|
345
|
+
timeout_s, output_format)
|
|
137
346
|
exe = ["claude"]
|
|
138
347
|
try:
|
|
139
348
|
exe = [binary()]
|
package/sleepkit/store.py
CHANGED
|
@@ -11,6 +11,7 @@ Policy (the part that keeps this from becoming a self-poisoning loop):
|
|
|
11
11
|
"""
|
|
12
12
|
from __future__ import annotations
|
|
13
13
|
|
|
14
|
+
import itertools
|
|
14
15
|
import json
|
|
15
16
|
import os
|
|
16
17
|
import re
|
|
@@ -600,6 +601,41 @@ def prune_buffer(older_than_hours: float = 0.0, session: str | None = None) -> d
|
|
|
600
601
|
return {"moved": moved, "remaining": buffer_counts()}
|
|
601
602
|
|
|
602
603
|
|
|
604
|
+
# A cheap pre-filter for the LLM adjudicator. Token Jaccard is a poor *decider* on
|
|
605
|
+
# short observations (measured: no real pair in a live 11-record pool cleared 0.5),
|
|
606
|
+
# but it is a fine *shortlist*: pairs that share at least a handful of content words
|
|
607
|
+
# are the only ones worth spending a model call on. The model decides; this decides
|
|
608
|
+
# what the model is asked about, so the cost stays bounded by the record count.
|
|
609
|
+
CONTRADICTION_SHORTLIST = 0.05
|
|
610
|
+
CONTRADICTION_MAX_PAIRS = 12
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def candidate_pairs(recs: list, limit: int = CONTRADICTION_MAX_PAIRS) -> list:
|
|
614
|
+
"""Pairs of provisional records worth asking a model about, newest-signal first.
|
|
615
|
+
|
|
616
|
+
recs: [(id, body, ts)] in any order. Returns [(older_id, newer_id, ts_map)] with
|
|
617
|
+
at most `limit` pairs, ordered by shared-wording score so a bounded number of
|
|
618
|
+
model calls covers the most likely conflicts first.
|
|
619
|
+
"""
|
|
620
|
+
scored = []
|
|
621
|
+
for (ia, ba, ta), (ib, bb, tb) in itertools.combinations(recs, 2):
|
|
622
|
+
s = similarity(ba, bb)
|
|
623
|
+
if s >= CONTRADICTION_SHORTLIST:
|
|
624
|
+
older, newer = (ia, ib) if (ta or "") <= (tb or "") else (ib, ia)
|
|
625
|
+
scored.append((s, older, newer))
|
|
626
|
+
scored.sort(reverse=True)
|
|
627
|
+
return [(o, n) for _s, o, n in scored[:limit]]
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _older_newer(a: str, b: str, ts_by_id: dict) -> tuple[str, str]:
|
|
631
|
+
"""Order two candidate ids by capture time, oldest first. ts is ISO-ish and sorts
|
|
632
|
+
lexicographically; a missing ts falls back to the id so a pair is always returned."""
|
|
633
|
+
ta, tb = ts_by_id.get(a, ""), ts_by_id.get(b, "")
|
|
634
|
+
if ta and tb and ta != tb:
|
|
635
|
+
return (a, b) if ta < tb else (b, a)
|
|
636
|
+
return (a, b) if a <= b else (b, a)
|
|
637
|
+
|
|
638
|
+
|
|
603
639
|
def doctor(memory_dir: str | None = None, targets: list[str] | None = None,
|
|
604
640
|
needle: str | None = None) -> list[dict]:
|
|
605
641
|
"""Read-only hygiene report.
|
|
@@ -642,7 +678,9 @@ def doctor(memory_dir: str | None = None, targets: list[str] | None = None,
|
|
|
642
678
|
if nlow in text.lower():
|
|
643
679
|
out.append({"issue": "stale-value-in-memory", "file": p,
|
|
644
680
|
"value": needle})
|
|
645
|
-
|
|
681
|
+
pool_records = list_candidates(with_body=True)
|
|
682
|
+
pool = [(c["id"], c.get("_body", "")) for c in pool_records]
|
|
683
|
+
pool_ts = {c["id"]: str(c.get("ts", "")) for c in pool_records}
|
|
646
684
|
for i in range(len(pool)):
|
|
647
685
|
for j in range(i + 1, len(pool)):
|
|
648
686
|
sim = similarity(pool[i][1], pool[j][1])
|
|
@@ -656,8 +694,16 @@ def doctor(memory_dir: str | None = None, targets: list[str] | None = None,
|
|
|
656
694
|
elif sim >= CONTRADICTION_OVERLAP:
|
|
657
695
|
mi, mj = bool(_CORRECTION.search(pool[i][1])), bool(_CORRECTION.search(pool[j][1]))
|
|
658
696
|
if mi != mj:
|
|
697
|
+
# Name the older/newer side so a person does not diff two timestamps by
|
|
698
|
+
# eye: the older record is the claim, the newer one is the correction.
|
|
699
|
+
# The suggestion is a command to RUN, never one this code runs -
|
|
700
|
+
# superseding on a keyword match could kill a true memory, so the gate
|
|
701
|
+
# stays human.
|
|
702
|
+
older, newer = _older_newer(pool[i][0], pool[j][0], pool_ts)
|
|
659
703
|
out.append({"issue": "contradicting-candidates",
|
|
660
|
-
"pair": [pool[i][0], pool[j][0]], "similarity": round(sim, 2)
|
|
704
|
+
"pair": [pool[i][0], pool[j][0]], "similarity": round(sim, 2),
|
|
705
|
+
"older": older, "newer": newer,
|
|
706
|
+
"suggest": "sleep.py supersede %s %s" % (older, newer)})
|
|
661
707
|
cutoff_hours = STALE_CANDIDATE_WEEKS * 7 * 24
|
|
662
708
|
for c in list_candidates():
|
|
663
709
|
if c.get("status") != "provisional":
|