Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
56 changes: 54 additions & 2 deletions lab/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ The local server designed in `docs/design/Agent-Integration.md` (fork #131, bran
`design/agent-integration`). Slice 0: the version-1 contracts, golden examples and a parser.
Slice 2: the attach-only read server ([below](#slice-2-the-attach-only-read-server)). Slice 3: the
durable control plane ([below](#slice-3-the-durable-control-plane)): leases, request records,
tickets and events in SQLite. Nothing presses a button yet: that is Slice 5.
tickets and events in SQLite. Slice 5 ([below](#slice-5-leased-actions)), first sub-slice: `stop_program`,
the first leased action. Nothing starts a program or presses a button yet.

| Path | What |
|---|---|
Expand All @@ -26,6 +27,8 @@ tickets and events in SQLite. Nothing presses a button yet: that is Slice 5.
| `pa_lab/db.py` | The SQLite file: migrations (`PRAGMA user_version`), owner-only file, `BEGIN IMMEDIATE` writes |
| `pa_lab/control.py` | Leases, idempotent requests, tickets, events, `next_events`, reconciliation, compaction |
| `tests/test_{db,control,control_concurrency,control_mcp}.py` | Slice 3's tests: restarts, threads and processes racing, kills mid-write |
| `pa_lab/actions.py` | Leased actions (Slice 5): `stop_program`, the channel request it sends and how its reply is read |
| `tests/test_actions.py` | Slice 5's tests: the ticket, retries, refusals, UI takeover, app restart, a terminal event before the response |

Stdlib only (Python 3.8+), so no venv: the MCP transport is small enough to write on
`http.server`. Run the tests from the repo root:
Expand Down Expand Up @@ -137,7 +140,9 @@ python3 -m pa_lab serve --config ~/.config/pa-lab/server.json
"profile": "lab-B"}}}
```

The config is the server's own, closed, and must list exactly `B`; it never reads
The config is the server's own, closed, and must list exactly `B`. `consoles.B.channel_owner`
(optional, one word, default the profile) is the token Slice 5's actions claim the app's channel
with; it never reads
`~/BDSPLab/consoles.json`. A Claude Code client adds it as an HTTP MCP server at
`http://127.0.0.1:8765/mcp` with the header `Authorization: Bearer <token>`.

Expand Down Expand Up @@ -264,3 +269,50 @@ every event after an active cursor (one used in the last 7 days), every event of
and every pending record; finished records go after 7 days. A cursor behind the compacted range
is refused (`invalid_arguments`, field `after_seq`, `evidence.compacted_through`), never served
with a silent gap.

## Slice 5: leased actions

Built so far: `stop_program`, the first tool that changes what the app does. The rest of Slice 5
(`preflight_program`, `run_program`, `cfr_batch`) needs app-side commands first; see the list in
the PR that added this section.

**A leased action is a ticket.** `stop_program(console, request_id, lease_token)` returns its
request record at once: `pending` until the app reports the outcome, which arrives as a
`request_completed` / `request_failed` event (`next_events`) and in `request_status`. The tool
does not wait for the program to stop. `ControlPlane.begin_action` stores the call in one
transaction with the lease check: an exact retry gets the stored record and sends nothing; the
lease must be held by the token (an idle lease is renewed by the call); a program that is not
`running` completes at once with `outcome: not_running`; otherwise the record is `pending` and
remembers the app instance it was sent to (`requests.instance_id`, migration 2).

**The channel request** (Lab.md "Requests", "Owner") is fixed text:

```
owner lab-B
request <request_id>
owner claim lab-B
stop
```

The daemon claims the channel with `channel_owner` before each action rather than once at
attach, so it works across app restarts and beside `lab/scripts/lc.sh`, which uses the same
default token. The app puts `request_id` on `program.last_transition` and keeps it from
`stopping` to `stopped`.

**What resolves the ticket.** The app's report, applied by `observe` on every read of
`console://B/state`, every `request_status`, and every poll of a waiting `next_events`:

| The app shows | Ticket |
|---|---|
| `stopped`, `last_transition` `{stop, lab, <this request_id>}` | completed, `outcome: stopped` |
| `stopping` with that transition | still pending |
| `stopped` by `program` or `error` at or after the call | completed, `outcome: ended` (the run's own end) |
| a UI Start/Stop at or after the call | failed, `console_held_by_user`; the lease becomes `user` |
| another `instance.id` | failed, `app_unavailable`, `evidence.reason: instance_replaced` |
| (the stop line failed and nothing runs) | completed, `outcome: not_running` |
| (the stop line failed otherwise, e.g. `owned by <other>`) | failed, `app_unavailable`, the journal in `evidence` |
| (no journal within 7 s and the request still in the inbox) | withdrawn; `refused`, `timeout`: nothing was sent |
| (no journal within 7 s and the app took the request) | still pending; the rows above resolve it |

A stop by this lease holder ends `agent_running` as before (`lease_changed`, reason `run_ended`).
`begin_run` (Slice 3) is still entered only by tests: `run_program` will call it.
4 changes: 3 additions & 1 deletion lab/server/pa_lab/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ def _serve(path: str) -> int:
for reader in readers.values(): # restart reconciliation: apply what the app shows now
reader.console_state()
plane.compact()
server = mcp_server.make_server(cfg.port, token, readers, control_plane=plane)
server = mcp_server.make_server(cfg.port, token, readers, control_plane=plane,
channel_owners={name: entry.channel_owner for name, entry in cfg.consoles.items()
if entry.channel_owner is not None})
logging.getLogger('pa_lab.server').info('serving %s on http://127.0.0.1:%d%s',
', '.join(sorted(readers)), server.server_address[1],
mcp_server.ENDPOINT)
Expand Down
141 changes: 141 additions & 0 deletions lab/server/pa_lab/actions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
"""Leased actions (Slice 5 of fork #131). First: `stop_program`.

A leased action is a long operation: the tool stores a ticket, sends one fixed request into the
app's channel and returns; the app's own report in `Lab/state.json` completes it. Agents do not
park on the call: they read `request_status` or wait in `next_events` for the ticket's
`request_completed` / `request_failed` event.

`stop_program(console, request_id, lease_token)`:

1. Read `Lab/state.json` (the app is up; its instance) and apply it (`observe`), so a UI click
that already happened takes the console before this call is decided.
2. `ControlPlane.begin_action`: the lease must be held by the token; a program that is not
`running` completes at once (`outcome: not_running`); otherwise a `pending` ticket bound to
that app instance. An exact retry returns the stored record and sends nothing.
3. Send `owner T` / `request <request_id>` / `owner claim T` / `stop` (Lab.md "Requests",
"Owner"). `T` is the console's channel owner from the config; the app names `request_id` in
`program.last_transition` and keeps it from `stopping` to `stopped`.
4. Wait for the journal (the line itself is immediate; the program stops in the background):
- `ok`: read the state again; the ticket completes when the app reports `stopped` with this
request id, possibly already in this read (a terminal event before the response);
- a failed line: if the program is no longer running the stop is moot (`not_running`),
otherwise the ticket fails with the app's error;
- no journal in time: if the request is still in the inbox it is withdrawn and the ticket is
`refused` with `timeout` (nothing was sent); if the app took it, the ticket stays pending
and resolves from the state as above.

No caller string reaches the inbox: the request id is a checked UUID and the rest is fixed text.
"""

from __future__ import annotations

import os
import time
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional

from pa_lab import control, shot
from pa_lab.lab_reader import ConsoleReader, Unavailable

STOP_ANSWER_MS = 5000
JOURNAL_POLL_S = 0.05

__all__ = ['stop_program', 'request_text']


def request_text(owner: str, request_id: str, commands: List[str]) -> str:
"""A channel request that claims the channel for `owner` and runs `commands` under it.

`owner T` must be the first line and `request <uuid>` follows (Lab.md "Requests");
`owner claim T` succeeds when the channel is free or already T's.
"""
return ''.join('{}\n'.format(line) for line in
['owner ' + owner, 'request ' + request_id, 'owner claim ' + owner] + commands)


def _send(lab_dir: Path, name: str, text: str) -> Path:
part = lab_dir / 'outbox' / (name + '.part')
inbox = lab_dir / 'inbox' / (name + '.txt')
part.write_text(text, encoding='utf-8')
os.replace(part, inbox)
return inbox


def _journal(reader: ConsoleReader, sleep: Callable[[float], None], deadline: float, name: str) -> Optional[List[str]]:
path = reader.lab_dir / 'outbox' / (name + '.out')
while True:
if path.exists():
lines = path.read_text(encoding='utf-8', errors='replace').splitlines()
if lines and lines[-1] == 'end':
return lines
if reader.now() >= deadline:
return None
sleep(JOURNAL_POLL_S)


def _withdrawn(inbox: Path) -> bool:
"""True when the request was still in the inbox and is now gone: the app never saw it."""
try:
os.remove(inbox)
return True
except FileNotFoundError:
return False


def _not_running(app: Dict[str, Any]) -> Dict[str, Any]:
program = app['program']
return {'outcome': 'not_running', 'instance_id': app['instance']['id'], 'run_id': program['run_id'],
'program_state': program['state']}


def stop_program(plane: control.ControlPlane, reader: ConsoleReader, client_id: str, request: Dict[str, Any],
owner: str, sleep: Callable[[float], None] = time.sleep) -> Dict[str, Any]:
"""Runs one stop_program request; returns its request_record (pending, completed, refused or failed).

Raises control.Refused for a request that cannot be keyed (bad console, request id or
arguments, or an id reused with other arguments); those are not stored.
"""
started = reader.now()
try:
app = reader.app_state()
except Unavailable as e:
app, unavailable = None, e
else:
plane.observe(reader.console, app)

def decide(lease_row) -> Optional[Dict[str, Any]]:
if app is None:
refusal = unavailable.refusal()
raise control.Refused(refusal.pop('code'), refusal.pop('message'), **refusal)
if app['program']['state'] != 'running':
return _not_running(app)
return None

record, send = plane.begin_action(client_id, request, None if app is None else app['instance']['id'], decide)
if not send:
return record
request_id = record['request_id']
name = 'palab_stop_program_{}'.format(request_id.replace('-', ''))
inbox = _send(reader.lab_dir, name, request_text(owner, request_id, ['stop']))
lines = _journal(reader, sleep, started + (STOP_ANSWER_MS + shot.ANSWER_GRACE_MS) / 1000.0, name)
if lines is None:
if _withdrawn(inbox):
return plane.resolve_ticket(client_id, 'stop_program', request_id, refusal={
'code': 'timeout', 'message': 'The app did not take the stop request in time; nothing was sent.',
'evidence': {'request': name}}, acted=False)
return plane.record(client_id, 'stop_program', request_id)
errors = [line for line in lines if line.startswith('error ')]
if errors:
try:
now = reader.app_state()
except Unavailable:
now = None
if now is not None and now['instance']['id'] == app['instance']['id'] and \
now['program']['state'] != 'running':
reader.console_state()
return plane.resolve_ticket(client_id, 'stop_program', request_id, result=_not_running(now))
return plane.resolve_ticket(client_id, 'stop_program', request_id, refusal={
'code': 'app_unavailable', 'message': "The app refused the stop: {}".format(errors[0]),
'evidence': {'journal': lines}})
reader.console_state() # applies observe: the stop may already be reported
return plane.record(client_id, 'stop_program', request_id)
15 changes: 12 additions & 3 deletions lab/server/pa_lab/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""The daemon's own config (Slice 2 of fork #131): a one-entry allowlist (console B), the loopback
port and the bearer token file. It never reads `~/BDSPLab/consoles.json`, which also lists A.
`channel_owner` (optional; default the profile name, which is what `lab/scripts/lc.sh` uses) is the
token the daemon claims the app's channel with before a leased action (Slice 5, Lab.md "Owner").

{"schema": 1, "host": "127.0.0.1", "port": 8765, "token_file": "~/.config/pa-lab/token",
"db_file": "~/.local/state/pa-lab/control.sqlite",
Expand All @@ -11,6 +13,7 @@

import json
import os
import re
from pathlib import Path
import secrets
import stat
Expand All @@ -19,18 +22,20 @@
ALLOWED_CONSOLES = ('B',)
LOOPBACK_HOSTS = ('127.0.0.1',)
TOP_KEYS = ('schema', 'host', 'port', 'token_file', 'db_file', 'consoles')
OWNER_RE = re.compile(r'^[A-Za-z0-9_.-]{1,64}$')
DEFAULT_DB_FILE = '~/.local/state/pa-lab/control.sqlite'
CONSOLE_KEYS = ('lab_dir', 'profile')
CONSOLE_KEYS = ('lab_dir', 'profile', 'channel_owner')


class ConfigError(ValueError):
pass


class ConsoleConfig:
def __init__(self, lab_dir: Path, profile: Optional[str]):
def __init__(self, lab_dir: Path, profile: Optional[str], channel_owner: Optional[str] = None):
self.lab_dir = lab_dir
self.profile = profile
self.channel_owner = channel_owner if channel_owner is not None else profile


class Config:
Expand Down Expand Up @@ -85,7 +90,11 @@ def load(path: Path) -> Config:
profile = entry.get('profile')
if profile is not None and (not isinstance(profile, str) or not profile):
raise ConfigError('{}.profile: expected a profile name'.format(field))
out[name] = ConsoleConfig(_path(entry.get('lab_dir'), field + '.lab_dir'), profile)
owner = entry.get('channel_owner', profile)
if owner is not None and (not isinstance(owner, str) or not OWNER_RE.match(owner)):
raise ConfigError('{}.channel_owner: expected one word of A-Z a-z 0-9 _ . - (it defaults to the '
'profile)'.format(field))
out[name] = ConsoleConfig(_path(entry.get('lab_dir'), field + '.lab_dir'), profile, owner)
return Config(host, port, _path(doc.get('token_file'), 'token_file'), out,
_path(doc.get('db_file', DEFAULT_DB_FILE), 'db_file'))

Expand Down
Loading
Loading