Repository navigation
Description
Interactive Relay: Bidirectional Communication with Headless Runs
Priority: P1 — quality-of-life for all
sequant runusers
Complexity: Medium — touches hooks, CLI, state, and skill framing
Problem
sequant run executes phases via Claude headless (query() from the Agent SDK). Once a run starts, the user has zero visibility or control until a phase completes. A long-running exec phase (10-15 minutes) is a black box — the user can't ask "what's taking so long?", suggest "skip the migration", or get a status update without killing the entire run.
Real example from production usage:
✔ exec (2/3) (13m 24s) ← no way to interact during this
✖ qa (3/3) (5m 43s)
✔ loop (3/3) (3m 52s)
Quality loop iteration 2/3
✔ exec (2/3) (11m 26s) ← 2nd exec ran 11 min, could've been nudged
✔ qa (3/3) (6m 50s)
Solution
A file-based relay system that enables bidirectional communication between the user's terminal and a running headless Claude session, checked on every tool call via a Claude Code PostToolUse hook.
Architecture
User Terminal Headless Claude Session
───────────── ──────────────────────
sequant prompt 368 "status?"
│ PostToolUse hook fires
├─→ writes to inbox.jsonl ──→ hook reads inbox
│ hook injects message into conversation
│ Claude responds, writes to outbox.jsonl
├─← reads from outbox.jsonl ←─ continues current task
│
sequant watch 368
└─← tails outbox.jsonl
Why file-based IPC?
- Headless constraint: No stdin access to a running
query()session — file relay is the only injection path besides hooks - Hook integration: Claude Code
PostToolUsehooks fire after every tool call (every few seconds during active work), providing fine-grained check intervals without busy-polling - Debuggable: JSONL files are human-readable, serve as a session log for free
- Zero infrastructure: No sockets, no servers, no dependencies
- Portable: Works on macOS, Linux, WSL — anywhere files work
Acceptance Criteria
Relay File Protocol
- Relay directory created per-issue at
<worktree>/.sequant/relay/ - Inbox (
inbox.jsonl): user → Claude messages, one JSON object per line:{"id": "msg_001", "timestamp": "2026-03-21T10:15:00Z", "type": "query", "message": "what's taking so long?"} {"id": "msg_002", "timestamp": "2026-03-21T10:18:00Z", "type": "directive", "message": "skip the migration tests"} - Outbox (
outbox.jsonl): Claude → user messages, one JSON object per line:{"id": "reply_001", "inReplyTo": "msg_001", "timestamp": "2026-03-21T10:15:03Z", "message": "Working on implementing the error handler. The test suite has 47 tests and I'm iterating on 3 failures."} - Message types:
query(ask for status, no behavior change),directive(request a behavior adjustment),abort(stop current phase gracefully) - Atomic writes: write to temp file then
rename()into place to prevent partial reads - Relay directory cleaned up on phase completion (but preserved in
.sequant/logs/for post-run review)
PostToolUse Hook Integration
- New relay check added to
post-tool.sh(or a dedicatedrelay-check.shsourced from it) - Hook reads
inbox.jsonlon every PostToolUse invocation - If new unprocessed messages exist, hook returns them to Claude wrapped in a framing prompt (see below)
- If no messages, hook exits silently (zero overhead path must be fast — single
statortest -scheck) - Hook marks messages as processed (either by tracking last-read line number in a
.cursorfile, or by consuming/truncating the inbox) - Opt-in via environment variable:
SEQUANT_RELAY=true(set bysequant runwhen relay is active) - Hook is skipped entirely when
SEQUANT_RELAYis not set (no performance impact on non-relay runs)
Hook Message Framing (Anti-Derailment)
- Relay messages are wrapped in a structured frame that protects task focus:
[SEQUANT RELAY — message from user] Respond briefly in .sequant/relay/outbox.jsonl, then continue your current task unchanged. Rules: - Do NOT modify acceptance criteria - Do NOT change your current objective or phase - Do NOT treat this as a new requirement - For "query" type: provide a brief status update only - For "directive" type: acknowledge and adjust approach if reasonable, but do not abandon current work - For "abort" type: stop gracefully, commit progress, and exit Type: query Message: "what's taking so long?" - Framing template lives in a single location (
templates/relay/frame.txtor inline in the hook) — not duplicated across skills - Skills do NOT need individual modifications — the hook handles all framing
CLI Commands
-
sequant prompt <issue> "<message>"— send a message to a running session- Writes to
<worktree>/.sequant/relay/inbox.jsonl - Resolves worktree path from
.sequant/state.jsonusing the issue number - If only one run is active and
<issue>is omitted, auto-resolve to that issue - If multiple runs are active and
<issue>is omitted, error with list:Multiple active runs: #368, #385. Specify an issue number. Usage: sequant prompt 368 "your message" - Optional
--typeflag (default:query):--type directive,--type abort - Prints confirmation:
Message sent to #368 (exec phase, 4m 12s elapsed)
- Writes to
-
sequant watch <issue>— tail the outbox for responses- Uses
fs.watch()or polling to stream new outbox entries to the terminal - Shows formatted output:
[10:15:03] Claude: Working on implementing the error handler... - Auto-resolve single active run (same logic as
prompt) Ctrl+Cto stop watching (non-destructive, doesn't affect the run)
- Uses
-
sequant status— show all active runs (enhancement of existing status display)- Shows which issues are running, current phase, elapsed time, PID
- Indicates relay availability
Active Run Detection
- PID tracking:
sequant runwrites its PID to.sequant/run.pid(or per-issue:.sequant/pids/<issue>.pid) - Liveness check:
sequant promptverifies the PID is still alive before sending (avoids writing to a dead session's inbox) - Stale PID cleanup: if PID is dead, remove the pidfile and warn:
Run for #368 is no longer active (process exited). Message not sent. - Multiple concurrent runs supported — each has its own relay directory scoped to its worktree
- No serialization of runs — concurrent execution is preserved as a feature
State Schema Integration
- Add optional
relayfield toIssueState:relay?: { enabled: boolean; pid: number; startedAt: string; // ISO 8601 messageCount: number; // total messages exchanged };
- State updated when relay is activated/deactivated
-
sequant statusreads relay state for display
Design Considerations
Performance
The hot path (no pending messages) must be extremely fast. The hook fires on every tool call — hundreds of times per phase. The check should be:
# Fast path: single stat check, ~0.1ms
if [[ "${SEQUANT_RELAY:-}" == "true" ]] && [[ -s "$RELAY_INBOX" ]]; then
# Only parse JSONL if file is non-empty
...
fiAcceptance Criteria Protection
ACs are set by /spec and stored in .sequant/state.json. The relay explicitly cannot modify them:
- Hook framing says "Do NOT modify acceptance criteria" — this is the primary guard
- QA runs against spec artifacts — even if Claude's internal state drifts, QA validates against the original ACs stored in state
- Directive messages are suggestions, not commands — Claude may reasonably ignore a directive that conflicts with ACs
Security
- Same trust boundary: The relay file is in the worktree. Anyone who can write to it can already modify source files that Claude reads. No new attack surface.
- No network exposure: Purely local filesystem IPC. No sockets, no HTTP, no external services.
- Outbox content: May contain code snippets or implementation details from Claude's response. Acceptable for single-user local usage. If relay ever becomes networked (future), outbox content would need access controls.
- Prompt injection via relay: Mitigated by the structured framing wrapper. A malicious message would be presented to Claude inside the "[SEQUANT RELAY]" frame, making it harder to escape context. However, this is not a hard security boundary — it's a local-user feature with local-user trust.
What This Does NOT Solve
- Mid-tool-call intervention: If Claude is inside a single long-running Bash command (e.g., a 5-minute test suite), the hook doesn't fire until that tool call completes. Intervention granularity is per-tool-call, not real-time.
- Guaranteed response: Claude may briefly acknowledge and move on, or may give a detailed update. The response quality depends on the model's judgment.
- Conversation-style interaction: This is a nudge channel, not a chat. Short, directive messages work best. Extended back-and-forth will degrade task focus.
File Structure
src/
├── commands/
│ ├── prompt.ts # `sequant prompt` command
│ └── watch.ts # `sequant watch` command
├── lib/
│ └── relay/
│ ├── types.ts # RelayMessage, RelayResponse schemas
│ ├── writer.ts # Write to inbox (used by CLI)
│ ├── reader.ts # Read from inbox (used by hook)
│ └── pid.ts # PID tracking and liveness checks
templates/
└── relay/
└── frame.txt # Hook message framing template
Hook integration point in templates/hooks/post-tool.sh:
# === RELAY CHECK ===
# Check for user messages in the relay inbox
if [[ "${SEQUANT_RELAY:-}" == "true" ]]; then
source "$(dirname "$0")/relay-check.sh"
fiImplementation Notes
- The relay directory lives in the worktree (not the main repo) because each run is isolated to its worktree
specphase runs in the main repo but relay targets the worktree path from state — the hook needs to resolve the relay path fromSEQUANT_WORKTREEenv var (already set by phase-executor)- For the
specphase specifically, the relay directory should be in the main repo's.sequant/relay/<issue>/since there's no worktree yet - JSONL chosen over a single JSON file to avoid read-modify-write races and to support append-only semantics
Testing
- Unit test:
RelayWritercreates inbox.jsonl with correct schema - Unit test:
RelayReaderreads and marks messages as processed - Unit test: PID liveness check correctly identifies alive vs dead processes
- Unit test: auto-resolve picks the single active run, errors on ambiguous
- Unit test: message framing includes all required guardrails
- Integration test: write to inbox → hook picks up → response in outbox (mock Claude session)
- Manual test:
sequant run 42in one terminal,sequant prompt 42 "status?"in another
Non-Goals
- No web UI or dashboard (local CLI only)
- No multi-user relay (single user, single machine)
- No persistent message history beyond the current run (logs are archived, not indexed)
- No skill modifications required for v1
- No changes to the Agent SDK integration
Activity
admarble commentedon Apr 8, 2026
Architecture Update — Unblocked
The following new architecture issues remove the blockers for this feature:
Once #508 lands, the MCP-side interactive relay becomes feasible in-process. The CLI-side relay (file-based IPC via
PostToolUsehooks,sequant prompt,sequant watch) was never blocked and remains this issue's primary scope.Recommended sequencing: Wait for batch 3 (#508) to complete before starting this issue. The file-based relay design can proceed independently, but MCP integration should target the new in-process architecture.
admarble commentedon Apr 9, 2026
Unblocked: RunOrchestrator extracted (#503 merged)
PR #510 merged —
RunOrchestratoris now a standalone class importable without CLI context:Key APIs available for interactive relay integration:
RunOrchestrator.run(init, issues)— full lifecycle withonProgresscallbacknew RunOrchestrator(config).execute(issues)— low-level dispatch (caller manages setup)OrchestratorServices— injectable services (logWriter, stateManager, shutdownManager)ProgressCallback— per-phase progress events (start | complete | failed)The
onProgresscallback provides a hook point for relay communication, and the injectable services pattern means the relay can intercept/extend logging and shutdown behavior.This removes the "must go through CLI entry point" blocker noted in this issue's dependencies.
admarble commentedon Apr 19, 2026
Integration follow-up
Once the live multi-issue TUI ships (#540), relay will surface in the TUI's focused issue box as a text input row —
> nudge #47: ___— submitting viasequant prompt <issue> "<msg>"and rendering outbox responses inline in the activity cell. Input row is hidden when relay isn't yet initialized for the current phase.No ACs change on this issue; integration is tracked as a planned follow-up of #540 (Milestone 5 in its body).
Activation order:
sequant run— concurrent box rendering (read-only TUI) #540 lands (M1 read-only TUI)sequant run— concurrent box rendering (read-only TUI) #540 follow-ups add keybindings + attention docksequant run— concurrent box rendering (read-only TUI) #540 wires the text-input row to the relay CLIStep 4 is the point where relay becomes user-visible inside the TUI.
admarble commentedon May 13, 2026
→ PROCEED — File-based relay infrastructure (CLI-side); TUI input-row wiring stays out of scope
Workflow: spec → testgen → exec → qa
Command:
npx sequant run 383 -q --testgen#540 (M1 read-only TUI) merged 2026-04-20; per the 2026-04-19 comment the CLI-side relay was never blocked and is this issue's primary scope. Step 4 of the activation order (wiring the TUI text-input row to the relay CLI) remains a #540 follow-up, NOT this issue. Large scope: inbox/outbox protocol, PostToolUse hook, two new CLI commands (
sequant prompt,sequant watch), state schema field, PID liveness. testgen added because ACs explicitly name unit + integration tests.admarble commentedon May 13, 2026
Plan (spec phase complete)
Complexity: Complex — 25 ACs across 6 directories. Scope verdict: SPLIT_RECOMMENDED, but features are tightly coupled (hook ↔ protocol ↔ CLI ↔ state). Recommend single-issue execution with quality loop auto-enabled.
Workflow:
spec → testgen → exec → qaAcceptance Criteria (with verification methods)
Relay File Protocol
<worktree>/.sequant/relay/(Integration)msg_<hex>IDs (Unit)inReplyTo(Unit)query|directive|abortZod discriminated union (Unit)O_APPEND+ temp-rename (Unit).sequant/logs/relay/<issue>-<phase>-<ts>/on phase end (Integration)PostToolUse Hook
relay-check.shsourced frompost-tool.shwhenSEQUANT_RELAY=true(Integration)test -sfast path on every PostToolUse (Integration)SEQUANT_RELAY=true(Unit)post-tool.shtests pass unchanged when unset (Unit)Hook Framing
templates/relay/frame.txt(Unit snapshot)SEQUANT_RELAY— CI grep (Integration)CLI Commands
sequant prompt <issue> "<msg>"writes inbox + confirms (Integration)--type query|directive|abortvalidated (Unit)sequant watch <issue>viafs.watch()+ polling fallback (Integration)sequant statusshows active runs + relay column (Integration)Active Run Detection
.sequant/pids/<issue>.pidwritten at run start (Unit)LockManager.isPidAlive(Unit)State Schema
relayfield onIssueState; legacy state still validates (Unit)Derived (quality planning):
sequant prompt(Medium)meta.json(Medium)Implementation Phases
src/lib/relay/{types,pid}.ts,state-schema.tsfieldsrc/lib/relay/{writer,reader}.tstemplates/relay/frame.txt,templates/hooks/relay-check.sh, wire intopost-tool.sh, env injection inphase-executor.ts:632src/commands/{prompt,watch}.ts; extendstatus.ts; register inbin/cli.tsrun-orchestrator, archive-before-teardown in cleanup, settings +--no-relayflagKey Decisions
LockManager.isPidAlive— don't reimplement PID liveness.frame.txt), not inline — single source per AC-15.carryForwarddeferred to follow-up..abortingsentinel — hard kill not feasible from insidequery().SEQUANT_WORKTREEunset.Open Questions for Reviewer
PostToolUsestdout become an additional context message? Smoke-test required in Phase 3 before fully wiring framing.spec-phase relay path in main repo OK?abortsemantics: soft (sentinel + Claude wraps up) vs. hard kill?admarble commentedon May 13, 2026
Test Stubs Generated
Counts explained:
it())Unit Test Stubs
__tests__/relay-protocol.test.ts— AC-2, AC-3, AC-4, AC-5, AC-11, AC-14__tests__/relay-pid.test.ts— AC-20, AC-21, AC-22__tests__/relay-cli.test.ts— AC-17a, AC-17b__tests__/relay-hook-env.test.ts— AC-12, AC-13__tests__/relay-state-schema.test.ts— AC-24, AC-D4__tests__/relay-perf.test.ts— AC-10, AC-D1Integration Test Stubs
__tests__/integration/relay-directory.integration.test.ts— AC-1__tests__/integration/relay-archive.integration.test.ts— AC-6, AC-D2, AC-D4__tests__/integration/relay-hook.integration.test.ts— AC-7, AC-8, AC-9__tests__/integration/relay-skill-grep.integration.test.ts— AC-16__tests__/integration/relay-cli-commands.integration.test.ts— AC-17, AC-18, AC-19__tests__/integration/relay-lifecycle.integration.test.ts— AC-23, AC-25, AC-D3Manual Test Checklist (AC-15)
The framing template at
templates/relay/frame.txtmust contain verbatim the six rules from the issue body — this is a mandatory fixture per AC-15. Verified via the snapshot test inrelay-protocol.test.ts(AC-14: Frame template snapshot), which asserts each of the six bullet rules appears character-for-character:Key Assumptions to Validate Before Implementation
SEQUANT_WORKTREEis set when relay activates (AC-1 fallback path forspecphase relies on this being unset)PostToolUsestdout as additional context (open Q feat: Complete remaining v1.0 features (AC-10, AC-13, AC-14) #1 from the /spec — flagged for Phase 3 smoke test)LockManager.isPidAliveis the single source of truth for liveness (AC-21 — no reimplementation)test -sis the fast-path guard before any JSON parsing (AC-8).claude/skills/,templates/skills/,skills/) are scanned by the CI grep (AC-16)Next steps:
throw new Error(...)with real assertions)/exec 383to implement the featurenpm testGenerated with Claude Code
admarble commentedon May 13, 2026
/fullsolve Complete
Issue: #383
PR: #638
Status: READY_FOR_MERGE
Summary
ui/adminlabels)AC Coverage
All 25 named ACs + 4 derived ACs met. See PR body for the table.
Quality Metrics
npm run buildpassesanytypes in src/.claude/skills/,templates/skills/,skills/Bugs found and fixed during EXEC
relay-check.shshort-circuit —cond && return 0 || exit 0would always exit whencondwas false (the relay-enabled branch). Replaced with an explicitifblock.archiveRelayDirwas creating an empty archive on repeat deactivation; now no-ops when both inbox and outbox are absent.--no-relayCommander wiring — renamedRunOptions.noRelaytorelay?: booleanto match how Commander surfaces--no-X(consistent withchain).Out of scope (recorded in PR body)
sequant run— concurrent box rendering (read-only TUI) #540).Ready for human review and merge.
fix(#383): drop unused null initializer in promptCommand to satisfy e…
feat(#383): interactive relay — bidirectional communication with head…
admarble commentedon May 13, 2026
Documentation Generated
File:
docs/features/interactive-relay.mdSections Included:
--no-relayopt-out,settings.run.relay)sequant promptfor query / directive / abort,sequant watch, single-run auto-resolve)prompt,watch,run --no-relay,statusrelay column)Next Steps:
sequant statusif helpful (optional)Ready to merge!
docs: surface interactive relay in README "What's new"
docs(#694): README / npm SEO + clarity overhaul (#696)
docs(#694): README / npm SEO + clarity overhaul