okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
20.2 KiB353 linesraw
1"""`strata connect <harness>`: the setup for an app that talks to a running Strata server.
2
3Every entry below comes from a config that was tested for real against a Strata server at 32K context (one simple prompt with the
4answer text checked and one tool call with its arguments checked, plus streaming, thinking and compaction at about 15K): the files in
5phaseA-tests/split/harness-configs/<harness>.md, one per app, with the versions tested. The generators here fill in the real address,
6key, model name and context of the running server; the "limits" are those files' gotchas in plain words.
7
8`tested` is the app version the config was tested with. A value of None would mean "not tested"; all eight entries are tested.
9"""
10
11from __future__ import annotations
12
13import json
14import os
15import shutil
16import time
17from dataclasses import dataclass, field
18from pathlib import Path
19from typing import Callable
20
21PLACEHOLDER_KEY = "strata-local"      # the tested configs' placeholder when the server has no key (not a secret)
22OUTPUT_CAP = 4096                     # the output cap every tested config used
23TESTED_CONTEXT = 32768                # the window every config below was tested on
24COMPACT_AT = 15000                    # and where those tested configs make the app compact its conversation
25
26
27@dataclass
28class Target:
29    """The running server, as a config needs to know it."""
30
31    url: str                           # server root, no /v1
32    key: str                           # real key, or the placeholder
33    model: str
34    context: int = 32768
35
36    @property
37    def base(self) -> str:
38        return self.url.rstrip("/") + "/v1"
39
40    @property
41    def input_limit(self) -> int:
42        return max(1024, self.context - OUTPUT_CAP)
43
44    @property
45    def output_cap(self) -> int:
46        """The longest reply a config lets the app ask for: the tested 4,096 up to the tested window, then an eighth of the window (16,384 at 128K).
47        Thinking counts against it, and an app asks its compaction summary for exactly this much: at 4,096 on a wide window the summary ended at the
48        limit and OpenCode failed the step ("Compaction summary reached the output token limit", #5006); a whole file written in one tool call was
49        cut off the same way (PR #4230). The input limit and the compaction point stay as tested (compaction fires long before the input limit, and the
50        server fits each request's cap to the room its prompt leaves)."""
51        return max(OUTPUT_CAP, self.context // 8)
52
53
54def compact_at(t: Target) -> int:
55    """Where the app should compact its conversation: the share of the input limit the tested configs used, so that the
56    summarising request (which carries the whole conversation) still fits the window.
57
58    A flat 15,000 summarises a wider server every 15,000 tokens - 6% of a 256K window - while the tested configs compact
59    a 32K server at 52% of its input limit. The share is what carries over, not the number: a 32K server keeps exactly
60    the value it was tested at."""
61    tested_limit = TESTED_CONTEXT - OUTPUT_CAP
62    return max(COMPACT_AT, int(t.input_limit * COMPACT_AT / tested_limit))
63
64
65@dataclass
66class FileSpec:
67    path: str                          # may start with ~
68    kind: str                          # json | toml | yaml | text
69    make: Callable[[Target], str]
70    merge: bool = False                # json only: merge into an existing file instead of replacing it
71
72
73@dataclass
74class Harness:
75    id: str
76    title: str
77    speaks: str
78    tested: str = ""                   # "opencode 1.19.3": the version the config was tested with
79    files: list[FileSpec] = field(default_factory=list)
80    env: Callable[[Target], dict[str, str]] | None = None
81    limits: Callable[[Target], list[str]] | None = None
82    run: str = ""                      # one example command
83    install: str = ""
84    built_in: bool = False
85    aliases: tuple[str, ...] = ()
86
87    @property
88    def status(self) -> str:
89        if self.built_in:
90            return "built into the Strata app (tested)"
91        return f"tested ({self.tested})" if self.tested else "not tested yet"
92
93
94def _j(obj) -> str:
95    return json.dumps(obj, indent=2)
96
97
98# ------------------------------------------------------------------------------------------------ the eight
99
100def opencode_file(t: Target) -> str:
101    return _j({"$schema": "https://opencode.ai/config.json", "model": f"strata/{t.model}", "small_model": f"strata/{t.model}",
102               "autoupdate": False,
103               "compaction": {"auto": True, "buffer": max(1024, t.input_limit - compact_at(t))},
104               "share": "disabled",
105               "provider": {"strata": {"npm": "@ai-sdk/openai-compatible", "name": "Strata (local)",
106                                       "options": {"baseURL": t.base, "apiKey": t.key},
107                                       "models": {t.model: {"name": "Qwen3.8-Flash-Next (local)", "tool_call": True, "reasoning": True,
108                                                            "limit": {"context": t.context, "input": t.input_limit, "output": t.output_cap}}}}}})
109
110
111def codex_file(t: Target) -> str:
112    return (f'model = "{t.model}"\nmodel_provider = "strata"\nmodel_context_window = {t.context}\n'
113            f"model_auto_compact_token_limit = {compact_at(t)}\nmodel_reasoning_summary = \"auto\"\napproval_policy = \"never\"\n"
114            'sandbox_mode = "workspace-write"\ncheck_for_update_on_startup = false\n\n[model_providers.strata]\n'
115            f'name = "Strata (local)"\nbase_url = "{t.base}"\nwire_api = "responses"\nenv_key = "STRATA_API_KEY"\n'
116            "stream_idle_timeout_ms = 600000\n")
117
118
119def claude_env(t: Target) -> dict[str, str]:
120    return {"ANTHROPIC_BASE_URL": t.url.rstrip("/"), "ANTHROPIC_AUTH_TOKEN": t.key, "ANTHROPIC_MODEL": t.model,
121            "ANTHROPIC_SMALL_FAST_MODEL": t.model, "ANTHROPIC_DEFAULT_SONNET_MODEL": t.model, "ANTHROPIC_DEFAULT_OPUS_MODEL": t.model,
122            "ANTHROPIC_DEFAULT_HAIKU_MODEL": t.model, "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "DISABLE_AUTOUPDATER": "1",
123            "DISABLE_TELEMETRY": "1", "CLAUDE_CODE_MAX_CONTEXT_TOKENS": str(t.context),
124            "CLAUDE_CODE_MAX_OUTPUT_TOKENS": str(t.output_cap)} | ({"CLAUDE_CODE_SIMPLE": "1"} if t.context <= 40960 else {})
125
126
127def claude_file(t: Target) -> str:
128    return _j({"env": claude_env(t)})
129
130
131def omp_models(t: Target) -> str:
132    return ("providers:\n  strata:\n    baseUrl: " + t.base + "\n    api: openai-completions\n    auth: none\n    compat:\n"
133            "      supportsDeveloperRole: false\n    models:\n      - id: " + t.model + "\n        name: Qwen3.8-Flash-Next (Strata, local)\n"
134            "        reasoning: true\n        input: [text]\n        contextWindow: " + str(t.context) + "\n        maxTokens: " + str(t.output_cap) +
135            "\n        thinking:\n          mode: effort\n          efforts: [minimal, low, medium, high]\n          defaultLevel: medium\n"
136            "        cost: {input: 0, output: 0, cacheRead: 0, cacheWrite: 0}\n")
137
138
139def omp_config(t: Target) -> str:
140    return ("modelRoles:\n  default: strata/" + t.model + "\ndefaultThinkingLevel: medium\ncompaction:\n  enabled: true\n  thresholdTokens: "
141            + str(compact_at(t)) + "\n  keepRecentTokens: 4000\n  methodOrder:\n    - soft\n  idleEnabled: false\nsetupVersion: 2\n")
142
143
144def pi_models(t: Target) -> str:
145    return _j({"providers": {"strata": {"baseUrl": t.base, "api": "openai-completions", "apiKey": t.key,
146                                        "compat": {"supportsDeveloperRole": False, "supportsReasoningEffort": False},
147                                        "models": [{"id": t.model, "name": "Qwen3.8-Flash-Next (Strata, local)", "reasoning": True,
148                                                    "input": ["text"], "contextWindow": t.context, "maxTokens": t.output_cap,
149                                                    "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}}]}}})
150
151
152def pi_settings(t: Target) -> str:
153    return _j({"defaultProvider": "strata", "defaultModel": t.model, "defaultThinkingLevel": "medium",
154               "compaction": {"enabled": True, "reserveTokens": max(1024, t.context - compact_at(t)), "keepRecentTokens": 4000}})
155
156
157def hermes_file(t: Target) -> str:
158    return ("model:\n  default: " + t.model + "\n  provider: lmstudio\n  base_url: " + t.base + "\n  context_length: " + str(t.context) +
159            "\ncompression:\n  enabled: true\n  threshold_tokens: " + str(compact_at(t)) + "\nauxiliary:\n  compression:\n    context_length: 65536\n")
160
161
162def openclaw_file(t: Target) -> str:
163    return _j({"models": {"mode": "merge", "providers": {"strata": {
164        "baseUrl": t.base, "apiKey": t.key, "api": "openai-completions",
165        "models": [{"id": t.model, "name": f"{t.model} (Strata)", "contextWindow": t.context,
166                    "contextTokens": int(t.context * 23192 / 32768), "maxTokens": t.output_cap, "reasoning": True, "input": ["text"],
167                    "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}}]}}},
168        "agents": {"defaults": {"model": {"primary": f"strata/{t.model}"},
169                                "compaction": {"enabled": True, "notifyUser": True, "keepRecentTokens": 4000}}}})
170
171
172def _limits_opencode(t: Target) -> list[str]:
173    return ["The setup needs limit.input (strata connect sets it to %d); without it OpenCode never compacts its conversation." % t.input_limit,
174            "Its first start downloads a plug-in from npm (internet needed once; the first run can take over a minute).",
175            "In a script or over ssh, run it as: opencode run \"...\" < /dev/null (it waits for typing otherwise).",
176            "Its system prompt and tools take about 7.4K tokens of the window."]
177
178
179def _limits_codex(t: Target) -> list[str]:
180    return ["Codex prints \"Model metadata ... not found\" on every start: harmless, it does not know the model.",
181            "It will not send without STRATA_API_KEY set; any text works when the server has no key.",
182            "Where the sandbox cannot start (no bubblewrap), use --dangerously-bypass-approvals-and-sandbox only in a throwaway folder.",
183            "Its system prompt and tools take about 8.6K tokens of the window."]
184
185
186def _limits_claude(t: Target) -> list[str]:
187    out = ["ANTHROPIC_BASE_URL is the server address %s without /v1: Claude Code adds /v1/messages itself (with /v1 in it the requests go to /v1/v1/messages)." % t.url,
188           "Set CLAUDE_CODE_MAX_CONTEXT_TOKENS to the served context (%d here) and CLAUDE_CODE_MAX_OUTPUT_TOKENS=%d: without them Claude Code "
189           "assumes a 100K window and never compacts, or compacts on every turn." % (t.context, t.output_cap),
190           "No Anthropic login or credential is used; the token is only checked by your own server.",
191           "The notice [claude-code:unrecognized_model] on stderr is harmless."]
192    if t.context <= 40960:
193        out.append("Its full prompt is 15.6K tokens (20 tools): with a 32K window use CLAUDE_CODE_SIMPLE=1 (3 tools, 1.25K tokens), as set here.")
194    return out
195
196
197def _limits_omp(t: Target) -> list[str]:
198    return ["Its system prompt and tools take about 7.5K tokens of the window.",
199            "One small title/summary request may come back empty because the model spent its 512 tokens thinking; omp carries on."]
200
201
202def _limits_pi(t: Target) -> list[str]:
203    return ["pi has the smallest prompt of the eight (1.5K tokens): the most room for the conversation.",
204            "It compacts after the turn that crosses the line, so one turn can reach about %dK tokens before it summarises."
205            % round(compact_at(t) / 1000)]
206
207
208def _limits_hermes(t: Target) -> list[str]:
209    out = ["Hermes refuses a window under 64,000 tokens unless the provider is lmstudio with an explicit context_length: the config uses "
210           "that, and auxiliary.compression.context_length 65536 for its summariser (the same floor).",
211           "Its system prompt and 20 tools take about 12.9K tokens (40% of a 32K window): about 19K is left for the conversation.",
212           "Its own 64K minimum floors the compaction threshold, so it compacts later than the value above (around 20K on a 32K window); it still fits 32K."]
213    if t.context < 65536:
214        out.insert(0, "WARNING: Hermes is built for 64K or more. At %dK it works only through the workaround above." % (t.context // 1024))
215    return out
216
217
218def _limits_openclaw(t: Target) -> list[str]:
219    return ["OpenClaw needs Node 24.16 or newer. On older Node, npm install -g openclaw quietly installs an empty 0.0.1 placeholder.",
220            "Its own token count runs 10-30% above the server's, so keep contextTokens (set here) below the window.",
221            "The embedded agent writes notes into its workspace folder: give it a scratch folder.",
222            "Harmless on exit: 'SQLite reclamation Worker failed' and 'semantic vector embeddings unavailable'."]
223
224
225def _limits_dsh(t: Target) -> list[str]:
226    return ["DeepSeek Harness is Strata's own coding harness inside the Strata app: nothing to write here.",
227            "Its package default compaction headroom (64K) is larger than a 32K window; the app's bridge sets it for you."]
228
229
230HARNESSES: list[Harness] = [
231    Harness("opencode", "OpenCode", "chat + tools", tested="opencode 1.19.3",
232            files=[FileSpec("~/.config/opencode/opencode.json", "json", opencode_file, merge=True)], limits=_limits_opencode,
233            run='opencode run "your task"', install="npm i -g opencode-ai"),
234    Harness("codex", "Codex CLI", "responses + tools", tested="codex-cli 0.163.0",
235            files=[FileSpec("~/.codex/config.toml", "toml", codex_file)], env=lambda t: {"STRATA_API_KEY": t.key}, limits=_limits_codex,
236            run='codex exec --skip-git-repo-check "your task"', install="npm i -g @openai/codex"),
237    Harness("claude-code", "Claude Code", "messages + tools", tested="Claude Code 2.1.302",
238            files=[FileSpec("~/.claude/settings.json", "json", claude_file, merge=True)], env=claude_env, limits=_limits_claude,
239            run='claude -p "your task"', install="npm i -g @anthropic-ai/claude-code", aliases=("claude",)),
240    Harness("omp", "oh-my-pi (omp)", "chat + tools", tested="omp 18.11.2",
241            files=[FileSpec("~/.omp/agent/models.yml", "yaml", omp_models), FileSpec("~/.omp/agent/config.yml", "yaml", omp_config)],
242            limits=_limits_omp, run='omp -p "your task"', install="curl -fsSL https://omp.sh/install | sh", aliases=("oh-my-pi",)),
243    Harness("pi", "pi (pi.dev)", "chat + tools", tested="pi 0.74.2",
244            files=[FileSpec("~/.pi/agent/models.json", "json", pi_models, merge=True),
245                   FileSpec("~/.pi/agent/settings.json", "json", pi_settings, merge=True)],
246            env=lambda t: {"PI_SKIP_VERSION_CHECK": "1"}, limits=_limits_pi, run='pi -p "your task"',
247            install="npm install -g @earendil-works/pi-coding-agent"),
248    Harness("hermes", "Hermes Agent", "chat + tools", tested="Hermes Agent 2026.9.24",
249            files=[FileSpec("~/.hermes/config.yaml", "yaml", hermes_file)], env=lambda t: {"OPENAI_API_KEY": t.key},
250            limits=_limits_hermes, run='hermes chat -Q --yolo -q "your task"', aliases=("hermes-agent",)),
251    Harness("openclaw", "OpenClaw", "chat + tools", tested="OpenClaw 2026.10.4",
252            files=[FileSpec("~/.openclaw/openclaw.json", "json", openclaw_file, merge=True)], limits=_limits_openclaw,
253            run='openclaw agent --local --agent main --session-id demo --thinking low -m "your task"', install="npm install -g openclaw (Node 24.16+)"),
254    Harness("deepseek-harness", "DeepSeek Harness", "the Strata app", tested="DSH 0.2.1-alpha.3", built_in=True,
255            limits=_limits_dsh, aliases=("deepseek", "dsh")),
256]
257
258
259def find(name: str) -> Harness | None:
260    key = name.strip().lower()
261    for h in HARNESSES:
262        if key == h.id or key in h.aliases or key == h.title.lower():
263            return h
264    return None
265
266
267def closest_name(name: str) -> str | None:
268    from strata_cli.launch.settings import closest
269    return closest(name, [h.id for h in HARNESSES])
270
271
272# ------------------------------------------------------------------------------------------------ rendering
273
274def server_root(url: str) -> str:
275    """The server root: the address without a trailing /v1 (people paste the OpenAI-style base). Anthropic apps add /v1/messages themselves."""
276    root = url.strip().rstrip("/")
277    return root[:-3].rstrip("/") if root.lower().endswith("/v1") else root
278
279
280def target(url: str, key: str | None, model: str, context: int | None = None) -> Target:
281    return Target(url=server_root(url), key=key or PLACEHOLDER_KEY, model=model or "strata", context=int(context or 32768))
282
283
284def render(h: Harness, t: Target) -> dict:
285    """What to show or write for this harness: files with their text, environment lines, the limits in plain words."""
286    files = [{"path": f.path, "kind": f.kind, "merge": f.merge, "text": f.make(t)} for f in h.files]
287    return {"harness": h.id, "title": h.title, "speaks": h.speaks, "status": h.status, "files": files,
288            "env": h.env(t) if h.env else {}, "limits": h.limits(t) if h.limits else [], "run": h.run, "install": h.install,
289            "tested": h.tested}
290
291
292def expand(path: str) -> Path:
293    return Path(os.path.expanduser(path))
294
295
296def write_file(spec: dict, *, backup: bool = True) -> dict:
297    """Write one rendered file. An existing file is copied to `<name>.strata-bak-<time>` first; a JSON file with `merge` keeps the
298    keys it already had (the new ones win on the same key). Returns {path, backup, action}."""
299    path = expand(spec["path"])
300    path.parent.mkdir(parents=True, exist_ok=True)
301    existed = path.is_file()
302    bak = None
303    text = spec["text"]
304    if existed and backup:
305        bak = path.with_name(path.name + ".strata-bak-" + time.strftime("%Y%m%d-%H%M%S"))
306        shutil.copy2(path, bak)
307    if existed and spec.get("merge") and spec["kind"] == "json":
308        try:
309            old = json.loads(path.read_text(encoding="utf-8-sig"))
310            merged = _merge(old, json.loads(text))
311            _keep_output_cap(old, merged)
312            text = json.dumps(merged, indent=2)
313        except ValueError:
314            pass                                    # an old file that is not JSON is replaced (a backup was made)
315    path.write_text(text if text.endswith("\n") else text + "\n", encoding="utf-8")
316    try:
317        os.chmod(path, 0o600)                       # it can hold the API key
318    except OSError:
319        pass
320    return {"path": str(path), "backup": str(bak) if bak else None,
321            "action": "merged" if existed and spec.get("merge") and spec["kind"] == "json" else ("replaced" if existed else "created")}
322
323
324def _keep_output_cap(old, merged) -> None:
325    """The output cap in a config being rewritten (in place on `merged`): a value the person set stays, so does a larger one from a newer Strata. The value
326    older Strata versions wrote on every window (OUTPUT_CAP, 4,096) is the generated default and is replaced, or the files written before #5006 would keep
327    the cap that breaks compaction for ever. OpenCode's limit.output and Claude Code's CLAUDE_CODE_MAX_OUTPUT_TOKENS."""
328    if not (isinstance(old, dict) and isinstance(merged, dict)):
329        return
330    models = ((old.get("provider") or {}).get("strata") or {}).get("models")
331    new_models = ((merged.get("provider") or {}).get("strata") or {}).get("models")
332    if isinstance(models, dict) and isinstance(new_models, dict):
333        for name, entry in models.items():
334            was = ((entry or {}).get("limit") or {}).get("output") if isinstance(entry, dict) else None
335            limit = (new_models.get(name) or {}).get("limit") if isinstance(new_models.get(name), dict) else None
336            if isinstance(was, int) and not isinstance(was, bool) and was != OUTPUT_CAP and isinstance(limit, dict):
337                limit["output"] = was
338    was_env = (old.get("env") or {}).get("CLAUDE_CODE_MAX_OUTPUT_TOKENS") if isinstance(old.get("env"), dict) else None
339    if isinstance(merged.get("env"), dict) and was_env is not None and str(was_env) != str(OUTPUT_CAP):
340        merged["env"]["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] = was_env
341
342
343def _merge(old, new):
344    if isinstance(old, dict) and isinstance(new, dict):
345        out = dict(old)
346        for k, v in new.items():
347            out[k] = _merge(old[k], v) if k in old else v
348        return out
349    return new
350
351
352def mask(text: str, key: str) -> str:
353    return text.replace(key, key[:10] + "•" * 8) if key and key != PLACEHOLDER_KEY else text