8000 feat(runner): run one opted-in agent on the PTY runner (#240) by simon-inkie · Pull Request #241 · simon-inkie/inkie-deck · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
523d594
refactor(runner): promote the runner out of tests for slice 2 (#240)
simon-inkie Nov 19, 2026
d0a8785
docs(specs): record commit for #240
simon-inkie Nov 19, 2026
3293d06
feat(runner): PTY registry, opt-in, lock, launch environment and shut…
simon-inkie Nov 19, 2026
dfd3d28
docs(specs): record commit for #240
simon-inkie Nov 19, 2026
0412b72
feat(base): skip and refuse PTY-runner agents in boot, push and provi…
simon-inkie Nov 19, 2026
2acd807
docs(specs): record commit for #240
simon-inkie Nov 19, 2026
e43efde
Merge step 3 guards into the slice 2 branch (#240)
simon-inkie Nov 19, 2026
5bec1b0
feat(runner): route send, push and terminal view through the PTY runn…
simon-inkie Nov 19, 2026
22d7411
docs(specs): record commit for #240
simon-inkie Nov 19, 2026
b7f3031
Merge origin/main into pty-slice-2 (#240)
simon-inkie Nov 19, 2026
4af6d74
fix(runner): keep the inbox push guard working inside the PTY child, …
simon-inkie Nov 19, 2026
b357555
docs(specs): record commit for #240
simon-inkie Nov 19, 2026
7db30a6
fix(runner): make lock recovery and cleanup crash-safe (#240)
simon-inkie Nov 19, 2026
b6de9d3
docs(specs): record commit for #240
simon-inkie Nov 19, 2026
098986b
fix(runner): recover lock phase and failure latches after transient e…
simon-inkie Nov 19, 2026
c783bcb
docs(specs): record commit for #240
simon-inkie Nov 19, 2026
64f6f47
fix(runner): base guards key on the .runner file, stop works after op…
simon-inkie Nov 19, 2026
13e9c22
docs(specs): record commit for #240
simon-inkie Nov 19, 2026
f906fe6
test(base): reset push_rc before each invocation in the PTY guard cas…
simon-inkie Nov 19, 2026
24dd805
docs(specs): record commit for #240
simon-inkie Nov 19, 2026
ec075e2
merge: origin/main into pty-slice-2
simon-inkie Nov 19, 2026
015c08b
fix(runner): address CodeRabbit lock and recovery findings (#241)
simon-inkie Nov 22, 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
6 changes: 6 additions & 0 deletions .dependency-cruiser.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
*/
module.exports = {
forbidden: [
{
name: "deck-runner-does-not-import-test-code",
severity: "error",
from: { path: "^packages/deck/app/lib/runner/" },
to: { path: "^packages/deck/(?:test|e2e)/" },
},
{
name: "base-never-imports-deck",
severity: "error",
Expand Down
364 changes: 364 additions & 0 deletions .specs/240-pty-agent-slice-2/SPEC.md
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions packages/base/bin/boot-agents.sh
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,17 @@ if [[ "${BOOT_AGENTS_LIB_ONLY:-0}" == "1" ]]; then
return 0 2>/dev/null || exit 0
fi

TMUX_AGENTS=()
for agent in "${AGENTS[@]}"; do
if agent_opts_into_pty "$agent"; then
echo "boot-agents: skipping $agent (opted into the PTY runner)" >&2
else
TMUX_AGENTS+=("$agent")
fi
done
[[ ${#TMUX_AGENTS[@]} -gt 0 ]] || exit 0
AGENTS=("${TMUX_AGENTS[@]}")

tmux start-server 2>/dev/null || true
# Turn on focus-events before any pane starts, so Claude Code does not show its
# "tmux focus-events off" hint. tmux has no per-session form of this option
Expand Down
13 changes: 13 additions & 0 deletions packages/base/bin/codex-provider-switch
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,26 @@ def state_root() -> Path:
).resolve()


def agent_opts_into_pty(home: Path) -> bool:
lock_file = home / ".runner.lock"
runner_file = home / ".runner"
try:
if lock_file.exists() or lock_file.is_symlink():
return True
return runner_file.is_file() and runner_file.read_text(encoding="utf-8").strip() == "pty"
except (OSError, UnicodeError):
return True


def validate_agent(agent: str) -> Path:
if not AGENT_RE.fullmatch(agent):
raise SwitchError("invalid agent name")
root = agents_root()
home = (root / agent).resolve()
if home.parent != root or not home.is_dir():
raise SwitchError("agent home does not exist")
if agent_opts_into_pty(home):
raise SwitchError(f"{agent} opted into the PTY runner; provider switch refused")
return home


Expand Down
8 changes: 7 additions & 1 deletion packages/base/bin/inbox-push
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
# that residual is the detection side (bin/stuck-pane-sweep.sh), not a wider
# guess here.
# 2 -- skip:<reason> not pushed; caller treats as persist-only. Reasons:
# self, no-window, unknown-runtime (runtime is not claude, agy or codex),
# self, pty-runner, no-window, unknown-runtime (not claude, agy or codex),
# staged (real text in the composer at the gate), unknown-format,
# dialog-pending (a Codex approval dialog is up: Enter would confirm it,
# not deliver -- see the dialog block above), ctx-over (recipient's
Expand Down Expand Up @@ -180,6 +180,12 @@ emit() {
esac
}

. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/runtime-launch.sh" || emit "skip:no-runtime-launch-lib"
declare -F agent_opts_into_pty >/dev/null || emit "skip:no-runtime-launch-lib"
if agent_opts_into_pty "$RECIPIENT"; then
emit "skip:pty-runner"
fi

# --------------------------------------------------------------------------
# check_idle <pane> -- return 0 (busy) / 1 (idle).
#
Expand Down
9 changes: 9 additions & 0 deletions packages/base/bin/runtime-launch.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@
#
# Requires AGENTS_HOME to be set by the caller.

agent_opts_into_pty() {
local agent_home="$AGENTS_HOME/$1" runner
# A marker drains tmux admission; a lock keeps it drained after opt-out.
[[ -e "$agent_home/.runner.lock" || -L "$agent_home/.runner.lock" ]] && return 0
[[ -f "$agent_home/.runner" ]] || return 1
runner="$(< "$agent_home/.runner")" || return 1
[[ "$runner" =~ ^[[:space:]]*pty[[:space:]]*$ ]]
}

# agent_role <agent> -- the optional one-line role in $AGENTS_HOME/<agent>/.role.
agent_role() {
local file="$AGENTS_HOME/$1/.role"
Expand Down
11 changes: 11 additions & 0 deletions packages/base/bin/workspace.sh
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,17 @@ fi
# Per-runtime launch constructors, shared with boot-agents.sh.
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/runtime-launch.sh"

TMUX_AGENTS=()
for agent in "${AGENTS[@]}"; do
if agent_opts_into_pty "$agent"; then
echo "workspace: skipping $agent (opted into the PTY runner)" >&2
else
TMUX_AGENTS+=("$agent")
fi
done
[[ ${#TMUX_AGENTS[@]} -gt 0 ]] || exit 0
AGENTS=("${TMUX_AGENTS[@]}")

get_runtime() {
local agent="$1"
if [[ -n "$RUNTIME_OVERRIDE" ]]; then
Expand Down
21 changes: 21 additions & 0 deletions packages/base/test/codex-provider-switch.test.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,27 @@ def test_prepare_rejects_provisioned_azure_without_authoritative_plus_state(self
self.assertIn("authoritative provider state showing plus", result.stderr)
self.assertFalse((self.state / "alex" / "provider-switch.lock").exists())

def test_pty_opt_in_refuses_prepare_and_launch(self):
(self.agent / ".runner").write_text("pty\n", encoding="utf-8")
(self.agent / ".runti 10BC8 me").write_text("claude\n", encoding="utf-8")
tmux = self.root / "tmux"
tmux.write_text('#!/bin/sh\ntouch "$TMUX_LOG"\nexit 1\n', encoding="utf-8")
tmux.chmod(0o755)
tmux_log = self.root / "tmux.log"
env = {**self.env, "PROVIDER_SWITCH_TMUX_BIN": str(tmux), "TMUX_LOG": str(tmux_log)}
transaction = "11111111-1111-4111-8111-111111111111"
env.pop("MC_PTY_RUNNER", None)
for marker in (".runner", ".runner.lock"):
(self.agent / ".runner").unlink(missing_ok=True)
(self.agent / marker).write_text("pty\n", encoding="utf-8")
for args in (("prepare", "alex"), ("launch", "alex", transaction, "T" * 43)):
with self.subTest(marker=marker, command=args[0]):
result = subprocess.run([str(CLI), *args], env=env, text=True, capture_output=True)
self.assertEqual(result.returncode, 2)
self.assertIn("opted into the PTY runner", result.stderr)
self.assertFalse(tmux_log.exists())
self.assertFalse(self.state.exists())

def test_validate_agent_rejects_shell_metacharacters(self):
result = subprocess.run(
[str(CLI), "status", "alex;touch-pwned"],
Expand Down
47 changes: 47 additions & 0 deletions packages/base/test/inbox.test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2098,6 +2098,53 @@ REF_PAT='!\d+|(?<![A-Za-z0-9])ENG-\d+'
rm -rf "$T"
}

{
T=$(mktemp -d)
make_inbox "$T" alpha
make_inbox "$T" beta
ln -s "$T/alpha/inbox/beta.md" "$T/beta/inbox/alpha.md"
mkdir -p "$T/bin"
printf 'pty\n' > "$T/beta/.runner"
cat > "$T/bin/tmux" <<'STUB'
#!/usr/bin/env bash
printf '%s\n' "$*" >> "$TMUX_LOG"
exit 1
STUB
chmod +x "$T/bin/tmux"
if (
export AGENTS_HOME="$T" TMUX_LOG="$T/tmux.log" PATH="$T/bin:$PATH"
export INBOX_PUSH=1 INBOX_NO_PUSH=0 INBOX_PUSH_BIN="$BIN_DIR/inbox-push"
unset MC_PTY_RUNNER PANE_OVERRIDE PUSH_DRY_RUN

push_rc=0
verdict=$(AGENT_NAME=alpha "$INBOX_PUSH_BIN" beta hello) || push_rc=$?
out=$(run_inbox "$T" alpha reply beta --subject "cutover" --body "Keep the full message.") || exit 1
[[ "$push_rc" -eq 2 && "$verdict" == "skip:pty-runner" && ! -e "$TMUX_LOG" ]] &&
[[ "$out" == *"push: skip:pty-runner (persisted, not pushed)"* ]] &&
grep -qxF 'Keep the full message.' "$T/beta/inbox/alpha.md" || exit 1

push_rc=0
verdict=$(MC_PTY_RUNNER=0 AGENT_NAME=alpha "$INBOX_PUSH_BIN" beta hello) || push_rc=$?
[[ "$push_rc" -eq 2 && "$verdict" == "skip:pty-runner" && ! -e "$TMUX_LOG" ]] || exit 1

rm "$T/beta/.runner"
touch "$T/beta/.runner.lock"
push_rc=0
verdict=$(AGENT_NAME=alpha "$INBOX_PUSH_BIN" beta hello) || push_rc=$?
[[ "$push_rc" -eq 2 && "$verdict" == "skip:pty-runner" && ! -e "$TMUX_LOG" ]] || exit 1

rm "$T/beta/.runner.lock"
push_rc=0
verdict=$(AGENT_NAME=alpha "$INBOX_PUSH_BIN" beta hello) || push_rc=$?
[[ "$push_rc" -eq 2 && "$verdict" == "skip:no-window" && -s "$TMUX_LOG" ]]
); then
ok "Case 67: marker or lock skips tmux without the flag; no marker or lock keeps tmux"
else
fail "Case 67: PTY persist-only delivery"
fi
rm -rf "$T"
}

# ---------------------------------------------------------------------------
# Summary
# ---------------------------------------------------------------------------
Expand Down
48 changes: 48 additions & 0 deletions 10BC8 packages/base/test/multi-harness.test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,9 @@ printf '%s\n' "$*" >> "$TMUX_LOG"
case "$1" in
has-session) exit 1 ;;
list-windows) for d in "$AGENTS_HOME"/*/; do basename "$d"; done ;;
list-panes)
if grep -q '^send-keys -t agents:cobalt ' "$TMUX_LOG"; then echo node; else echo bash; fi ;;
capture-pane) printf 'OpenAI Codex\n\342\200\272 \n' ;;
esac
exit 0
STUB
Expand All @@ -213,6 +216,51 @@ ws_rc=$?
[[ "$ws_rc" -eq 0 && "$(sent_to cobalt)" == *" codex Enter" && "$(sent_to gale)" == *" agy --conversation gale-conv-1 Enter" && "$(sent_to claudia)" == *" claude "* ]] \
&& pass "W6 workspace run: each pane is sent its own runtime's command" || fail "W6 workspace run" "rc=$ws_rc $(cat "$TMUX_LOG")"

mkdir -p "$AGENTS_HOME/ptytest"
: > "$AGENTS_HOME/ptytest/SOUL.md"
: > "$AGENTS_HOME/ptytest/.auto-arm-watcher"
printf 'pty\n' > "$AGENTS_HOME/ptytest/.runner"
old_session=55555555-5555-4555-8555-555555555555
printf '%s\n' "$old_session" > "$AGENTS_HOME/ptytest/.session-id"
unset MC_PTY_RUNNER

for launcher in boot-agents.sh workspace.sh; do
: > "$TMUX_LOG"
out=$(PATH="$STUB_PATH" BOOT_STAGGER_SECS=0 BOOT_READY_SECS=1 WATCHER_ENABLED=0 \
bash "$BIN_DIR/$launcher" ptytest cobalt 2>&1)
rc=$?
if [[ "$rc" -eq 0 && "$out" == *"skipping ptytest (opted into the PTY runner)"* ]] &&
[[ "$(sent_to cobalt)" == *" codex Enter" && ! -e "$AGENTS_HOME/ptytest/.first-boot-done" ]] &&
[[ "$(cat "$AGENTS_HOME/ptytest/.session-id")" == "$old_session" ]] &&
! grep -qF ptytest "$TMUX_LOG"; then
pass "$launcher skips a PTY target without the flag but launches an unmarked target on tmux"
else
fail "$launcher PTY skip" "rc=$rc $out $(cat "$TMUX_LOG")"
fi

: > "$TMUX_LOG"
out=$(PATH="$STUB_PATH" bash "$BIN_DIR/$launcher" ptytest 2>&1)
rc=$?
if [[ "$rc" -eq 0 && "$out" == *"skipping ptytest"* && ! -s "$TMUX_LOG" ]]; then
pass "$launcher does not contact tmux when all targets opt in"
else
fail "$launcher PTY-only run" "rc=$rc $out $(cat "$TMUX_LOG")"
fi
done

rm "$AGENTS_HOME/ptytest/.runner"
touch "$AGENTS_HOME/ptytest/.runner.lock"
for launcher in boot-agents.sh workspace.sh; do
: > "$TMUX_LOG"
out=$(PATH="$STUB_PATH" bash "$BIN_DIR/$launcher" ptytest 2>&1)
rc=$?
if [[ "$rc" -eq 0 && "$out" == *"skipping ptytest"* && ! -s "$TMUX_LOG" ]]; then
pass "$launcher skips a locked target after its marker is removed"
else
fail "$launcher locked target" "rc=$rc $out $(cat "$TMUX_LOG")"
fi
done

provider_home="$AGENTS_HOME/cobalt/.codex-home"
exported_home="$BOX/exported codex"
mkdir -p "$provider_home/sessions" "$exported_home/sessions" "$HOME/.codex/sessions"
Expand Down
58 changes: 58 additions & 0 deletions packages/deck/app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { PassThrough } from "node:stream";
import { createReadableStreamFromReadable } from "@react-router/node";
import { isbot } from "isbot";
import { renderToPipeableStream } from "react-dom/server";
import { ServerRouter, type EntryContext } from "react-router";
import { runnerRegistry } from "./lib/runner/registry.server.js";

export const runnerLifecycle = {
recover: () => runnerRegistry.recover(),
shutdown: () => runnerRegistry.shutdown(),
};

export const streamTimeout = 5_000;

export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
routerContext: EntryContext,
) {
if (request.method.toUpperCase() === "HEAD") {
return new Response(null, { status: responseStatusCode, headers: responseHeaders });
}

return new Promise<Response>((resolve, reject) => {
let shellRendered = false;
const userAgent = request.headers.get("user-agent");
const readyOption = (userAgent && isbot(userAgent)) || routerContext.isSpaMode ? "onAllReady" : "onShellReady";
const timeout = setTimeout(() => abort(), streamTimeout + 1000);
const { pipe, abort } = renderToPipeableStream(
<ServerRouter context={routerContext} url={request.url} />,
{
[readyOption]() {
shellRendered = true;
const body = new PassThrough({
final(callback) {
clearTimeout(timeout);
callback();
},
});
responseHeaders.set("Content-Type", "text/html");
pipe(body);
resolve(new Response(createReadableStreamFromReadable(body), {
headers: responseHeaders, status: responseStatusCode,
}));
},
onShellError(error: unknown) {
clearTimeout(timeout);
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
if (shellRendered) console.error(error);
},
},
);
});
}
4 changes: 4 additions & 0 deletions packages/deck/app/lib/instance.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ export function tmuxEnabled(env: Env): boolean {
return !(v === "0" || v === "false");
}

export function ptyRunnerEnabled(env: Env): boolean {
return env["MC_PTY_RUNNER"] === "1";
}

/**
* Whether the agent-activity panel is exposed on this instance.
*
Expand Down
Loading
Loading
0