Skip to content

feat(sandbox): stop idle agent sandboxes from OSC 7501 program status - #5856

Draft
mrunalp wants to merge 16 commits into
ai-openshell:mainfrom
mrunalp:feat/5852-idle-stop/mrunalp
Draft

mrunalp wants to merge 16 commits into
ai-openshell:mainfrom
mrunalp:feat/5852-idle-stop/mrunalp

Conversation

@mrunalp

@mrunalp mrunalp commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Stop a sandbox whose coding agent has waited on the user longer than a configured timeout, and start it again on openshell sandbox connect. Agents such as Claude Code and Codex declare their state on their terminal with OSC 7501. The supervisor reads those reports from workload PTYs, applies the timeout itself, and proposes the stop to the gateway. This PR also adds the draft RFC 0025.

Related Issue

Closes #5852

Changes

  • Supervisor (openshell-supervisor-process, openshell-supervisor):
    • New program_status module that scans OSC 7501 reports in the canonical process output and in SSH PTY sessions, and keeps the protocol's per-terminal records.
    • Reports, OSC 133 prompts, and full resets (RIS) apply in output order, however reads split them. RIS clears the terminal's records.
    • Answers the support query itself with the full-form reply, so a program that probes with echo on does not loop, and removes the query from forwarded output. Report bytes pass through unchanged; msg and title are validated and then dropped.
    • Owns the idle clock: the configuration poller keeps the effective idle_stop_after_seconds current, and an idle reporter on each gateway session checks every second and on every summary change.
    • Once some program reports, none is working, and the later of the state change and the latest client input is older than the timeout, the reporter sends a SupervisorWorkloadIdle proposal. It repeats it with a new id every minute while the wait continues, and retracts it on input or a new turn.
    • The reporter sends from its own task, so a full outbound queue never stalls the session's receive loop.
  • Proto: SupervisorMessage.workload_idle = 7 (SupervisorWorkloadIdle), two enums, and SupervisorHello.supports_idle_proposals = 10. This is supervisor control traffic only. No public Sandbox, SandboxSpec, or SandboxStatus fields change, so the SDK's exhaustive-literal fixture still compiles, and the durable schema hash is unchanged.
  • Gateway (openshell-server):
    • Keeps each supervisor session's latest proposal in memory on the replica that holds the session. A proposal from a replaced session, or an older one from the current session, is dropped. Nothing is stored, so nothing stops after a restart or session change until the current session proposes.
    • A proposal starts one idle stop per sandbox through the ordinary stop path.
    • Before the Stopping write, under the lifecycle lock, each attempt requires:
      • the same session's proposal still held;
      • a Ready sandbox on the proposing instance;
      • the gateway's own effective timeout reached by the proposal's wait;
      • a fresh owner record naming the session.
    • After the write and before the driver call, it checks the proposal again. A retraction received in between rolls the sandbox back to its previous state. If that rollback loses a write race, the stop goes ahead like any in-flight stop.
    • An internal.openshell.ai/idle-stop marker survives recovery and settles the stop as IdleStopped, which is reapplied after driver snapshots of the stopped runtime. An explicit stop of an idle-stopped sandbox becomes an ordinary stop, including while the idle stop is still in flight on another replica.
    • The idle orchestration lives in compute/idle_stop.rs.
  • Settings: new registered int setting idle_stop_after_seconds. Unset, zero, or negative disables it; it is capped at 30 days, and gateway scope wins over sandbox scope as for every runtime setting.
  • CLI: sandbox connect starts an IdleStopped sandbox before connecting, first waiting for an in-flight idle stop (IdleStopping) to leave Stopping. It connects without a start if the sandbox came back Ready or Starting. An explicitly stopped sandbox keeps the existing error.
  • Docs and RFC: a "Stop Idle Sandboxes" section in the sandbox overview, crate README notes, and rfc/0025-workload-idle-stop/README.md. Showing program status to clients is a non-goal for this change; the RFC keeps a separate status record as the open option.

Release Notes

Set idle_stop_after_seconds to stop a sandbox after its coding agent has waited on you that long. openshell sandbox connect starts it again. Agents that report OSC 7501 program status, such as Claude Code and Codex, are supported; sandboxes whose programs never report are never stopped.

Testing

  • Checks appropriate to the affected code and behavior pass:
    • cargo fmt --check, including the conformance workspace
    • cargo clippy --all-targets -D warnings for core, supervisor-process, supervisor, server, cli, and sdk
    • cargo test for core, supervisor-process, supervisor, server, cli, and sdk
    • markdown lint
  • Unit tests added/updated:
    • OSC 7501 parsing, chunk splits, limits, record semantics, and probe replies
    • wire order for every chunking, RIS, report counting, and input surviving terminal close
    • the idle rule: only a wait past the timeout with no input and no working program
    • the reporter proposing, repeating with new ids, retracting on input and on a new turn, and proposing again
    • a proposal stopping the sandbox with IdleStopped, kept after an exited-container snapshot and cleared by a start
    • the gateway timeout and a disabled setting declining a proposal
    • ordering: repeats, older proposals, retractions of earlier ids, replaced sessions, and supervisors without the capability
    • a retraction or takeover before the write cancelling the stop
    • a retraction after the Stopping write restoring the sandbox
    • a forced write conflict readmitting the stop
    • overlapping stops, an explicit stop after a settled or in-flight idle stop, and an in-flight idle stop's reason through driver snapshots
    • CLI: connect during IdleStopping when the watch reports Ready, Starting, or IdleStopped
  • E2E tests added/updated:
    • New conformance test idle_stop::idle_stopped_sandbox_wakes_on_connect_until_stopped_explicitly. It checks that idle stop then sandbox connect starts the sandbox, and that idle stop, explicit stop, then sandbox connect leaves it stopped.
    • With a rebuilt supervisor image, it passes together with the attach, cli, ssh, exec_cli, and lifecycle suites against a local Docker gateway: 21 of 21.
  • Claude Code 2.1.327 and Codex 0.170.0 were run through the scanner on a host PTY. Both report working/done per turn and blocked:kind=permission at approval prompts.
  • Codex 0.172.0 ran inside a Docker sandbox against this branch, with an OpenAI API key provider and idle_stop_after_seconds=30. After a one-prompt turn, the gateway logged Stopped idle sandbox ... program=codex state=Done, and the sandbox settled as IdleStopped. sandbox connect started it again, and the restarted Codex was idle-stopped a second time. Codex needed TMPDIR set inside the sandbox, because its SQLite state otherwise fails on the read-only /var/tmp; that's unrelated to idle stop.
  • Claude Code 2.1.331 ran the same way, with the claude-code provider profile carrying an Anthropic API key. Its turn reached POST /v1/messages through the provider policy and answered "OK". The gateway logged Stopped idle sandbox ... program=claude-code state=Done for both idle stops, before and after a sandbox connect wake.

Checklist

  • Follows Conventional Commits
  • Commits are signed off (DCO)
  • Architecture docs updated (if applicable)

Draft an RFC for stopping sandboxes whose terminal program reports over
OSC 7501 that it is waiting on the user, and starting them again on
connect. Maintainers assign the RFC number from the originating issue.

Refs ai-openshell#5852

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Coding agents such as Claude Code and Codex report on their terminal
whether they are working, done, or blocked on the user. The supervisor
now scans workload PTY output for these reports, answers the support
query itself, and reports a sandbox-wide summary to the gateway over the
supervisor session.

The gateway records the latest report as a ProgramStatus condition. With
the idle_stop_after_seconds runtime setting, it stops a sandbox whose
program has waited on the user past the timeout and settles it as
IdleStopped. openshell sandbox connect starts an idle-stopped sandbox
before connecting. Idle stop is off unless the setting is set, and the
public Sandbox messages are unchanged.

Closes ai-openshell#5852

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
@github-actions github-actions Bot added the state:accepted A maintainer decided OpenShell should pursue this issue label Nov 20, 2026
Run rustfmt on the conformance workspace and remove semicolons from the RFC's Mermaid labels, which Mermaid parses as statement separators.

Refs ai-openshell#5852

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Review found cases where a running sandbox could be stopped: recent
input lost to throttling, a lost Working write, a restored condition
after a gateway restart, a stale timeout, and an explicit stop that a
later connect undid.

The gateway now decides idleness only from the latest report of the
sandbox's current supervisor session, kept in memory on the replica
that holds it, with exact input time. Every replica sweeps its own
sessions, and nothing stops until the current session reports. The
stored ProgramStatus condition is display-only and retries write
conflicts. The stop re-reads the live report and the setting under the
lifecycle lock and waits out a 15-second input report lag. An explicit
stop of an idle-stopped sandbox becomes an ordinary stop.

The supervisor reports input within seconds, keeps the latest input
after a terminal closes, applies reports, prompts, and full resets in
output order, clears records on RIS, and counts terminals with a
current report.

Refs ai-openshell#5852

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Re-review found that a stop could still be decided from a report that
was already stale: input since the supervisor's last poll, a Working
report racing admission, or a session that another replica had taken
over. An explicit stop during an in-flight idle stop could also settle
as IdleStopped.

Before committing an idle stop, the gateway now sends a
WorkloadActivityRequest over the current session and requires a fresh
due report within 5 seconds. Only supervisors that advertise
supports_workload_activity_requests are idle-stopped. Admission also
requires the shared owner record to name the session, and holds an
activity gate across the final check and the Stopping write. Every live
report update takes the same gate. An explicit stop on the in-flight
retry path drops the idle intent.

The supervisor notes every transition while it applies a read's events,
so a turn within one read restarts the timer. It publishes summaries
under the activity lock with a revision that advances on each
transition, so concurrent terminals cannot suppress a notification.

Refs ai-openshell#5852

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Third review found four races between the supervisor's confirmation
snapshot and the Stopping write: the session reader could block on the
sandbox lock behind a stop, a write conflict kept a global gate across
a second confirmation, a takeover could slip past a local session
check, and an older confirmation could overwrite a newer push.

The stop task now confirms before taking any lifecycle lock. Under the
lock, each Stopping attempt requires a confirmation at most 2 seconds
old, the re-read setting, a still-due live report from the confirming
session, and a fresh owner record naming it. It holds a per-sandbox
activity gate for that attempt only. Display persistence moves to a
background task, so recording a report never waits on the sandbox lock.

The supervisor serializes snapshot and enqueue for pushes and replies
and stamps each summary with an increasing sequence. The gateway drops
an older summary from the same session. The RFC states the remaining
stop boundary.

Refs ai-openshell#5852

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Fourth review found that the confirmation's 2-second freshness was
checked before the final check's waits, so a slow owner read could
admit a stop with an older confirmation. It also found that a former
owner's delayed display write could overwrite the new owner's status,
and that every report spawned its own display task.

The final check now runs every wait under the confirmation's deadline,
and the deadline is checked again just before the Stopping write is
issued. Display writes coalesce behind one writer per sandbox. Each
attempt rereads the newest live report and is fenced to the session the
shared owner record names. The RFC states report ordering in terms of
the activity gate.

Refs ai-openshell#5852

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Fifth review found that the confirmation deadline started when the stop
task resumed rather than when the reply reached the report handler, so
scheduling delay extended it. It also found that a display write checked
ownership before reading the sandbox, so a takeover between the two let
a former owner overwrite the new owner's status.

The report handler now captures a monotonic arrival time and sends it
through the confirmation waiter, and the deadline derives from it. Each
display write attempt reads the versioned sandbox, then checks
ownership, then writes conditionally on that version, so any later
status write forces a retry with a fresh ownership check.

Refs ai-openshell#5852

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Architecture review found that a superseded session's late report could
displace its replacement's live report, that overlapping sweeps shared
one confirmation slot per sandbox, and that connecting during an
in-flight idle stop failed instead of waking the sandbox.

Recording a report now re-checks the session under the activity gate,
and a replaced session's reply wakes no waiter. The confirmation
travels with its own stop attempt as QuiesceCause::Idle, and a
per-sandbox in-flight guard runs one idle stop at a time. The gateway
keeps the IdleStopping reason through driver snapshots, and sandbox
connect waits for the stop to finish before starting the sandbox.

The docs and RFC state that a waiting report covers only its own
program, and record the review's remaining architecture questions.

Refs ai-openshell#5852

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Re-review found that connect during IdleStopping waited strictly for
Stopped. A stop that rolled back to Ready, or a sandbox another client
had already restarted, never reaches Stopped, so connect waited for the
full lifecycle timeout.

Connect now waits until the sandbox leaves Stopping. It connects to a
Ready sandbox, waits for Ready from Starting, and starts the sandbox only
when it settled as IdleStopped, printing one notice. The lifecycle watch
loop is shared between both waits.

Refs ai-openshell#5852

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Rename the draft from its placeholder number and link its pull request.

Refs ai-openshell#5852

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Program status reports no longer write the sandbox record. GetSandbox
and each WatchSandbox snapshot attach the owning replica's live report
as the ProgramStatus condition while the sandbox is Ready, and a replica
without the session reads it from the owner over the peer-only
PeerGetSandboxProgramStatus RPC, bounded to 2 seconds. A change of
state, blocked kind, or app notifies local watchers.

This removes the display writer, its owner fencing and conflict
retries, condition merging, snapshot preservation, and the phase-change
clearing in set_phase. The supervisor now sends input-only reports only
while the program waits on the user.

ListSandboxes and watchers on other replicas do not show the condition;
the RFC records this as a risk and an open question.

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Record storing ProgramStatus in its own object, merged on read, as an
open future option for cross-replica visibility, and update the
implementation plan for the read-time condition.

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
…ification

The first ProgramStatus change notifies watchers at once and opens a
2-second window. Further changes inside it collapse into one
notification at its end, so flips such as working, blocked, working cost
at most one watch read per window. Notifications go only to sandboxes
that already have watchers, so a late one never recreates a bus entry
for a deleted sandbox.

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
Idle stop decides from the owning replica's live report and never needed
the ProgramStatus condition. Showing it had uneven visibility:
ListSandboxes never carried it, watchers on other replicas saw no
updates, and each of their watch events cost a peer call.

Remove the read-time condition, the PeerGetSandboxProgramStatus RPC, its
routed-request metric, and the watch notification window. The RFC lists
showing status to clients as a non-goal and keeps a separate status
record as the open option. The conformance test now waits for the idle
stop directly.

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>
The supervisor now applies the sandbox's effective idle_stop_after_seconds
itself. Once a program has waited on the user, with no client input, past
the timeout, it sends a SupervisorWorkloadIdle proposal, repeats it each
minute while the wait continues, and retracts it on input or a new turn.
The setting reaches it through the configuration poller.

The gateway keeps the session's latest proposal and stops the sandbox
through the ordinary stop path. Before the Stopping write it checks the
proposal, the sandbox's phase and instance, its own effective timeout,
and the owner record. After the write and before the driver call it
checks the proposal again and rolls the sandbox back to its previous
state if a retraction arrived.

This removes the gateway's 30-second sweep, the input report lag, the
summary sequence numbers, the confirmation round trip and the per-sandbox
activity gate, which made the session's receive loop wait on a store
write. The idle reporter sends from its own task, so a full outbound
queue no longer stalls the receive loop. The two explicit-stop retry
blocks share one helper, and the idle orchestration moves into
idle_stop.rs.

Signed-off-by: Mrunal Patel <mrunalp@gmail.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state:accepted A maintainer decided OpenShell should pursue this issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: stop idle agent sandboxes using OSC 7501 program status

1 participant