Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
ca773ac
feat(harness): hybrid router with a local lane for subagents
Siddhesh2377 Nov 3, 2026
7dcbf12
fix(harness): close the hybrid router review findings
Siddhesh2377 Nov 3, 2026
aad937e
fix(pls): reuse KV through mlx-vlm APC instead of a raw prompt cache
Siddhesh2377 Nov 4, 2026
eceefb8
feat(pls): privacy and cost policies routed by a local decision model
Siddhesh2377 Nov 4, 2026
d3fa879
fix(pls): gate the unix socket server so Windows builds
Siddhesh2377 Nov 4, 2026
796faf5
fix(pls): draw the launch token from getrandom on every OS
Siddhesh2377 Nov 4, 2026
245f080
perf(pls): stream through the guard, size APC, log cloud timing
Siddhesh2377 Nov 5, 2026
9e9de46
fix(pls): close the privacy, token, and credential gaps
Siddhesh2377 Nov 5, 2026
9af023d
feat(pls): hybrid mode for opencode, OpenWork, Hermes and OpenClaw
Siddhesh2377 Nov 5, 2026
8d5d986
fix(harness): keep hybrid routing on DeepSeek and Hermes only
Siddhesh2377 Nov 6, 2026
70da4ce
refactor(harness): one hybrid launch module, drop wally pls
Siddhesh2377 Nov 6, 2026
ce76892
feat(pls): span-mask private prompts and return the masked answer
Siddhesh2377 Nov 6, 2026
b08cc29
fix(pls): pin the PII masker and withhold private subagent answers
Siddhesh2377 Nov 6, 2026
231c950
fix(pls): mask cloud copies and rebind the decision socket
Siddhesh2377 Nov 9, 2026
ac6986a
fix(ci): install uvicorn for the PLS unit tests
Siddhesh2377 Nov 9, 2026
4c3d818
fix(pls): a privacy no drops the launch line
Siddhesh2377 Nov 9, 2026
0a122c9
fix(test): record pplx coder and the pii masker in the catalog golden
Siddhesh2377 Nov 9, 2026
bcf43e4
fix(pls): close the review findings on masking, hybrid launch, and help
Siddhesh2377 Nov 9, 2026
782d956
fix(pls): keep delegate off the policy help and bound remask
Siddhesh2377 Nov 9, 2026
12eebf3
fix(pls): keep opencode --cloud, span order, and one queue put
Siddhesh2377 Nov 9, 2026
b77ac2b
fix(pls): remask values that contain a token without a colliding marker
Siddhesh2377 Nov 9, 2026
acbc3d6
fix(pls): skip a token reserve when the prompt has none
Siddhesh2377 Nov 9, 2026
3a9352c
feat(pls): add watch, prefix reuse, and hybrid --custom
Siddhesh2377 Nov 10, 2026
b2fa168
fix(pls): drop the watch page and keep the request log
Siddhesh2377 Nov 10, 2026
4aed871
fix(cli): satisfy clippy and record --custom in help goldens
Siddhesh2377 Nov 10, 2026
f0a7a7e
fix(pls): close the remaining review notes on the log and the mask
Siddhesh2377 Nov 10, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ jobs:
WALLY_INSTALL_SH=dash bash scripts/test/test-install-skill-dirs.sh
WALLY_INSTALL_SH=dash bash scripts/test/test-install-lock.sh
WALLY_INSTALL_SH=dash bash scripts/test/test-install-libstdcxx-preflight.sh
- name: PLS unit tests
run: |
set -euo pipefail
python3 -m venv /tmp/pls-test
/tmp/pls-test/bin/pip install --quiet fastapi==0.162.0 httpx==0.28.1 uvicorn==0.54.0
cd pls
/tmp/pls-test/bin/python -m unittest test_pls test_mask_store
- name: install.sh output is byte-identical under bash, dash and sh
# Runs the real install.sh under all three with a stubbed curl/uname
# and a fixture release -- no network -- across the happy path, an
Expand Down
11 changes: 11 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,17 @@ The credential is a normal API key with the customer's credit behind it. Treat
it as one: it goes in the profile file at `0600` and nowhere else, and it is
never logged.

## Python router, no Rust rebuild

`pls/*.py` is the router. The binary embeds those files and writes them to
the profile `pls` directory (`~/.config/wally/pls/` unless `WALLY_PROFILE_DIR`
moves the profile) when `assets.sha` does not match. A change that stays
inside `pls/` does not need a Rust rebuild for a local try: copy the changed
files into that directory and leave `assets.sha` alone, or the next launch
puts the embedded copy back. The copy is not what ships. A release still
needs a rebuild so the embedded files are the ones in the binary. Rebuild
when `src/` or the launch path changes too.

## Building against the SDK

`WALLY_SDK_KIT` points at a built kit, not at SDK source. `cmake/sdk-pin.cmake`
Expand Down
188 changes: 188 additions & 0 deletions pls/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
# PLS — hybrid router

A loopback router with one endpoint, `/v1/chat/completions`, for the main
chat and every subagent. `/v1/models` lists two ids, `Hybrid-Wally-0.1` for
the parent and `Hybrid-Wally-0.1-local` for subagents. The local id is also
how a child request is recognised, together with `x-parent-session-id`
(opencode) and a prompt that starts `pls-task:`. Each entry carries
`context_length` and `max_completion_tokens` (Hermes reads them). Routing reads
the request:

| Kind | Rule | `hybrid` | `cloud` |
|---|---|---|---|
| subagent | model is `Hybrid-Wally-0.1-local`, or header `x-parent-session-id` (opencode), or first prompt starts `pls-task:` | local model, never decided | cloud, marker stripped |
| side | no `tools` (session title) | cloud; privacy span-masks the prompt | cloud as sent |
| main | everything else | decision, rewrite, PII redact, guard, cloud | cloud as sent |

Only the router writes `pls-task:`. Ids look like `a1b2c3-t1`: the prefix
names the session (its first prompt) and numbers start at t1 in each one.
Prompts with no reply between them are one task, and only the unanswered
prompt carries a task line. It stamps every spawn call in a main reply
(the harness's own tool, see Harnesses) with the pending task's id, or with a new ad hoc task (`local_only`
under privacy, `summary` under cost). Any other path, `/local/v1` included,
is 404.

`wally` starts it, points the harness at it, and stops it on exit. The local
model server is spawned by the router and killed with it.

## Running

```
wally <harness> --hybrid [--policy privacy|cost] -m <local-model> --cloud-model <cloud-model>
```

`<harness>` is `deepseek` or `hermes`.
Each launch is temporary: the harness gets its config for one run (an
environment variable, a temp file or a temp directory) and none of the
person's own harness files change. Every request must carry the launch's
`x-pls-token`; each harness config sends it.

## Harnesses

`wally` writes the harness's profile into `config.json` as `harness`. It
names the spawn tool the router stamps, guards and denies to children, and
the text the harness adds around a child's prompt.

| Profile | Spawn tool and task field | Child loses | Prompt cleanup | Launch |
|---|---|---|---|---|
| `deepseek` | `subagent.prompt` | `subagent`, `subagent_fork`, `send_message` | dsh's "Your parent agent id…" note | `--patch` overlay |
| `hermes` | `delegate_task.tasks[].goal` | `delegate_task`, `send_message` | none | `HERMES_MANAGED_DIR` temp overlay |
| `opencode-v2` | `subagent.prompt` (`agent` required) | `subagent`, `task` | the "You are a subagent spawned…" preface | config `harness` |
| `opencode-v1` | `task.prompt` (`subagent_type` required) | `subagent`, `task` | none | config `harness`; OpenWork uses this |
| `openclaw` | `sessions_spawn.task` | `sessions_spawn`, `subagents` | the OpenClaw context block | config `harness` |

`wally <harness> --hybrid` is `deepseek` or `hermes` only. The other
profiles are what `config.json` `harness` names; `opencode` reads as
`opencode-v2` and `openwork` as `opencode-v1`. An unknown name reads as
`deepseek`.

The synthesised call fills the fields each harness requires. Hermes
`delegate_task` with `action: list|steer|stop` starts nothing and is left
alone. Under privacy the parent keeps its spawn tool.

Harness-written `user` messages are skipped when routing: dsh's
`<system-reminder>`, its runtime snapshot, and its "Agent … sent a message"
reports. The Hermes patterns come from source, not yet from a loopback capture.

## Policies

Each new user prompt goes to a local decision model (`mlx-clef-flash-9b-4bit`,
served by wally on its socket as `POST /decide`). Two questions are asked.
The policy question decides the record. A second `delegate` question decides
whether the launch line is appended. `delegate` is not a `--policy` value.

| Policy | Policy decision | The cloud sees | Subagent answer |
|---|---|---|---|
| `privacy` (default) | private | the prompt with personal values replaced by tokens. The launch line is added only when `delegate` is not a clear no | full local report; personal values replaced before the parent sees it (`local_only`) |
| `privacy` | not private | that same masked prompt. The launch line is added on the same rule | summarised |
| `cost` | large task | the prompt plus "launch a subagent, `pls-task: tN`" | summarised |
| `cost` | small task | the prompt plus "do it yourself" | no subagent |

A clear `delegate` no drops the launch line on every policy. A failed
`delegate` call still appends it. A failed policy decision fails safe:
`privacy` treats the prompt as private, `cost` treats it as small.

Under `privacy` the parent is offered only its spawn tool, and any other
tool call in its reply is dropped and asked again; after two tries the router
emits the subagent call itself. The `pls-task:` id is how the subagent side
finds its summary type and, for a private prompt, the real text. If the masker
fails, the cloud gets the whole-prompt placeholder and not the raw prompt.

If the decision socket is missing, both calls fail the same way: `privacy`
treats every prompt as private and `cost` tells the parent to do the task
itself. Records live in
`tasks.json` (mode `0600`): the masked prompt and its session, not a second
copy of the raw prompt. A resumed session demasks from that pair.

## Subagents

A subagent runs on the local model and cannot launch another: it loses its
profile's spawning and messaging tools under both policies, and its system
prompt says so once. `kvc.py` places the harness's own messages before the
task, so the system prompt and that harness block are the token prefix every
new sub-agent in the launch reuses. The task stays last, because it changes. A second spawn while one child is already running is
dropped. A local reply that still calls one has the
call dropped (`child_spawn_blocked`). If the local model cannot start,
privacy returns the withheld sentence and cost sends the same request to the
cloud with the marker stripped (`local_unavailable`). A full local queue
(depth 8) overflows to the cloud under `cost`; `privacy` and a `local_only`
task wait instead.

## Socket

wally serves the router over a unix socket at `~/.config/wally/pls/pls.sock`
(mode `0600`, path in `PLS_SOCKET`): `POST /decide` for the decision model and
`GET /token` for the cloud token. Nothing is gated on a plan.

## Log

Each event is one JSON line in the profile `pls/watch/traffic.jsonl`
(`~/.config/wally/pls/watch/` unless `WALLY_PROFILE_DIR` is set). Lines from
the same request share a `req` id. The file is mode 0600. It keeps roles and
lengths, not the raw prompt. Rows older than 7 days are dropped, and only the
newest 2000 lines are kept. Delete the `pls/watch` package and the router
keeps running without the log.

## PII

Under `privacy`, every cloud-bound prompt is span-masked by the local model
`perplexity-ai/pplx-pii-masking-MLX` before it leaves. A personal value becomes
a token `⟦pii:N⟧`. The map is one SQLite file per harness under
`masks/<harness>.sqlite` (file `0600`, directory `0700`) and stays on this
machine. The subagent and a summary on the way back use the same session.
A summary is span-masked first; if that fails the parent gets the
summary-failure sentence, not the answer. A subagent's report is shown in full. Personal values in it are replaced
before that text reaches the cloud, and the cloud's reply is restored
before it is shown. The mask file drops rows older than 7 days when it
opens, and a row with no timestamp is dropped too. A session resumed after
that still shows the cloud reply, with any `⟦pii:N⟧` whose value was dropped
left as the token. New values number past every token this session has
issued, including ones already purged.

The regex still runs after the span mask, and it is the only pass under
`cost`. It replaces emails, phone numbers, API keys, IPv4 addresses and
IBANs with `[email]`, `[phone]`, `[key]`, `[iban]` and `[ipv4]`. Counts,
attributed to the file path the text mentions, travel in `x-pls-pii`.
The values do not. The counts are also in the watch log.

## Mode

`~/.config/wally/pls/config.json` is re-read on every request:

```json
{ "mode": "hybrid", "policy": "privacy", "max_turns": 20,
"harness": "opencode-v2",
"cloud_limits": { "context_length": 200000, "max_completion_tokens": 32000 } }
```

`harness` and `cloud_limits` are written by each launch. A hybrid launch
sets `mode` to `hybrid`, so a previous `cloud` does not stick. An unknown
harness reads as `deepseek`, and a missing limit as the local one.

- `cloud`: everything goes to the cloud exactly as the harness sent it, and
the local model is never loaded. Switching a session here and back is safe.
Comment thread
Siddhesh2377 marked this conversation as resolved.
Resolved
- `hybrid`: main chat goes to the cloud under the policy, subagents go local.

Missing or unparseable falls back to `hybrid`, `privacy` and 20 turns.

## Files

```
~/.config/wally/pls/pls.py override, wins over the copy beside the binary
~/.config/wally/pls/config.json mode, policy and turn cap
~/.config/wally/pls/tasks.json privacy records: masked prompt and mask session (0600)
~/.config/wally/pls/masks/ one <harness>.sqlite per harness (0700)
~/.config/wally/pls/venv/ built once from requirements.lock
~/.config/wally/pls/pls.pid swept on the next start
~/.config/wally/pls/watch/traffic.jsonl request log, kept after exit
```

## Requirements

`uv` on `PATH` or beside the binary. The first launch builds the venv
(`mlx-vlm`, `mlx-lm`, `fastapi`, `uvicorn`, `httpx`) — about 1–2 GB.

## Limits

Text only, one concurrent local request (queue depth 8, then overflow to the
cloud under `cost`; `privacy` waits instead), one global mode.
27 changes: 27 additions & 0 deletions pls/fixtures/dsh_first_turn.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"_source": "dsh 0.1.7-rc.2 first turn, captured 2026-11-04, message bodies trimmed",
"model": "Hybrid-Wally-0.1",
"stream": true,
"messages": [
{
"role": "system",
"content": "You are an AI agent powered by DeepSeek Harness.\n\nYou are a coding agent powered by the Hybrid-Wally-0.1 model.\n\nCheck the [exit code: N] marker on every bash result; investigate failures before moving on.\n\nUse the read tool \u2014 not shell com"
},
{
"role": "user",
"content": "What does this repo build? Answer in one line."
},
{
"role": "user",
"content": "<system-reminder>\nThe following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user "
},
{
"role": "user",
"content": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"/Users/h"
},
{
"role": "user",
"content": "<system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `amazon-bedrock`: Builds generative AI applications on Amazon Bedrock. Covers model invocat\n...\ne Bases, creating agents, applying guardrails, deploying to AgentCore, migrating/porting/converting a Bedrock Agent (including i"
}
]
}
37 changes: 37 additions & 0 deletions pls/kvc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""Session prefix for the local KV cache.

The cache reuses an identical token prefix. The system prompt and the
harness's own messages are the same for every sub-agent in one launch. The
task is not. Placing the task after the shared messages makes that prefix
the part every new sub-agent hits.
"""

from typing import Callable


def order(messages: list, stable_user: Callable[[dict], bool]) -> list:
"""Shared messages first, the task after them, then the dialogue."""
end = 0
while end < len(messages) and messages[end].get("role") not in ("assistant", "tool"):
end += 1
head, tail = messages[:end], messages[end:]
stable: list = []
task: list = []
for message in head:
if message.get("role") == "user" and not stable_user(message):
task.append(message)
else:
stable.append(message)
if not task:
return messages
first_task = next(
index for index, message in enumerate(head)
if message.get("role") == "user" and not stable_user(message)
)
shared_after = any(
message.get("role") != "user" or stable_user(message)
for message in head[first_task + 1:]
)
if not shared_after:
return messages
return stable + task + tail
9 changes: 9 additions & 0 deletions pls/local_limits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""Shared window and prefix-cache settings for the local model."""

import os

MAX_KV = int(os.environ.get("PLS_MAX_KV", "65536"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The default window and reply cap are duplicated in pls/pls.py (LOCAL_LIMITS). Import MAX_KV and MAX_OUT from local_limits there so the advertised context_length and max_completion_tokens cannot drift from the values the server enforces.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At pls/local_limits.py, line 5:

<comment>The default window and reply cap are duplicated in `pls/pls.py` (`LOCAL_LIMITS`). Import `MAX_KV` and `MAX_OUT` from `local_limits` there so the advertised `context_length` and `max_completion_tokens` cannot drift from the values the server enforces.</comment>

<file context>
@@ -0,0 +1,9 @@
+
+import os
+
+MAX_KV = int(os.environ.get("PLS_MAX_KV", "65536"))
+MAX_OUT = int(os.environ.get("PLS_MAX_OUT", "8192"))
+APC_BLOCKS = int(os.environ.get("PLS_APC_BLOCKS", "8192"))
</file context>

MAX_OUT = int(os.environ.get("PLS_MAX_OUT", "8192"))
APC_BLOCKS = int(os.environ.get("PLS_APC_BLOCKS", "8192"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: These settings are parsed with a bare int() and no range check. A non-numeric value fails at import with a bare ValueError, and zero or negative values are accepted (for example PLS_APC_BLOCKS=0 or PLS_MAX_KV=0), which breaks the server at startup or refuses every prompt. Parse with a helper that rejects non-positive values with a clear error naming the variable.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At pls/local_limits.py, line 7:

<comment>These settings are parsed with a bare `int()` and no range check. A non-numeric value fails at import with a bare ValueError, and zero or negative values are accepted (for example `PLS_APC_BLOCKS=0` or `PLS_MAX_KV=0`), which breaks the server at startup or refuses every prompt. Parse with a helper that rejects non-positive values with a clear error naming the variable.</comment>

<file context>
@@ -0,0 +1,9 @@
+
+MAX_KV = int(os.environ.get("PLS_MAX_KV", "65536"))
+MAX_OUT = int(os.environ.get("PLS_MAX_OUT", "8192"))
+APC_BLOCKS = int(os.environ.get("PLS_APC_BLOCKS", "8192"))
+APC_CHECKPOINTS = int(os.environ.get("PLS_APC_CHECKPOINTS", "32"))
+APC_CHECKPOINT_INTERVAL = int(os.environ.get("PLS_APC_CHECKPOINT_INTERVAL", "4096"))
</file context>

APC_CHECKPOINTS = int(os.environ.get("PLS_APC_CHECKPOINTS", "32"))
APC_CHECKPOINT_INTERVAL = int(os.environ.get("PLS_APC_CHECKPOINT_INTERVAL", "4096"))
76 changes: 76 additions & 0 deletions pls/local_only.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""Load the PLS local model with the same window and prefix cache, then answer once.

Uses PLS_MAX_KV, PLS_MAX_OUT and the APC block settings from model_server.py.
The model path comes from PLS_MODEL or ~/.config/wally/pls/config.json.
"""

import json
import os
import time
from pathlib import Path

import mlx.core as mx
import mlx_vlm
from mlx_vlm.apc import APCManager

from local_limits import (
APC_BLOCKS,
APC_CHECKPOINT_INTERVAL,
APC_CHECKPOINTS,
MAX_KV,
MAX_OUT,
)


def model_path() -> str:
if os.environ.get("PLS_MODEL"):
return os.environ["PLS_MODEL"]
config = Path.home() / ".config" / "wally" / "pls" / "config.json"
return json.loads(config.read_text())["model_path"]


def gb(n: int) -> str:
return f"{n / 1024**3:.2f} GB"


def main() -> None:
path = model_path()
print(f"model {path}", flush=True)
print(f"max_kv {MAX_KV} max_out {MAX_OUT} apc_blocks {APC_BLOCKS} "
f"checkpoints {APC_CHECKPOINTS} interval {APC_CHECKPOINT_INTERVAL}", flush=True)
mx.set_cache_limit(0)
started = time.monotonic()
model, processor = mlx_vlm.load(path)
apc = APCManager(num_blocks=APC_BLOCKS, overrides={
"checkpoint_entries": APC_CHECKPOINTS,
"checkpoint_interval_tokens": APC_CHECKPOINT_INTERVAL,
})
print(f"loaded in {time.monotonic() - started:.1f}s mlx {gb(mx.get_active_memory())}", flush=True)

prompt = os.environ.get("PLS_PROMPT", "Reply with one word: ok")
messages = [{"role": "user", "content": prompt}]
text = mlx_vlm.apply_chat_template(
processor, model.config, messages, add_generation_prompt=True,
)
tokenizer = getattr(processor, "tokenizer", processor)
prompt_tokens = len(tokenizer.encode(text))
if prompt_tokens >= MAX_KV:
raise SystemExit(f"prompt is {prompt_tokens} tokens; window is {MAX_KV}")
budget = min(64, MAX_OUT, MAX_KV - prompt_tokens)
started = time.monotonic()
out = mlx_vlm.generate(
model, processor, text,
max_tokens=budget,
temperature=0.0,
verbose=False,
apc_manager=apc,
)
answer = out.text if hasattr(out, "text") else str(out)
cached = getattr(out, "cached_tokens", 0) or 0
print(f"prompt_tokens {prompt_tokens} cached {cached} "
f"gen {time.monotonic() - started:.1f}s mlx {gb(mx.get_active_memory())}", flush=True)
print(answer.strip(), flush=True)


if __name__ == "__main__":
main()
Loading
Loading