Skip to content
Merged
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
51 changes: 51 additions & 0 deletions CONTEXT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# agent-tty

`agent-tty` manages long-lived terminal sessions and preserves enough state to inspect, replay, and clean them up safely.

## Language

**Session**:
A long-lived PTY-backed terminal instance owned by `agent-tty`.

**Session Status**:
The lifecycle state of a **Session**: `running`, `exiting`, `exited`, `failed`, `destroying`, or `destroyed`.

**Active Session**:
A **Session** whose host-side lifecycle may still be in progress.

**Terminal Session**:
A **Session** whose host-side lifecycle has reached a final persisted state.
_Avoid_: Finished session

**Commandable Session**:
A **Session** that can still accept user input and control commands.

**Live Host Eligible Session**:
A **Session** where callers should ask the live session host for fresh state.

**Offline Replay Eligible Session**:
A **Session** where callers should reconstruct renderer state from persisted replay data.

**Collectable Session**:
A **Terminal Session** whose persisted directory may be removed by garbage collection.
_Avoid_: Deletable session

**Destroyed Status Check**:
A convenience policy predicate for the single `destroyed` **Session Status** value. It is not a separate lifecycle classification.

## Relationships

- A **Session** has exactly one **Session Status** at a time.
- A `running` **Session** is **Active**, **Commandable**, and **Live Host Eligible**.
- An `exiting` **Session** is **Active** and **Live Host Eligible**, but not **Commandable**.
- A `destroying` **Session** is **Active** and **Offline Replay Eligible**, but not **Terminal** or **Collectable**.
- `exited`, `failed`, and `destroyed` **Sessions** are **Terminal**, **Offline Replay Eligible**, and **Collectable**.
Comment thread
ThomasK33 marked this conversation as resolved.

## Example dialogue

> **Dev:** "Can garbage collection remove a **destroying** **Session**?"
> **Domain expert:** "No. It is still an **Active Session**, even though renderer inspection should use **Offline Replay** instead of the live host."

## Flagged ambiguities

- "Active" and "offline replay eligible" are independent classifications: `destroying` is both **Active** and **Offline Replay Eligible**.
26 changes: 13 additions & 13 deletions src/cli/commands/gc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import type { CommandContext } from '../context.js';
import { emitSuccess } from '../output.js';
import { reconcileSession } from '../../host/lifecycle.js';
import { ERROR_CODES, makeCliError } from '../../protocol/errors.js';
import {
isCollectableSessionStatus,
isTerminalSessionStatus,
} from '../../protocol/sessionStatusPolicy.js';
import type { SessionRecord } from '../../protocol/schemas.js';
import { readManifestIfExists } from '../../storage/manifests.js';
import { manifestPath, sessionDir } from '../../storage/sessionPaths.js';
Expand Down Expand Up @@ -142,9 +146,10 @@ function wasReconciledFromStaleHost(
manifestBefore: SessionRecord,
manifestAfter: SessionRecord,
): boolean {
const isTerminal = (s: string): boolean =>
s === 'exited' || s === 'failed' || s === 'destroyed';
return !isTerminal(manifestBefore.status) && isTerminal(manifestAfter.status);
return (
!isTerminalSessionStatus(manifestBefore.status) &&
isTerminalSessionStatus(manifestAfter.status)
);
}

function shouldSkipForAge(
Expand Down Expand Up @@ -335,11 +340,7 @@ export async function gcSessions(
}

const sessionId = manifestAfter.sessionId;
const isTerminalAfter =
manifestAfter.status === 'exited' ||
manifestAfter.status === 'failed' ||
manifestAfter.status === 'destroyed';
if (!isTerminalAfter) {
if (!isCollectableSessionStatus(manifestAfter.status)) {
result.skippedSessions.push({
sessionId,
reason: 'session host is still alive',
Expand Down Expand Up @@ -384,11 +385,10 @@ export async function gcSessions(
continue;
}

const isFinalTerminal =
finalManifest?.status === 'exited' ||
finalManifest?.status === 'failed' ||
finalManifest?.status === 'destroyed';
if (finalManifest !== null && !isFinalTerminal) {
if (
finalManifest !== null &&
!isCollectableSessionStatus(finalManifest.status)
) {
result.skippedSessions.push({
sessionId,
reason: 'session restarted between check and delete',
Expand Down
37 changes: 13 additions & 24 deletions src/cli/commands/inspect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ import type { CommandContext } from '../context.js';
import { countEventLogEntries } from '../../host/eventLog.js';
import { reconcileSession } from '../../host/lifecycle.js';
import { sendRpc } from '../../host/rpcClient.js';
import {
isCommandableSessionStatus,
isLiveHostEligibleSessionStatus,
isOfflineReplayEligibleSessionStatus,
} from '../../protocol/sessionStatusPolicy.js';
import { deriveTerminationCategory } from '../../protocol/terminationCategory.js';
import { ERROR_CODES, makeCliError } from '../../protocol/errors.js';
import { emitSuccess } from '../output.js';
Expand All @@ -32,8 +37,10 @@ interface CommandOptions {

function computeUptime(session: SessionRecord): number {
const createdAt = Date.parse(session.createdAt);
const endAt =
session.status === 'running' ? Date.now() : Date.parse(session.updatedAt);
// Matches pre-existing behavior: only running sessions show live uptime.
const endAt = isCommandableSessionStatus(session.status)
Comment thread
ThomasK33 marked this conversation as resolved.
? Date.now()
: Date.parse(session.updatedAt);

return Math.max(0, endAt - createdAt);
}
Expand All @@ -54,23 +61,6 @@ function formatArtifactKinds(byKind: Record<string, number>): string {

const RENDERER_BACKEND = 'ghostty-web';

function usesOfflineReplay(sessionStatus: SessionStatus): boolean {
switch (sessionStatus) {
case 'running':
case 'exiting':
return false;
case 'exited':
case 'failed':
case 'destroying':
case 'destroyed':
return true;
default: {
const exhaustiveStatus: never = sessionStatus;
throw new Error(`unexpected session status: ${String(exhaustiveStatus)}`);
}
}
}

function deriveRendererRuntimeSummary(options: {
usedOfflineReplay: boolean;
sessionStatus: SessionStatus;
Expand All @@ -84,7 +74,7 @@ function deriveRendererRuntimeSummary(options: {
};
}

if (usesOfflineReplay(options.sessionStatus)) {
if (isOfflineReplayEligibleSessionStatus(options.sessionStatus)) {
return {
backend: RENDERER_BACKEND,
mode: 'offline-replay',
Expand Down Expand Up @@ -146,8 +136,7 @@ function formatSessionLines(result: InspectResult): string[] {
);

if (
session.status !== 'running' &&
session.status !== 'exiting' &&
!isLiveHostEligibleSessionStatus(session.status) &&
result.terminationCategory !== undefined
) {
lines.push(`Termination: ${result.terminationCategory}`);
Expand Down Expand Up @@ -181,8 +170,8 @@ export async function runInspectCommand(
});
}

const isOffline = usesOfflineReplay(session.status);
if (!isOffline) {
const isLiveHostEligible = isLiveHostEligibleSessionStatus(session.status);
if (isLiveHostEligible) {
try {
const rawResult: unknown = await sendRpc(
socketPath(sessionDirectory),
Expand Down
21 changes: 2 additions & 19 deletions src/cli/commands/mark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
sessionDir,
socketPath,
} from '../../storage/sessionPaths.js';
import { assertSessionCommandable } from '../sessionGuards.js';

export type { MarkResult } from '../../protocol/messages.js';

Expand All @@ -37,25 +38,7 @@ export async function runMarkCommand(options: CommandOptions): Promise<void> {
});
}

if (manifest.status === 'destroyed') {
throw makeCliError(ERROR_CODES.SESSION_ALREADY_DESTROYED, {
message: `Session "${options.sessionId}" is already destroyed.`,
details: {
sessionId: options.sessionId,
status: manifest.status,
},
});
}

if (manifest.status !== 'running') {
throw makeCliError(ERROR_CODES.SESSION_NOT_RUNNING, {
message: `Session "${options.sessionId}" is not running.`,
details: {
sessionId: options.sessionId,
status: manifest.status,
},
});
}
assertSessionCommandable(manifest, options.sessionId);

const rawResult: unknown = await sendRpc(
socketPath(sessionDirectory),
Expand Down
21 changes: 2 additions & 19 deletions src/cli/commands/paste.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
socketPath,
} from '../../storage/sessionPaths.js';
import { resolveCommandInputText } from './inputSource.js';
import { assertSessionCommandable } from '../sessionGuards.js';

export interface PasteResult {
[key: string]: never;
Expand Down Expand Up @@ -54,25 +55,7 @@ export async function runPasteCommand(options: CommandOptions): Promise<void> {
});
}

if (manifest.status === 'destroyed') {
throw makeCliError(ERROR_CODES.SESSION_ALREADY_DESTROYED, {
message: `Session "${options.sessionId}" is already destroyed.`,
details: {
sessionId: options.sessionId,
status: manifest.status,
},
});
}

if (manifest.status !== 'running') {
throw makeCliError(ERROR_CODES.SESSION_NOT_RUNNING, {
message: `Session "${options.sessionId}" is not running.`,
details: {
sessionId: options.sessionId,
status: manifest.status,
},
});
}
assertSessionCommandable(manifest, options.sessionId);

await sendRpc(socketPath(sessionDirectory), 'paste', {
text,
Expand Down
21 changes: 2 additions & 19 deletions src/cli/commands/resize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
sessionDir,
socketPath,
} from '../../storage/sessionPaths.js';
import { assertSessionCommandable } from '../sessionGuards.js';

export interface ResizeResult {
cols: number;
Expand Down Expand Up @@ -39,25 +40,7 @@ export async function runResizeCommand(options: CommandOptions): Promise<void> {
});
}

if (manifest.status === 'destroyed') {
throw makeCliError(ERROR_CODES.SESSION_ALREADY_DESTROYED, {
message: `Session "${options.sessionId}" is already destroyed.`,
details: {
sessionId: options.sessionId,
status: manifest.status,
},
});
}

if (manifest.status !== 'running') {
throw makeCliError(ERROR_CODES.SESSION_NOT_RUNNING, {
message: `Session "${options.sessionId}" is not running.`,
details: {
sessionId: options.sessionId,
status: manifest.status,
},
});
}
assertSessionCommandable(manifest, options.sessionId);

if (
!Number.isInteger(options.cols) ||
Expand Down
21 changes: 2 additions & 19 deletions src/cli/commands/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
socketPath,
} from '../../storage/sessionPaths.js';
import { resolveCommandInputText } from './inputSource.js';
import { assertSessionCommandable } from '../sessionGuards.js';

interface CommandOptions {
context: CommandContext;
Expand Down Expand Up @@ -63,25 +64,7 @@ export async function runRunCommand(options: CommandOptions): Promise<void> {
});
}

if (manifest.status === 'destroyed') {
throw makeCliError(ERROR_CODES.SESSION_ALREADY_DESTROYED, {
message: `Session "${options.sessionId}" is already destroyed.`,
details: {
sessionId: options.sessionId,
status: manifest.status,
},
});
}

if (manifest.status !== 'running') {
throw makeCliError(ERROR_CODES.SESSION_NOT_RUNNING, {
message: `Session "${options.sessionId}" is not running.`,
details: {
sessionId: options.sessionId,
status: manifest.status,
},
});
}
assertSessionCommandable(manifest, options.sessionId);

const noWait = !options.wait;
const rpcParams: Record<string, unknown> = {
Expand Down
3 changes: 3 additions & 0 deletions src/cli/commands/screenshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,9 @@ export async function runScreenshotCommand(
let rawResult: unknown;
let invalidResultMessage = 'Unexpected response from host';

// Snapshot and screenshot intentionally keep their narrower legacy live-RPC
// gate. `exiting` sessions are live-host eligible for inspect, but these
// commands preserve their existing offline-replay capture behavior.
if (manifest.status === 'running') {
try {
rawResult = await sendRpc(socketPath(sessionDirectory), 'screenshot', {
Expand Down
21 changes: 2 additions & 19 deletions src/cli/commands/send-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
sessionDir,
socketPath,
} from '../../storage/sessionPaths.js';
import { assertSessionCommandable } from '../sessionGuards.js';

export type { SendKeysResult } from '../../protocol/messages.js';

Expand Down Expand Up @@ -39,25 +40,7 @@ export async function runSendKeysCommand(
});
}

if (manifest.status === 'destroyed') {
throw makeCliError(ERROR_CODES.SESSION_ALREADY_DESTROYED, {
message: `Session "${options.sessionId}" is already destroyed.`,
details: {
sessionId: options.sessionId,
status: manifest.status,
},
});
}

if (manifest.status !== 'running') {
throw makeCliError(ERROR_CODES.SESSION_NOT_RUNNING, {
message: `Session "${options.sessionId}" is not running.`,
details: {
sessionId: options.sessionId,
status: manifest.status,
},
});
}
assertSessionCommandable(manifest, options.sessionId);

const rawResult: unknown = await sendRpc(
socketPath(sessionDirectory),
Expand Down
Loading
Loading