mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-17 19:59:33 +01:00
Merge pull request #694: feat(agent): COD-529 add bounded inspection and guarded submission
Conflicts resolved by keeping both sides: - CLAUDE.md (Agent CLI): #694's opening (an HTTP client, the experimental agent-session-routes behind agentCoordinationEnabled) with #708's clause on the directory spawn and its two refusals. - docs/api-reference.md (codeman agent): #708's spawn paragraph and --json shape, with #694's inspect/stage/submit in the verb list and the guarded endpoints named before "adds no route for the other verbs". - src/cli-agent.ts (@fileoverview): #708's quick-start / directory spawn routes and #694's experimental routes in one endpoint list; the two node:fs/promises imports (#708's realpath+stat, #694's open+stat) merged into one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
5908cc51fd
50 files changed
+5408
-116
No files matched your search
@@ -0,0 +1,275 @@
|
||||
/**
|
||||
* @fileoverview Bounded Codex rollout attribution for agent evidence. Never uses
|
||||
* newest-mtime, prompt timestamps or cwd alone as proof of session ownership.
|
||||
* The first call walks the store under explicit budgets; the attributed file is
|
||||
* then remembered per session and only re-verified (plus a scan of the date
|
||||
* directories not older than it) on later calls, since codex never prunes
|
||||
* `~/.codex/sessions`.
|
||||
*/
|
||||
import { open, opendir, realpath } from 'node:fs/promises';
|
||||
import { probePathKind } from './utils/bounded-path-probe.js';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, relative, resolve, sep } from 'node:path';
|
||||
import { LRUMap } from './utils/lru-map.js';
|
||||
|
||||
const UUID_AT_END = /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i;
|
||||
const HEAD_BYTES = 131072;
|
||||
const PREFIX_SCAN_BYTES = 8 * 1024 * 1024;
|
||||
export interface CodexAttributionOptions {
|
||||
codexHome: string;
|
||||
sessionId: string;
|
||||
workingDir: string;
|
||||
resumeSessionId?: string;
|
||||
}
|
||||
export interface CodexAttributionBudget {
|
||||
maxEntries: number;
|
||||
maxBytes: number;
|
||||
/** Separate bound for cheap negative prefixes; full candidate metadata has its own budget. */
|
||||
maxPrefixBytes?: number;
|
||||
}
|
||||
interface Metadata {
|
||||
id?: string;
|
||||
cwd?: string;
|
||||
originator?: string;
|
||||
}
|
||||
async function canonical(path: string): Promise<string | undefined> {
|
||||
if ((await probePathKind(path, { pastCap: true })) !== 'directory') return undefined;
|
||||
try {
|
||||
return await realpath(path);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
/** Match the CLI's relative CODEX_HOME interpretation without exposing env credentials. */
|
||||
export function resolveEffectiveCodexHome(
|
||||
sessionHome: string | undefined,
|
||||
workingDir: string,
|
||||
env: Readonly<Record<string, string | undefined>> = process.env
|
||||
): string {
|
||||
const path = resolve(workingDir, sessionHome || env.CODEX_HOME || join(env.HOME || tmpdir(), '.codex'));
|
||||
return path;
|
||||
}
|
||||
/** Complete metadata only: a prefix or a partially flushed JSONL row proves nothing. */
|
||||
function strictMetadata(bytes: Buffer): Metadata | undefined {
|
||||
const rows = bytes.toString('utf8').split('\n');
|
||||
rows.pop();
|
||||
let found: Metadata | undefined;
|
||||
for (const line of rows) {
|
||||
try {
|
||||
const row = JSON.parse(line) as { type?: string; payload?: Metadata };
|
||||
if (row.type !== 'session_meta') continue;
|
||||
if (
|
||||
found ||
|
||||
typeof row.payload?.id !== 'string' ||
|
||||
typeof row.payload.cwd !== 'string' ||
|
||||
(row.payload.originator !== undefined && typeof row.payload.originator !== 'string')
|
||||
)
|
||||
return undefined;
|
||||
found = row.payload;
|
||||
} catch {
|
||||
/* Incomplete or malformed rows are not identity evidence. */
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
/**
|
||||
* The rollout a previous call attributed, per session. A later call re-verifies only
|
||||
* this file's head (same `dev:ino`, same strict metadata) and then scans just the
|
||||
* directories not older than its own for a second candidate (codex `/new`, or a new
|
||||
* owned rollout beside a configured resume), instead of re-reading the whole store,
|
||||
* which codex never prunes. A head that no longer verifies drops the entry and falls
|
||||
* back to the full walk; a failed incremental scan drops it and answers unattributed,
|
||||
* since the full walk reads a superset of that scan. Bounded: one entry per live
|
||||
* session is the expected size.
|
||||
*/
|
||||
interface AttributionMemo {
|
||||
id: string;
|
||||
path: string;
|
||||
dev: number;
|
||||
ino: number;
|
||||
meta: Metadata;
|
||||
/** Directory components of `path` below `sessions/`, used to prune older siblings. */
|
||||
dirParts: string[];
|
||||
}
|
||||
const attributionMemo = new LRUMap<string, AttributionMemo>({ maxSize: 1024 });
|
||||
/** Test-only: forget every remembered attribution. */
|
||||
export function __clearCodexAttributionMemo(): void {
|
||||
attributionMemo.clear();
|
||||
}
|
||||
/** Short first read: `originator` sits right after `id`, `timestamp` and `cwd`. */
|
||||
const PREFIX_FIRST_BYTES = 1024;
|
||||
/** Fallback read when the first window holds no complete `originator` field. */
|
||||
const PREFIX_MAX_BYTES = 4096;
|
||||
const ORIGINATOR_FIELD = /"originator"\s*:\s*"(?:[^"\\]|\\.)*"/;
|
||||
/**
|
||||
* Is a date-shaped directory name older than the remembered one at the same depth?
|
||||
* Only all-digit names compare (codex writes `sessions/YYYY/MM/DD/`); anything else
|
||||
* is never pruned, so an unexpected layout costs a wider scan, not a missed rollout.
|
||||
*/
|
||||
function olderDatePart(name: string, memo: string | undefined): boolean {
|
||||
if (memo === undefined || !/^\d+$/.test(name) || !/^\d+$/.test(memo)) return false;
|
||||
return Number(name) < Number(memo);
|
||||
}
|
||||
/**
|
||||
* A configured resume and a newly owned rollout conflict rather than pinning an
|
||||
* old launch forever after /new. TUI resumes of foreign-originator threads cannot
|
||||
* be authoritatively tracked from this metadata; this returns attributed evidence.
|
||||
*/
|
||||
export async function findExactCodexConversation(
|
||||
options: CodexAttributionOptions,
|
||||
budget: CodexAttributionBudget = { maxEntries: 8192, maxBytes: 1048576 }
|
||||
): Promise<{ id: string; path: string } | undefined> {
|
||||
const workspace = await canonical(options.workingDir);
|
||||
const home = await canonical(options.codexHome);
|
||||
if (!workspace || !home) return undefined;
|
||||
const sessions = join(home, 'sessions');
|
||||
if ((await probePathKind(sessions, { pastCap: true })) !== 'directory') return undefined;
|
||||
const key = [home, options.sessionId, options.resumeSessionId ?? '', workspace].join('\0');
|
||||
const remembered = attributionMemo.get(key);
|
||||
if (remembered) {
|
||||
const verified = await verifyRemembered(remembered, workspace, budget);
|
||||
if (verified) {
|
||||
const others = await scanCandidates(sessions, options, budget, remembered.dirParts);
|
||||
if (others && others.length === 1 && others[0].path === remembered.path) {
|
||||
return { id: remembered.id, path: remembered.path };
|
||||
}
|
||||
}
|
||||
attributionMemo.delete(key);
|
||||
// A file that no longer verifies (replaced, rewritten, gone) gets one full walk
|
||||
// now. A verified file whose incremental scan failed does not: that scan reads a
|
||||
// subset of what a full walk reads under the same budget, so a second candidate,
|
||||
// an exhausted budget or an unreadable entry it hit is one the full walk would hit
|
||||
// too, and walking the whole never-pruned store could only end the same way.
|
||||
if (verified) return undefined;
|
||||
}
|
||||
const candidates = await scanCandidates(sessions, options, budget);
|
||||
if (!candidates || candidates.length !== 1) return undefined;
|
||||
const candidate = candidates[0];
|
||||
if (!candidate.meta.cwd || (await canonical(candidate.meta.cwd)) !== workspace) return undefined;
|
||||
const handle = await open(candidate.path, 'r').catch(() => undefined);
|
||||
if (!handle) return undefined;
|
||||
try {
|
||||
const info = await handle.stat();
|
||||
const bytes = Buffer.alloc(HEAD_BYTES);
|
||||
const read = await handle.read(bytes, 0, bytes.length, 0);
|
||||
const meta = strictMetadata(bytes.subarray(0, read.bytesRead));
|
||||
if (
|
||||
!meta ||
|
||||
meta.id !== candidate.id ||
|
||||
meta.cwd !== candidate.meta.cwd ||
|
||||
meta.originator !== candidate.meta.originator
|
||||
)
|
||||
return undefined;
|
||||
attributionMemo.set(key, {
|
||||
id: candidate.id,
|
||||
path: candidate.path,
|
||||
dev: info.dev,
|
||||
ino: info.ino,
|
||||
meta,
|
||||
dirParts: relative(sessions, dirname(candidate.path)).split(sep).filter(Boolean),
|
||||
});
|
||||
return { id: candidate.id, path: candidate.path };
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
/** Same file (`dev:ino`), same strict metadata, same canonical workspace: nothing else. */
|
||||
async function verifyRemembered(
|
||||
memo: AttributionMemo,
|
||||
workspace: string,
|
||||
budget: CodexAttributionBudget
|
||||
): Promise<boolean> {
|
||||
if (HEAD_BYTES > budget.maxBytes) return false;
|
||||
if (!memo.meta.cwd || (await canonical(memo.meta.cwd)) !== workspace) return false;
|
||||
const handle = await open(memo.path, 'r').catch(() => undefined);
|
||||
if (!handle) return false;
|
||||
try {
|
||||
const info = await handle.stat();
|
||||
if (!info.isFile() || info.dev !== memo.dev || info.ino !== memo.ino) return false;
|
||||
const bytes = Buffer.alloc(HEAD_BYTES);
|
||||
const read = await handle.read(bytes, 0, bytes.length, 0);
|
||||
const meta = strictMetadata(bytes.subarray(0, read.bytesRead));
|
||||
return !!meta && meta.id === memo.id && meta.cwd === memo.meta.cwd && meta.originator === memo.meta.originator;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Every rollout under `sessions` whose strict metadata names this session (or the
|
||||
* configured resume id), or undefined when the walk hit a bound or an unreadable
|
||||
* entry (an incomplete inventory proves nothing). With `notOlderThan`, date-shaped
|
||||
* directories older than those components are skipped.
|
||||
*/
|
||||
async function scanCandidates(
|
||||
sessions: string,
|
||||
options: CodexAttributionOptions,
|
||||
budget: CodexAttributionBudget,
|
||||
notOlderThan?: string[]
|
||||
): Promise<Array<{ id: string; path: string; meta: Metadata }> | undefined> {
|
||||
// `onBoundary`: every ancestor so far equals the remembered path, so pruning applies.
|
||||
const directories = [{ path: sessions, depth: 0, onBoundary: notOlderThan !== undefined }];
|
||||
const candidates: Array<{ id: string; path: string; meta: Metadata }> = [];
|
||||
const originator = `codeman_${options.sessionId}`;
|
||||
const originatorJson = JSON.stringify(originator);
|
||||
const explicit = options.resumeSessionId;
|
||||
let entries = 0;
|
||||
let prefixes = 0;
|
||||
const prefixLimit = Math.min(budget.maxPrefixBytes ?? PREFIX_SCAN_BYTES, PREFIX_SCAN_BYTES);
|
||||
let scanned = HEAD_BYTES; // Reserve an independent final verification.
|
||||
while (directories.length) {
|
||||
const dir = directories.pop()!;
|
||||
const handle = await opendir(dir.path).catch(() => undefined);
|
||||
if (!handle) return undefined;
|
||||
for await (const entry of handle) {
|
||||
if (++entries > budget.maxEntries) return undefined;
|
||||
const path = join(dir.path, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
if (dir.depth >= 8) return undefined;
|
||||
const part = notOlderThan?.[dir.depth];
|
||||
if (dir.onBoundary && olderDatePart(entry.name, part)) continue;
|
||||
directories.push({ path, depth: dir.depth + 1, onBoundary: dir.onBoundary && entry.name === part });
|
||||
} else if (entry.isFile() && entry.name.endsWith('.jsonl')) {
|
||||
const id = entry.name.match(UUID_AT_END)?.[1];
|
||||
if (!id) continue; // no rollout id in the name: never a candidate, read nothing
|
||||
const file = await open(path, 'r').catch(() => undefined);
|
||||
if (!file) return undefined;
|
||||
try {
|
||||
const info = await file.stat();
|
||||
if (!info.isFile()) return undefined;
|
||||
if (id !== explicit) {
|
||||
// Cheap negative filter only; a match still needs full parsed metadata.
|
||||
// A short first window decides when it already holds the whole
|
||||
// `originator` field; only otherwise is the wider window read.
|
||||
let window = Math.min(info.size, PREFIX_FIRST_BYTES);
|
||||
let prefix = '';
|
||||
for (;;) {
|
||||
if (prefixes + window > prefixLimit) return undefined;
|
||||
prefixes += window;
|
||||
const buffer = Buffer.alloc(window);
|
||||
const first = await file.read(buffer, 0, window, 0);
|
||||
prefix = buffer.subarray(0, first.bytesRead).toString('utf8');
|
||||
if (prefix.includes(originatorJson) || ORIGINATOR_FIELD.test(prefix)) break;
|
||||
const wider = Math.min(info.size, PREFIX_MAX_BYTES);
|
||||
if (wider <= window) break;
|
||||
window = wider;
|
||||
}
|
||||
if (!prefix.includes(originatorJson)) continue;
|
||||
}
|
||||
const size = Math.min(info.size, HEAD_BYTES);
|
||||
if (scanned + size > budget.maxBytes) return undefined;
|
||||
scanned += size;
|
||||
const bytes = Buffer.alloc(size);
|
||||
const read = await file.read(bytes, 0, size, 0);
|
||||
const meta = strictMetadata(bytes.subarray(0, read.bytesRead));
|
||||
if (!meta || meta.id !== id) continue;
|
||||
if (id === explicit || meta.originator === originator) candidates.push({ id, path, meta });
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* @fileoverview Bounded append-only JSONL evidence reads for agent inspection.
|
||||
* Opaque, expiring server-side cursors contain no public filesystem paths. A cursor
|
||||
* binds the caller, pane generation, attributed conversation and opened file identity.
|
||||
* Complete records only; an oversized row stalls explicitly rather than losing evidence.
|
||||
*/
|
||||
import { open, type FileHandle } from 'node:fs/promises';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { isUtf8 } from 'node:buffer';
|
||||
|
||||
export const INSPECT_MAX_BYTES = 65536;
|
||||
export const INSPECT_SCAN_BYTES = 262144;
|
||||
export interface InspectionScope {
|
||||
owner: string;
|
||||
sessionId: string;
|
||||
generation: string;
|
||||
conversationId: string;
|
||||
}
|
||||
interface CursorState {
|
||||
scope: string;
|
||||
/** Owner and session only: the unit the per-scope cap counts. */
|
||||
holder: string;
|
||||
path: string;
|
||||
identity: string;
|
||||
offset: number;
|
||||
observedSize: number;
|
||||
modifiedAt: number;
|
||||
changedAt: number;
|
||||
anchor: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
export class InspectionConflict extends Error {}
|
||||
|
||||
/** UTF8-safe suffix, also used for explicitly non-incremental pane evidence. */
|
||||
export function boundedUtf8Tail(text: string, maxBytes: number): string {
|
||||
// A UTF8 suffix fits within this many UTF16 units. Include a pair of extra
|
||||
// units so slicing cannot introduce a surrogate replacement inside the result.
|
||||
const bytes = Buffer.from(text.slice(-maxBytes - 2));
|
||||
let start = Math.max(0, bytes.length - maxBytes);
|
||||
while (start < bytes.length && (bytes[start] & 0xc0) === 0x80) start++;
|
||||
return bytes.subarray(start).toString('utf8');
|
||||
}
|
||||
async function anchor(handle: FileHandle, offset: number): Promise<string> {
|
||||
const count = Math.min(offset, 4096);
|
||||
const head = Buffer.alloc(count);
|
||||
const tail = Buffer.alloc(count);
|
||||
await handle.read(head, 0, count, 0);
|
||||
await handle.read(tail, 0, count, Math.max(0, offset - count));
|
||||
return createHash('sha256').update(head).update(tail).digest('hex');
|
||||
}
|
||||
|
||||
/** Cursors kept per owner and session; older ones are retired first. */
|
||||
export const INSPECT_CURSORS_PER_SCOPE = 8;
|
||||
|
||||
export class InspectionReader {
|
||||
private readonly cursors = new Map<string, CursorState>();
|
||||
constructor(
|
||||
private readonly now = Date.now,
|
||||
private readonly capacity = 1024,
|
||||
private readonly ttlMs = 900000,
|
||||
private readonly perScope = INSPECT_CURSORS_PER_SCOPE
|
||||
) {}
|
||||
|
||||
async read(path: string, scope: InspectionScope, maxBytes: number, since?: string) {
|
||||
if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > INSPECT_MAX_BYTES)
|
||||
throw new Error('Invalid byte budget');
|
||||
const scopeKey = JSON.stringify(scope);
|
||||
const previous = since ? this.cursors.get(since) : undefined;
|
||||
if (
|
||||
since &&
|
||||
(!previous || previous.expiresAt <= this.now() || previous.scope !== scopeKey || previous.path !== path)
|
||||
) {
|
||||
throw new InspectionConflict('Invalid or expired inspection cursor; inspect without since to start again');
|
||||
}
|
||||
const handle = await open(path, 'r');
|
||||
try {
|
||||
const before = await handle.stat();
|
||||
if (!before.isFile()) throw new InspectionConflict('Inspection source is not a regular file');
|
||||
const identity = `${before.dev}:${before.ino}:${before.birthtimeMs}`;
|
||||
let offset = previous?.offset ?? Math.max(0, before.size - INSPECT_SCAN_BYTES + 1);
|
||||
if (
|
||||
previous &&
|
||||
(identity !== previous.identity ||
|
||||
before.size < previous.observedSize ||
|
||||
(before.size === previous.observedSize &&
|
||||
(before.mtimeMs !== previous.modifiedAt || before.ctimeMs !== previous.changedAt)) ||
|
||||
(await anchor(handle, offset)) !== previous.anchor)
|
||||
) {
|
||||
throw new InspectionConflict('Inspection cursor source changed; inspect without since to start again');
|
||||
}
|
||||
let startsAtBoundary = offset === 0;
|
||||
if (!previous && offset > 0) {
|
||||
const preceding = Buffer.alloc(1);
|
||||
await handle.read(preceding, 0, 1, offset - 1);
|
||||
startsAtBoundary = preceding[0] === 10;
|
||||
}
|
||||
const scan = Buffer.alloc(
|
||||
Math.min(INSPECT_SCAN_BYTES - (!previous && offset > 0 ? 1 : 0), Math.max(0, before.size - offset))
|
||||
);
|
||||
const { bytesRead } = await handle.read(scan, 0, scan.length, offset);
|
||||
let selectedStart = 0;
|
||||
let consumed = 0;
|
||||
let blockedReason: string | undefined;
|
||||
let omittedBeforeBytes = 0;
|
||||
if (!previous) {
|
||||
const leading = startsAtBoundary ? 0 : scan.indexOf(10) + 1;
|
||||
const completeEnd = scan.lastIndexOf(10, bytesRead - 1) + 1;
|
||||
if (!startsAtBoundary && leading === 0) {
|
||||
// The tail lies wholly inside one unfinished oversized record. Its
|
||||
// beginning is not known: retain the known file boundary rather than
|
||||
// manufacture a cursor pointing into a JSON/UTF8 fragment.
|
||||
offset = 0;
|
||||
blockedReason = 'record-exceeds-scan-limit';
|
||||
} else {
|
||||
selectedStart = completeEnd;
|
||||
consumed = completeEnd;
|
||||
while (selectedStart > leading) {
|
||||
const recordStart = Math.max(leading, scan.lastIndexOf(10, selectedStart - 2) + 1);
|
||||
if (completeEnd - recordStart > maxBytes) {
|
||||
if (selectedStart === completeEnd) {
|
||||
selectedStart = recordStart;
|
||||
consumed = recordStart;
|
||||
blockedReason = 'record-exceeds-output-budget';
|
||||
}
|
||||
break;
|
||||
}
|
||||
selectedStart = recordStart;
|
||||
}
|
||||
if (completeEnd < bytesRead && !blockedReason) blockedReason = 'partial-record';
|
||||
// If the only known boundary is the end of a skipped leading row,
|
||||
// the remainder is a partial record and stays pending there.
|
||||
if (completeEnd < leading) selectedStart = consumed = leading;
|
||||
omittedBeforeBytes = offset + selectedStart;
|
||||
}
|
||||
} else {
|
||||
while (consumed < bytesRead) {
|
||||
const end = scan.indexOf(10, consumed);
|
||||
if (end < 0) {
|
||||
blockedReason = bytesRead === INSPECT_SCAN_BYTES ? 'record-exceeds-scan-limit' : 'partial-record';
|
||||
break;
|
||||
}
|
||||
if (end + 1 > maxBytes) {
|
||||
if (consumed === 0) blockedReason = 'record-exceeds-output-budget';
|
||||
break;
|
||||
}
|
||||
consumed = end + 1;
|
||||
}
|
||||
}
|
||||
const evidenceBytes = scan.subarray(selectedStart, consumed);
|
||||
if (!isUtf8(evidenceBytes)) throw new InspectionConflict('Inspection source contains invalid UTF8');
|
||||
for (const row of evidenceBytes.toString('utf8').split('\n').slice(0, -1)) {
|
||||
try {
|
||||
JSON.parse(row);
|
||||
} catch {
|
||||
throw new InspectionConflict('Inspection source contains invalid JSONL');
|
||||
}
|
||||
}
|
||||
const after = await handle.stat();
|
||||
if (
|
||||
after.size < before.size ||
|
||||
after.ino !== before.ino ||
|
||||
(after.size === before.size && (after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs))
|
||||
)
|
||||
throw new InspectionConflict('Inspection source changed during read');
|
||||
const nextAnchor = await anchor(handle, offset + consumed);
|
||||
const cursor = randomUUID();
|
||||
// No await between capacity enforcement and insertion: concurrent reads
|
||||
// must not all reserve the same remaining slot while hashing anchors.
|
||||
// Each owner and session keeps only its newest cursors, so one agent polling in
|
||||
// a loop retires its own oldest ones instead of pushing every other caller's out
|
||||
// of the shared map. The cursor just used stays among the newest, so a retry of
|
||||
// the last call still works. The global capacity is only a backstop.
|
||||
const holder = JSON.stringify([scope.owner, scope.sessionId]);
|
||||
const mine: string[] = [];
|
||||
for (const [key, value] of this.cursors) {
|
||||
if (value.expiresAt <= this.now()) this.cursors.delete(key);
|
||||
else if (value.holder === holder) mine.push(key);
|
||||
}
|
||||
while (mine.length >= this.perScope) this.cursors.delete(mine.shift()!);
|
||||
while (this.cursors.size >= this.capacity) this.cursors.delete(this.cursors.keys().next().value!);
|
||||
this.cursors.set(cursor, {
|
||||
scope: scopeKey,
|
||||
holder,
|
||||
path,
|
||||
identity,
|
||||
offset: offset + consumed,
|
||||
observedSize: before.size,
|
||||
modifiedAt: before.mtimeMs,
|
||||
changedAt: before.ctimeMs,
|
||||
anchor: nextAnchor,
|
||||
expiresAt: this.now() + this.ttlMs,
|
||||
});
|
||||
return {
|
||||
evidence: evidenceBytes.toString('utf8'),
|
||||
cursor,
|
||||
omittedBeforeBytes,
|
||||
truncated: omittedBeforeBytes > 0 || offset + consumed < before.size,
|
||||
blockedReason,
|
||||
scannedBytes: bytesRead,
|
||||
};
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
clear(): void {
|
||||
this.cursors.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
/**
|
||||
* @fileoverview Short-lived, bounded guarded prompt receipts. No prompt content is
|
||||
* retained: only caller/session identity, lifecycle/input revisions and SHA-256.
|
||||
* A receipt is consumed synchronously before verification/delivery, including failures.
|
||||
*/
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { stripAnsi } from './utils/regex-patterns.js';
|
||||
import { visibleWidth } from './tui/tui-ansi.js';
|
||||
import { compileVersionRegex } from './config/cli-registry/patterns.js';
|
||||
import type { CliEntry } from './config/cli-registry/types.js';
|
||||
|
||||
/**
|
||||
* The screen chrome a guarded composer read relies on, all from the CLI registry
|
||||
* (`capabilities.workDetect`): the composer glyph, the pattern every row below an
|
||||
* idle composer must match, and what opens a popup or turns Enter into a command.
|
||||
* Nothing here names a CLI; a CLI takes part in guarded input by declaring
|
||||
* `composerFooterLine`.
|
||||
*/
|
||||
export interface GuardedComposerChrome {
|
||||
promptGlyph: string;
|
||||
footerLine: RegExp;
|
||||
/** A row of a suggestion popup drawn directly above the composer (`composerPopupLine`). */
|
||||
popupLine?: RegExp;
|
||||
/** First characters of a draft that make Enter run a command (`composerCommandPrefixes`). */
|
||||
commandPrefixes?: string;
|
||||
/** First characters of the word at the caret that open a completion popup (`composerCompletionSigils`). */
|
||||
completionSigils?: string;
|
||||
}
|
||||
/** The chrome a registry entry declares, or null (no guarded input for that CLI). */
|
||||
export function guardedComposerChrome(entry: CliEntry | undefined): GuardedComposerChrome | null {
|
||||
const detect = entry?.capabilities.workDetect;
|
||||
if (!detect?.promptGlyph || !detect.composerFooterLine) return null;
|
||||
// Config-supplied (~/.codeman/clis.json): compiled through the ReDoS guard, null on refusal.
|
||||
const footerLine = compileVersionRegex(detect.composerFooterLine);
|
||||
if (!footerLine) return null;
|
||||
// A declared popup pattern the guard refuses is no chrome at all: dropping it would
|
||||
// silently read a popup frame as an idle composer.
|
||||
const popupLine = detect.composerPopupLine ? compileVersionRegex(detect.composerPopupLine) : undefined;
|
||||
if (popupLine === null) return null;
|
||||
return {
|
||||
promptGlyph: detect.promptGlyph,
|
||||
footerLine,
|
||||
...(popupLine ? { popupLine } : {}),
|
||||
...(detect.composerCommandPrefixes ? { commandPrefixes: detect.composerCommandPrefixes } : {}),
|
||||
...(detect.composerCompletionSigils ? { completionSigils: detect.composerCompletionSigils } : {}),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Why a message cannot be staged into this composer, or null. Typing it would change
|
||||
* what Enter does rather than what it sends: a draft starting with a command prefix
|
||||
* (codex: `/` for a slash command, `!` for a shell command) is run, not sent as a
|
||||
* prompt, and a last word starting with a completion sigil (codex: `@` file and
|
||||
* mention search, `$` skills) opens a popup at the caret whose highlighted entry Enter
|
||||
* would accept. Checked before anything is typed. Only the LAST word matters for the
|
||||
* sigils because the caret is at the end of the message and the popup follows the
|
||||
* caret; a sigil word earlier in the message opens nothing.
|
||||
*/
|
||||
export function composerTriggerRefusal(message: string, chrome: GuardedComposerChrome): string | null {
|
||||
const first = message.trimStart().charAt(0);
|
||||
if (first && chrome.commandPrefixes?.includes(first))
|
||||
return `Stage refuses a message starting with "${first}": the CLI runs it as a command instead of sending it as a prompt. Send commands with \`codeman agent send\` (POST /api/v1/sessions/:id/input) instead`;
|
||||
const last = message.split(/\s/).at(-1)?.charAt(0);
|
||||
if (last && chrome.completionSigils?.includes(last))
|
||||
return `Stage refuses a message whose last word starts with "${last}": it opens a completion popup at the caret and Enter would accept the highlighted entry instead of sending the message. End the message with another word, or use \`codeman agent send\``;
|
||||
return null;
|
||||
}
|
||||
/** How many rows above the composer a popup check reads: the popup cap (8) plus header and hint rows. */
|
||||
const POPUP_WINDOW_ROWS = 12;
|
||||
/** Blank rows a popup can leave between itself and the composer row (the composer's own top padding, plus a popup's). */
|
||||
const POPUP_GAP_ROWS = 3;
|
||||
const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const composerRow = (chrome: GuardedComposerChrome) =>
|
||||
new RegExp(String.raw`^\s*${escapeRegex(chrome.promptGlyph)}(?:\s|$)`);
|
||||
export const STAGE_MAX_BYTES = 8192;
|
||||
export const promptSha256 = (text: string): string => createHash('sha256').update(text).digest('hex');
|
||||
export interface GuardedInputSnapshot {
|
||||
generation: string;
|
||||
revision: number;
|
||||
composerSha: string;
|
||||
/** Actual captured pane width minus the rendered composer prefix (including indentation). */
|
||||
availableColumns: number;
|
||||
}
|
||||
export interface GuardedInputTarget {
|
||||
id: string;
|
||||
/** The session's composer chrome, read before typing for what a message would trigger. */
|
||||
chrome(): GuardedComposerChrome | null;
|
||||
snapshot(): GuardedInputSnapshot | null;
|
||||
write(text: string): Promise<boolean>;
|
||||
submit(expected: GuardedInputSnapshot): Promise<boolean>;
|
||||
}
|
||||
interface Receipt extends GuardedInputSnapshot {
|
||||
owner: string;
|
||||
sessionId: string;
|
||||
expiresAt: number;
|
||||
sha256: string;
|
||||
/** When the staged keys went out, for `SUBMIT_QUIET_MS`. */
|
||||
typedAt: number;
|
||||
}
|
||||
export class GuardedInputConflict extends Error {}
|
||||
|
||||
/**
|
||||
* How long stage keeps reading the pane after typing for a frame that shows the
|
||||
* message, and how often. A capture taken right after the keys land is often a
|
||||
* frame from before them: codex repaints its composer 30 to 60 ms after input
|
||||
* arrives (measured on a live 0.162.0 pane), so the first read can show the old,
|
||||
* empty composer, or nothing provable at all. A second of 50 ms reads covers that
|
||||
* many times over and still answers the caller quickly.
|
||||
*/
|
||||
export const STAGE_SETTLE_TIMEOUT_MS = 1000;
|
||||
export const STAGE_SETTLE_INTERVAL_MS = 50;
|
||||
/**
|
||||
* The least time between the staged keys and the conditional Enter. Stage types its
|
||||
* text as plain keys (`send-keys -l`), which codex's paste-burst detector reads as a
|
||||
* paste, and for 120 ms after such a burst codex turns Enter into a NEWLINE rather
|
||||
* than a submit (`PASTE_ENTER_SUPPRESS_WINDOW`, codex-rs/tui/src/bottom_pane/
|
||||
* paste_burst.rs at rust-v0.162.0). A caller that submits the moment stage answers
|
||||
* would land inside it and be told one Enter was delivered while codex only broke
|
||||
* the line. Submit waits out the rest of this window first; a keystroke in that
|
||||
* time still invalidates the receipt.
|
||||
*/
|
||||
export const SUBMIT_QUIET_MS = 250;
|
||||
/** Settle-window overrides for tests: a fake clock comes from the store's `now`. */
|
||||
export interface StageSettleOptions {
|
||||
timeoutMs?: number;
|
||||
intervalMs?: number;
|
||||
sleep?: (ms: number) => Promise<void>;
|
||||
}
|
||||
/**
|
||||
* Every refusal after the keys went out says so: stage cannot tell whether the text
|
||||
* landed, so the caller must look before staging again (the recovery steps clear a
|
||||
* stranded draft with Ctrl+U).
|
||||
*/
|
||||
export const MAY_BE_TYPED =
|
||||
'no receipt was issued. The message may already be in the composer: inspect the pane and follow the stranded-draft recovery steps (Ctrl+U) before staging again';
|
||||
|
||||
/**
|
||||
* Conservatively read a composer: exactly one visible, unwrapped row and a known
|
||||
* footer, both as the registry describes them. Never remove internal spaces, infer
|
||||
* an unknown shell prompt, or interpret dialog options as authority. An unsupported
|
||||
* frame yields no proof.
|
||||
*/
|
||||
export function readGuardedComposer(screen: string, chrome: GuardedComposerChrome): string | null {
|
||||
const isComposer = composerRow(chrome);
|
||||
const lines = stripAnsi(screen)
|
||||
.split('\n')
|
||||
.map((line) => line.trimEnd());
|
||||
const rows = lines.map((line, index) => ({ line, index })).filter((row) => isComposer.test(row.line));
|
||||
const last = rows.at(-1);
|
||||
if (!last) return null;
|
||||
const below = lines.slice(last.index + 1).filter((line) => line.trim());
|
||||
if (below.length === 0 || below.length > 3 || below.some((line) => !chrome.footerLine.test(line))) return null;
|
||||
if (chrome.popupLine && popupAbove(lines, last.index, chrome.popupLine)) return null;
|
||||
// Preserve exact printable content; only SGR-dim placeholder/suggestion text is excluded.
|
||||
const raw = screen.split('\n')[last.index];
|
||||
let dim = false;
|
||||
let visible = '';
|
||||
// eslint-disable-next-line no-control-regex
|
||||
for (const token of raw.split(/(\x1b\[[0-9;]*m)/)) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
if (/^\x1b\[/.test(token)) {
|
||||
const codes = token.slice(2, -1).split(';').map(Number);
|
||||
for (let i = 0; i < codes.length; i++) {
|
||||
// Extended color payloads may contain 0, 2 or 22; those are not SGR modes.
|
||||
if (codes[i] === 38 || codes[i] === 48 || codes[i] === 58) {
|
||||
i += codes[i + 1] === 2 ? 4 : codes[i + 1] === 5 ? 2 : 0;
|
||||
} else if (codes[i] === 0 || codes[i] === 22) dim = false;
|
||||
else if (codes[i] === 2) dim = true;
|
||||
}
|
||||
} else if (!dim) visible += token;
|
||||
}
|
||||
// The glyph and the one space after it are the prefix, not input.
|
||||
return stripAnsi(visible)
|
||||
.trimStart()
|
||||
.slice(chrome.promptGlyph.length + 1)
|
||||
.trimEnd();
|
||||
}
|
||||
|
||||
/**
|
||||
* Does a suggestion popup sit directly above the composer row? A popup draws over
|
||||
* the rows above the composer and leaves the footer below it alone, so the footer
|
||||
* check alone reads a popup frame as an idle composer. Read the contiguous block of
|
||||
* rows just above (past at most `POPUP_GAP_ROWS` blank rows), never the whole pane:
|
||||
* the transcript further up is the agent's own and may print anything. A transcript
|
||||
* row that happens to match costs a refusal, never a receipt.
|
||||
*/
|
||||
function popupAbove(lines: string[], composerIndex: number, popupLine: RegExp): boolean {
|
||||
let index = composerIndex - 1;
|
||||
for (let gap = 0; gap < POPUP_GAP_ROWS && index >= 0 && !lines[index].trim(); gap++) index--;
|
||||
for (let seen = 0; seen < POPUP_WINDOW_ROWS && index >= 0 && lines[index].trim(); seen++, index--) {
|
||||
if (popupLine.test(lines[index])) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Require the capture's caret at the exact end of the unwrapped composer. */
|
||||
export function readGuardedSnapshot(snapshot: string, chrome: GuardedComposerChrome): string | null {
|
||||
return readGuardedSnapshotDetails(snapshot, chrome)?.composer ?? null;
|
||||
}
|
||||
/** Exact input-row prefix width, shared by proof and preflight wrapping checks. */
|
||||
export function readGuardedSnapshotDetails(
|
||||
snapshot: string,
|
||||
chrome: GuardedComposerChrome
|
||||
): { composer: string; prefixWidth: number } | null {
|
||||
// formatPaneSnapshot emits one absolute row address per line, then the caret.
|
||||
// Plain captures lack caret evidence and cannot prove invisible trailing edits.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const positions = [...snapshot.matchAll(/\x1b\[(\d+);(\d+)H/g)];
|
||||
if (positions.length < 2) return null;
|
||||
const caret = positions.at(-1)!;
|
||||
if (caret.index! + caret[0].length !== snapshot.length) return null;
|
||||
const rows: string[] = [];
|
||||
for (let i = 0; i < positions.length - 1; i++) {
|
||||
const position = positions[i];
|
||||
if (Number(position[1]) !== i + 1 || position[2] !== '1') return null;
|
||||
rows.push(snapshot.slice(position.index! + position[0].length, positions[i + 1].index));
|
||||
}
|
||||
const composer = readGuardedComposer(rows.join('\n'), chrome);
|
||||
if (composer === null) return null;
|
||||
const isComposer = composerRow(chrome);
|
||||
let row = -1;
|
||||
for (let i = rows.length - 1; i >= 0; i--)
|
||||
if (isComposer.test(stripAnsi(rows[i]))) {
|
||||
row = i;
|
||||
break;
|
||||
}
|
||||
const prefix = stripAnsi(rows[row]).match(new RegExp(String.raw`^(\s*${escapeRegex(chrome.promptGlyph)}[ \u00a0])`));
|
||||
if (!prefix || Number(caret[1]) !== row + 1 || Number(caret[2]) !== visibleWidth(prefix[1] + composer) + 1)
|
||||
return null;
|
||||
return { composer, prefixWidth: visibleWidth(prefix[1]) };
|
||||
}
|
||||
|
||||
export class GuardedStageStore {
|
||||
private readonly receipts = new Map<string, Receipt>();
|
||||
private readonly busy = new Set<string>();
|
||||
private readonly settleTimeoutMs: number;
|
||||
private readonly settleIntervalMs: number;
|
||||
private readonly sleep: (ms: number) => Promise<void>;
|
||||
constructor(
|
||||
private readonly now = Date.now,
|
||||
private readonly capacity = 1024,
|
||||
private readonly ttlMs = 120000,
|
||||
settle: StageSettleOptions = {}
|
||||
) {
|
||||
this.settleTimeoutMs = settle.timeoutMs ?? STAGE_SETTLE_TIMEOUT_MS;
|
||||
this.settleIntervalMs = settle.intervalMs ?? STAGE_SETTLE_INTERVAL_MS;
|
||||
this.sleep = settle.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
||||
}
|
||||
async stage(target: GuardedInputTarget, owner: string, message: string) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const hasControls = /[\x00-\x1f\x7f-\x9f]/.test(message);
|
||||
if (
|
||||
!message ||
|
||||
message !== message.trimEnd() ||
|
||||
Buffer.byteLength(message) > STAGE_MAX_BYTES ||
|
||||
Buffer.from(message).toString('utf8') !== message ||
|
||||
hasControls
|
||||
)
|
||||
throw new GuardedInputConflict(
|
||||
'Stage requires printable single-line input within 8192 UTF8 bytes, without trailing whitespace'
|
||||
);
|
||||
const chrome = target.chrome();
|
||||
const refusal = chrome && composerTriggerRefusal(message, chrome);
|
||||
if (refusal) throw new GuardedInputConflict(refusal);
|
||||
const key = target.id;
|
||||
if (this.busy.has(key)) throw new GuardedInputConflict('Another guarded input operation is in progress');
|
||||
this.busy.add(key);
|
||||
try {
|
||||
const before = target.snapshot();
|
||||
if (!before || before.composerSha !== promptSha256(''))
|
||||
throw new GuardedInputConflict('An empty, verifiable composer is required');
|
||||
if (!Number.isFinite(before.availableColumns) || visibleWidth(message) >= before.availableColumns)
|
||||
throw new GuardedInputConflict('Message would reach the pane edge or wrap; shorten it or widen the pane');
|
||||
for (const [id, receipt] of this.receipts)
|
||||
if (receipt.expiresAt <= this.now() || receipt.sessionId === target.id) this.receipts.delete(id);
|
||||
// Refuse capacity before typing. Do not evict a caller's still-live receipt.
|
||||
// Include in-flight stages (this operation already owns one busy slot),
|
||||
// so different sessions cannot type concurrently into the same last slot.
|
||||
if (this.receipts.size + this.busy.size > this.capacity)
|
||||
throw new GuardedInputConflict('Guarded stage receipt capacity reached');
|
||||
if (!(await target.write(message)))
|
||||
throw new GuardedInputConflict(`Staging delivery failed or ambiguous; ${MAY_BE_TYPED}`);
|
||||
const typedAt = this.now();
|
||||
const after = await this.settle(target, before, promptSha256(message));
|
||||
const stageId = randomUUID();
|
||||
const expiresAt = this.now() + this.ttlMs;
|
||||
const sha256 = promptSha256(message);
|
||||
this.receipts.set(stageId, { ...after, owner, sessionId: target.id, expiresAt, sha256, typedAt });
|
||||
return { stageId, sha256, expiresAt, sessionId: target.id, submitted: false as const };
|
||||
} finally {
|
||||
this.busy.delete(key);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* The first frame after the write that shows exactly this message, with the input
|
||||
* revision the write itself moved and nothing else changed. A null or stale frame
|
||||
* (the old composer, a half-painted one) is read again until the settle window
|
||||
* ends; a frame showing another writer's keystroke, a new pane lifecycle or a new
|
||||
* geometry is refused at once, since waiting cannot undo that.
|
||||
*/
|
||||
private async settle(
|
||||
target: GuardedInputTarget,
|
||||
before: GuardedInputSnapshot,
|
||||
expectedSha: string
|
||||
): Promise<GuardedInputSnapshot> {
|
||||
const deadline = this.now() + this.settleTimeoutMs;
|
||||
for (;;) {
|
||||
const frame = target.snapshot();
|
||||
if (
|
||||
frame &&
|
||||
(frame.generation !== before.generation ||
|
||||
frame.revision !== before.revision + 1 ||
|
||||
frame.availableColumns !== before.availableColumns)
|
||||
)
|
||||
throw new GuardedInputConflict(`Input or pane changed while staging; ${MAY_BE_TYPED}`);
|
||||
if (frame?.composerSha === expectedSha) return frame;
|
||||
if (this.now() >= deadline)
|
||||
throw new GuardedInputConflict(
|
||||
`The composer did not show the staged message within ${this.settleTimeoutMs} ms; ${MAY_BE_TYPED}`
|
||||
);
|
||||
await this.sleep(this.settleIntervalMs);
|
||||
}
|
||||
}
|
||||
async submit(target: GuardedInputTarget, owner: string, stageId: string, confirmSha: string) {
|
||||
const receipt = this.receipts.get(stageId);
|
||||
if (!receipt || receipt.owner !== owner || receipt.sessionId !== target.id)
|
||||
throw new GuardedInputConflict('Unknown, used, or foreign stage receipt');
|
||||
// One shot, even a wrong hash or unprovable composer. No retry of ambiguous Enter.
|
||||
this.receipts.delete(stageId);
|
||||
if (this.busy.has(target.id)) throw new GuardedInputConflict('Another guarded input operation is in progress');
|
||||
this.busy.add(target.id);
|
||||
try {
|
||||
if (receipt.expiresAt <= this.now() || receipt.sha256 !== confirmSha)
|
||||
throw new GuardedInputConflict('Expired stage receipt or confirmation hash mismatch');
|
||||
const quiet = receipt.typedAt + SUBMIT_QUIET_MS - this.now();
|
||||
if (quiet > 0) await this.sleep(quiet);
|
||||
const current = target.snapshot();
|
||||
if (
|
||||
!current ||
|
||||
current.generation !== receipt.generation ||
|
||||
current.revision !== receipt.revision ||
|
||||
current.availableColumns !== receipt.availableColumns ||
|
||||
current.composerSha !== receipt.sha256
|
||||
)
|
||||
throw new GuardedInputConflict('Staged composer, input, or pane identity changed; nothing submitted');
|
||||
if (!(await target.submit(current)))
|
||||
throw new GuardedInputConflict('Submission delivery failed or ambiguous; receipt consumed, inspect the pane');
|
||||
return { stageId, sessionId: target.id, submitted: true as const };
|
||||
} finally {
|
||||
this.busy.delete(target.id);
|
||||
}
|
||||
}
|
||||
clear(): void {
|
||||
this.receipts.clear();
|
||||
this.busy.clear();
|
||||
}
|
||||
}
|
||||
+151
-6
@@ -2,13 +2,15 @@
|
||||
* @fileoverview `codeman agent …` — session-to-session verbs for the agent running
|
||||
* inside a Codeman session, in every CLI mode.
|
||||
*
|
||||
* A thin HTTP client over endpoints that already exist (`quick-start` for a named
|
||||
* A thin HTTP client over the server's endpoints (`quick-start` for a named
|
||||
* case, `POST sessions` + `sessions/:id/interactive|shell` for a worker in an
|
||||
* existing directory, `input`, `wait`, `wait-output`, `last-response`, `terminal`,
|
||||
* `DELETE sessions/:id`, and the agent inbox: `inbox`, `inbox/ack`,
|
||||
* `agent-inbox/summary`). It
|
||||
* invents no route and no transport: everything goes through `CODEMAN_API_URL`, so
|
||||
* auth, ownership and the per-session waiter cap apply unchanged. The behaviour is
|
||||
* `DELETE sessions/:id`, the agent inbox: `inbox`, `inbox/ack`,
|
||||
* `agent-inbox/summary`, and the experimental, opt-in
|
||||
* `inspect`/`stage`/`submit` of `web/routes/agent-session-routes.ts`, which answer 403
|
||||
* until `agentCoordinationEnabled` is on; that refusal is printed verbatim). It uses no
|
||||
* transport of its own: everything goes through `CODEMAN_API_URL`, so auth, ownership
|
||||
* and the per-session waiter cap apply unchanged. The behaviour is
|
||||
* the packaged agent skill's (`skills/codeman`), ported from shell prose into code
|
||||
* with tests, so a `codex`/`opencode`/`pi` agent — which never gets the claude-only
|
||||
* preamble — has the same verbs from one line in its AGENTS.md.
|
||||
@@ -38,11 +40,14 @@
|
||||
*
|
||||
* @module cli-agent
|
||||
*/
|
||||
import { realpath, stat } from 'node:fs/promises';
|
||||
import { open, realpath, stat } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { resolve } from 'node:path';
|
||||
import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
import { isUtf8 } from 'node:buffer';
|
||||
import { STAGE_MAX_BYTES } from './agent-staging.js';
|
||||
import { INSPECT_MAX_BYTES } from './agent-inspection.js';
|
||||
import type { Command } from 'commander';
|
||||
import {
|
||||
basicAuthHeader,
|
||||
@@ -879,6 +884,103 @@ export async function agentWait(deps: AgentDeps, options: WaitOptions): Promise<
|
||||
return waitExitCode(data?.wait);
|
||||
}
|
||||
|
||||
/** Bounded incremental evidence, with an opaque server-owned cursor. */
|
||||
export async function agentInspect(
|
||||
deps: AgentDeps,
|
||||
options: { id: string; maxBytes: number; since?: string }
|
||||
): Promise<number> {
|
||||
if (!Number.isInteger(options.maxBytes) || options.maxBytes < 1 || options.maxBytes > INSPECT_MAX_BYTES)
|
||||
return fail(deps, '--max-bytes must be between 1 and 65536', EXIT.refused);
|
||||
const target = await resolveSessionId(deps, options.id);
|
||||
if ('error' in target) return fail(deps, target.error, target.code);
|
||||
const response = await deps.request(deps.ctx, {
|
||||
method: 'GET',
|
||||
path: `/api/v1/sessions/${encodeURIComponent(target.id)}/inspect`,
|
||||
query: { maxBytes: options.maxBytes, since: options.since },
|
||||
});
|
||||
if (!response.json?.success) return fail(deps, describeFailure(response));
|
||||
if (deps.json) emitJson(deps, response.json.data);
|
||||
else {
|
||||
const data = response.json.data as {
|
||||
source?: string;
|
||||
evidence?: string;
|
||||
truncated?: boolean;
|
||||
cursor?: string;
|
||||
blockedReason?: string;
|
||||
};
|
||||
deps.io.out(
|
||||
`[${data.source ?? 'unknown'}]${data.truncated ? ' truncated' : ''}${data.blockedReason ? ` (${data.blockedReason})` : ''}`
|
||||
);
|
||||
deps.io.out(data.evidence ?? '');
|
||||
if (data.cursor) deps.io.out(`cursor: ${data.cursor}`);
|
||||
}
|
||||
return EXIT.ok;
|
||||
}
|
||||
|
||||
/** Stage exactly the printable UTF8 file contents; never sends Enter. */
|
||||
export async function agentStage(deps: AgentDeps, options: { id: string; messageFile: string }): Promise<number> {
|
||||
if (isSelfSession(deps.ctx.selfId, options.id)) return fail(deps, `refusing: ${options.id} is me`, EXIT.refused);
|
||||
let message: string;
|
||||
try {
|
||||
const info = await stat(options.messageFile);
|
||||
if (!info.isFile() || info.size > STAGE_MAX_BYTES)
|
||||
return fail(deps, 'message file must be a regular file within 8192 UTF8 bytes', EXIT.refused);
|
||||
const handle = await open(options.messageFile, 'r');
|
||||
try {
|
||||
const buffer = Buffer.alloc(STAGE_MAX_BYTES + 1);
|
||||
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
||||
const bytes = buffer.subarray(0, bytesRead);
|
||||
if (bytesRead > STAGE_MAX_BYTES || !isUtf8(bytes))
|
||||
return fail(deps, 'message file must contain at most 8192 bytes of UTF8', EXIT.refused);
|
||||
message = bytes.toString('utf8');
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
} catch (error) {
|
||||
return fail(deps, `cannot read message file: ${getErrorMessage(error)}`, EXIT.refused);
|
||||
}
|
||||
const refusal = inputRefusal(message);
|
||||
if (refusal || message !== message.trimEnd())
|
||||
return fail(deps, refusal ?? 'stage refuses trailing whitespace', EXIT.refused);
|
||||
const target = await resolveSessionId(deps, options.id);
|
||||
if ('error' in target) return fail(deps, target.error, target.code);
|
||||
const response = await deps.request(deps.ctx, {
|
||||
method: 'POST',
|
||||
path: `/api/v1/sessions/${encodeURIComponent(target.id)}/stage`,
|
||||
body: { message },
|
||||
});
|
||||
if (!response.json?.success) return fail(deps, describeFailure(response));
|
||||
if (deps.json) emitJson(deps, response.json.data);
|
||||
else {
|
||||
const data = response.json.data as { stageId: string; sha256: string; expiresAt: number };
|
||||
deps.io.out(
|
||||
`staged (no Enter): ${data.stageId}\nsha256: ${data.sha256}\nexpires: ${new Date(data.expiresAt).toISOString()}`
|
||||
);
|
||||
}
|
||||
return EXIT.ok;
|
||||
}
|
||||
|
||||
/** Submit one verified staged composer; failure never automatically replays Enter. */
|
||||
export async function agentSubmit(
|
||||
deps: AgentDeps,
|
||||
options: { id: string; stageId: string; confirmSha: string }
|
||||
): Promise<number> {
|
||||
if (isSelfSession(deps.ctx.selfId, options.id)) return fail(deps, `refusing: ${options.id} is me`, EXIT.refused);
|
||||
if (!/^[a-f0-9]{64}$/.test(options.confirmSha) || !/^[a-f0-9-]{36}$/.test(options.stageId))
|
||||
return fail(deps, 'submit requires a stage UUID and its exact SHA-256', EXIT.refused);
|
||||
const target = await resolveSessionId(deps, options.id);
|
||||
if ('error' in target) return fail(deps, target.error, target.code);
|
||||
const response = await deps.request(deps.ctx, {
|
||||
method: 'POST',
|
||||
path: `/api/v1/sessions/${encodeURIComponent(target.id)}/submit`,
|
||||
body: { stageId: options.stageId, confirmSha: options.confirmSha },
|
||||
});
|
||||
if (!response.json?.success) return fail(deps, describeFailure(response));
|
||||
if (deps.json) emitJson(deps, response.json.data);
|
||||
else deps.io.out('Enter delivered once; inspect or wait for acceptance (no automatic retry).');
|
||||
return EXIT.ok;
|
||||
}
|
||||
|
||||
export interface ReadOptions {
|
||||
id: string;
|
||||
/** Bytes of raw terminal to fetch; ANSI is stripped for humans. */
|
||||
@@ -1297,6 +1399,49 @@ export function registerAgentCommands(program: Command): Command {
|
||||
)
|
||||
);
|
||||
|
||||
agent
|
||||
.command('inspect <id>')
|
||||
.description(
|
||||
'Experimental, opt-in (agentCoordinationEnabled): bounded transcript evidence or a labeled pane snapshot; opaque incremental cursors'
|
||||
)
|
||||
.option('--max-bytes <n>', 'UTF8 evidence budget (1–65536)', '8192')
|
||||
.option('--since <cursor>', 'Resume a cursor from the same owner, pane and transcript')
|
||||
.option('--json', 'Machine-readable output')
|
||||
.action((id: string, options: { maxBytes: string; since?: string; json?: boolean }) =>
|
||||
run(Boolean(options.json), (deps) =>
|
||||
agentInspect(deps, {
|
||||
id,
|
||||
maxBytes: parsePositiveInt(options.maxBytes, 8192, '--max-bytes'),
|
||||
since: options.since,
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
agent
|
||||
.command('stage <id>')
|
||||
.description(
|
||||
'Experimental, opt-in (agentCoordinationEnabled): type a printable single-line UTF8 file without Enter; requires a verifiable local Codex composer, and refuses slash or shell commands and a last word starting with @ or $ (use send)'
|
||||
)
|
||||
.requiredOption('--message-file <path>', 'Regular UTF8 file, at most 8192 bytes, no trailing newline')
|
||||
.option('--json', 'Machine-readable output')
|
||||
.action((id: string, options: { messageFile: string; json?: boolean }) =>
|
||||
run(Boolean(options.json), (deps) => agentStage(deps, { id, messageFile: options.messageFile }))
|
||||
);
|
||||
|
||||
agent
|
||||
.command('submit <id>')
|
||||
.description(
|
||||
'Experimental, opt-in (agentCoordinationEnabled): send Enter once only when the staged composer, pane and hash still match'
|
||||
)
|
||||
.requiredOption('--stage-id <receipt>', 'One-shot stage receipt')
|
||||
.requiredOption('--confirm-sha <hash>', 'Exact SHA-256 returned by stage')
|
||||
.option('--json', 'Machine-readable output')
|
||||
.action((id: string, options: { stageId: string; confirmSha: string; json?: boolean }) =>
|
||||
run(Boolean(options.json), (deps) =>
|
||||
agentSubmit(deps, { id, stageId: options.stageId, confirmSha: options.confirmSha })
|
||||
)
|
||||
);
|
||||
|
||||
agent
|
||||
.command('read <id>')
|
||||
.description("Print a session's last answer (as the server reads it for that mode) or, with --tail, its terminal")
|
||||
|
||||
@@ -384,6 +384,35 @@ const capabilitiesSchema = z
|
||||
// marker but never the footer. Still bounded, since it is also how much text the
|
||||
// pattern runs over.
|
||||
blockedLines: z.number().int().min(1).max(24).optional(),
|
||||
// Same guard again: run over the rows under the composer each time guarded
|
||||
// input reads the pane, and ~/.codeman/clis.json can set it.
|
||||
composerFooterLine: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(
|
||||
(src) => compileVersionRegex(src) !== null,
|
||||
'composerFooterLine must be a regex compileVersionRegex() accepts: at most 200 characters, no nested quantifiers'
|
||||
)
|
||||
.optional(),
|
||||
// Same guard again: run over the rows just above the composer by the same reads.
|
||||
composerPopupLine: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(
|
||||
(src) => compileVersionRegex(src) !== null,
|
||||
'composerPopupLine must be a regex compileVersionRegex() accepts: at most 200 characters, no nested quantifiers'
|
||||
)
|
||||
.optional(),
|
||||
// Single ASCII punctuation characters, never letters, digits or whitespace: each one
|
||||
// refuses every message that starts (or whose last word starts) with it.
|
||||
composerCommandPrefixes: z
|
||||
.string()
|
||||
.regex(/^[!-/:-@[-`{-~]{1,8}$/, 'composerCommandPrefixes must be 1 to 8 ASCII punctuation characters')
|
||||
.optional(),
|
||||
composerCompletionSigils: z
|
||||
.string()
|
||||
.regex(/^[!-/:-@[-`{-~]{1,8}$/, 'composerCompletionSigils must be 1 to 8 ASCII punctuation characters')
|
||||
.optional(),
|
||||
})
|
||||
.strict()
|
||||
// A window with nothing to search is a typo, not a configuration. Refused at LOAD
|
||||
|
||||
@@ -13,6 +13,14 @@
|
||||
import type { CliEntry } from './types.js';
|
||||
import { CODEX_REASONING_EFFORTS } from '../../types/session.js';
|
||||
|
||||
/**
|
||||
* Codex's footer effort words: every CODEX_REASONING_EFFORTS level plus `default` (what
|
||||
* codex prints when no effort is configured), as one regex alternation. Shared by the two
|
||||
* patterns that read that footer (`modelDetect.screenLine` and
|
||||
* `workDetect.composerFooterLine`), so a new level is a one-place edit.
|
||||
*/
|
||||
const CODEX_EFFORT_WORDS = [...CODEX_REASONING_EFFORTS, 'default'].join('|');
|
||||
|
||||
const HOME_DIRS = {
|
||||
local: '~/.local/bin',
|
||||
usrLocal: '/usr/local/bin',
|
||||
@@ -734,6 +742,34 @@ const CODEX: CliEntry = {
|
||||
watchingLines: 4,
|
||||
blockedLine: String.raw`(?:^|\n) {0,4}› \d\. [\s\S]*\n {2}(?:Press enter to confirm|tab (?:to add|or esc to clear) notes|enter continue)(?:[^\n]|\n {2}(?=[a-z←])){0,120}(?:cancel|interrupt|quit|back|answer|all)$`,
|
||||
blockedLines: 20,
|
||||
// The rows codex draws under an idle composer, tested one at a time by guarded
|
||||
// stage/submit (agent-staging.ts): the model footer (` gpt-5.6-terra default ·
|
||||
// ~/case`, effort words from CODEX_EFFORT_WORDS as in modelDetect below), the
|
||||
// `? for shortcuts` / `← for agents` hint row 0.162.0 adds at rest, and the older
|
||||
// `NN% context left` footer. Indented, so the `›` composer row itself never matches.
|
||||
composerFooterLine: String.raw`^\s+(?:\d+% context left|\? for shortcuts|← for agents|\S+ (?:${CODEX_EFFORT_WORDS}) · )`,
|
||||
// Read from codex-rs/tui/src/bottom_pane at rust-v0.162.0 (chat_composer/
|
||||
// popup_state.rs, composer_layout.rs and the popups' render code and snapshots):
|
||||
// every suggestion popup renders ABOVE the composer and keeps the footer below it,
|
||||
// so the footer alone cannot tell `› /stat` with the command list open from an
|
||||
// idle draft, and Enter then runs the highlighted `/status`. What sits in the
|
||||
// block just above the composer (past its blank top padding row):
|
||||
// command list (`/`) `› /status show current session ...`
|
||||
// ` /statusline configure which items ...`
|
||||
// skill and mention lists ` enter insert · esc close` (key-hint row)
|
||||
// (`$`, `@` with mentions on) ` enter/tab insert · esc close · ↑/↓ select · ←/→ filter`
|
||||
// file search (`@`) ` loading...` / ` no matches`, else bare path
|
||||
// rows, which no pattern can tell from prose
|
||||
// The last case is why stage also refuses the triggers themselves (below).
|
||||
composerPopupLine: String.raw`^ {0,2}(?:enter(?:/tab)? insert · esc close|loading\.\.\.$|no matches$)|^[› ] /[\w:-]+ {2,}\S`,
|
||||
// Same source. A draft starting with `/` is a slash command (the popup opens while
|
||||
// the caret is in its name, and Enter runs a command either way), and one starting
|
||||
// with `!` is a shell command (codex switches its prompt to `!` and runs it). Popups
|
||||
// open for the word under the caret only: `@` (file search, or the unified mention
|
||||
// list) and `$` (skills and mentions; whether a given `$word` opens it depends on
|
||||
// codex's skill catalog, so every `$` word is refused).
|
||||
composerCommandPrefixes: '/!',
|
||||
composerCompletionSigils: '@$',
|
||||
},
|
||||
// The footer under the composer, measured on a live 0.147.0 pane:
|
||||
// ` gpt-5.6-terra default · ~/codeman-cases/th-scratch` (model, reasoning effort,
|
||||
@@ -757,7 +793,7 @@ const CODEX: CliEntry = {
|
||||
// and the `›` composer, and a forged footer-shaped transcript line is not followed by
|
||||
// an indented row, so it is not read.
|
||||
modelDetect: {
|
||||
screenLine: String.raw`(?:^|\n) {2}([A-Za-z0-9][\w.:/@+-]{0,79}) (?:${[...CODEX_REASONING_EFFORTS, 'default'].join('|')}) · [^\n]*(?:\n {2}[^\n]*)?$`,
|
||||
screenLine: String.raw`(?:^|\n) {2}([A-Za-z0-9][\w.:/@+-]{0,79}) (?:${CODEX_EFFORT_WORDS}) · [^\n]*(?:\n {2}[^\n]*)?$`,
|
||||
screenLines: 2,
|
||||
},
|
||||
// App Settings → Codex model / reasoning effort (synced), filled into a LOCAL launch's
|
||||
|
||||
@@ -432,6 +432,39 @@ export interface CliCapabilities {
|
||||
* this is sized for the narrowest pane the CLI was measured at. Default 1.
|
||||
*/
|
||||
blockedLines?: number;
|
||||
/**
|
||||
* Source of a regex every non-blank row BELOW an idle composer must match (at most
|
||||
* three rows): the footer and hint rows this CLI draws there and nowhere else. It is
|
||||
* what lets the experimental guarded stage/submit routes (`agent-staging.ts`) prove
|
||||
* that the `promptGlyph` row they read is this CLI's own composer, at rest, and not
|
||||
* a dialog option or a transcript line the agent printed. A CLI that omits it never
|
||||
* takes guarded input: stage and submit refuse it. Tested one row at a time.
|
||||
*/
|
||||
composerFooterLine?: string;
|
||||
/**
|
||||
* Source of a regex matching a row of a suggestion popup this CLI draws directly
|
||||
* ABOVE its composer (a slash-command list, a file or mention search, its key-hint
|
||||
* row). The footer below such a composer is unchanged, so without this guarded
|
||||
* stage/submit would read the popup frame as an idle composer, and Enter would
|
||||
* accept the highlighted entry instead of sending the draft. Tested one row at a
|
||||
* time against the contiguous block just above the composer row, never further
|
||||
* up the pane: a match there refuses the frame. See `readGuardedComposer()`.
|
||||
*/
|
||||
composerPopupLine?: string;
|
||||
/**
|
||||
* Characters that, as the first character of a draft, make Enter run a command
|
||||
* rather than send a prompt (codex: `/` slash commands, `!` shell commands).
|
||||
* Guarded stage refuses such a message before typing; commands go through the
|
||||
* ordinary input route.
|
||||
*/
|
||||
composerCommandPrefixes?: string;
|
||||
/**
|
||||
* Characters that, starting the word under the caret, open a completion popup
|
||||
* whose highlighted entry Enter accepts (codex: `@` file and mention search, `$`
|
||||
* skills). Guarded stage refuses a message whose LAST word starts with one,
|
||||
* before typing: the caret ends there, and the popup follows the caret.
|
||||
*/
|
||||
composerCompletionSigils?: string;
|
||||
};
|
||||
/**
|
||||
* How many columns this CLI indents its transcript body by, so a copy taken from its
|
||||
|
||||
@@ -314,9 +314,10 @@ export interface TerminalMultiplexer extends EventEmitter {
|
||||
// ========== Input ==========
|
||||
|
||||
/**
|
||||
* Send input to a session via tmux send-keys.
|
||||
* Send input to a session via tmux send-keys. The optional internal Enter-only
|
||||
* guard runs synchronously immediately before transport dispatch.
|
||||
*/
|
||||
sendInput(sessionId: string, input: string): Promise<boolean>;
|
||||
sendInput(sessionId: string, input: string, options?: { beforeDispatch?: () => boolean }): Promise<boolean>;
|
||||
|
||||
// ========== Metadata ==========
|
||||
|
||||
|
||||
+303
-15
@@ -130,6 +130,14 @@ import { DEFAULT_TMUX_HISTORY_LIMIT } from './config/terminal-history.js';
|
||||
import { EXEC_TIMEOUT_MS } from './config/exec-timeout.js';
|
||||
import { getCli } from './config/cli-registry/registry.js';
|
||||
import { SubmitVerifier } from './session-submit-verifier.js';
|
||||
import {
|
||||
guardedComposerChrome,
|
||||
promptSha256,
|
||||
readGuardedSnapshotDetails,
|
||||
type GuardedInputSnapshot,
|
||||
} from './agent-staging.js';
|
||||
import { isKeyboardTerminalInput } from './terminal-input-classifier.js';
|
||||
import { stripAnsi } from './utils/regex-patterns.js';
|
||||
import { KEEP_WARM_NUDGE } from './prompt-cache-keepwarm.js';
|
||||
import { compileVersionRegex } from './config/cli-registry/patterns.js';
|
||||
import { resolveSessionCliVersion } from './utils/cli-resolver.js';
|
||||
@@ -458,6 +466,17 @@ export interface ClaudeMessage {
|
||||
duration_ms?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A write that a guarded submit's lease could not hold, because the per-lease hold
|
||||
* queue (`Session.MAX_GUARDED_HELD_INPUTS`) was full. Nothing was written; retry it.
|
||||
*/
|
||||
export class GuardedInputBusyError extends Error {
|
||||
constructor() {
|
||||
super('A guarded submit is in progress on this session; nothing was written. Retry the input.');
|
||||
this.name = 'GuardedInputBusyError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a programmatic write leaves the keep-alive turn running: the nudge itself, or a bare
|
||||
* Enter (which submits nothing new). Anything else carrying an Enter starts a turn of its own.
|
||||
@@ -1323,6 +1342,7 @@ export class Session extends EventEmitter {
|
||||
|
||||
/** Set the owning username (used by recovery to restore ownership). */
|
||||
set owner(username: string | undefined) {
|
||||
if (this._owner !== username) this._guardedPaneRevision++;
|
||||
this._owner = username;
|
||||
}
|
||||
|
||||
@@ -1427,11 +1447,13 @@ export class Session extends EventEmitter {
|
||||
* tmux session whose record is about to be deleted (Ark0N/Codeman#446).
|
||||
*/
|
||||
markClosing(closing: boolean): void {
|
||||
if (this._closing !== closing) this._guardedPaneRevision++;
|
||||
this._closing = closing;
|
||||
}
|
||||
|
||||
/** Run one pane start, attach or relaunch with {@link paneLifecycleInFlight} raised. */
|
||||
private async _withPaneLifecycle<T>(op: () => Promise<T>): Promise<T> {
|
||||
this._guardedPaneRevision++;
|
||||
this._paneLifecycleOps++;
|
||||
try {
|
||||
return await op();
|
||||
@@ -1458,6 +1480,7 @@ export class Session extends EventEmitter {
|
||||
* Ark0N/Codeman#446 review; both now persist on their success path.
|
||||
*/
|
||||
private clearPaneExitForNewPane(): void {
|
||||
this._guardedPaneRevision++;
|
||||
this.setPaneExit(undefined);
|
||||
if (this._muxSession) this._mux?.clearPaneExit?.(this._muxSession.muxName);
|
||||
}
|
||||
@@ -4255,6 +4278,11 @@ export class Session extends EventEmitter {
|
||||
prompt: string,
|
||||
options?: { model?: string; onProgress?: (info: { tokens?: number; status?: string }) => void }
|
||||
): Promise<{ result: string; cost: number }> {
|
||||
if (this.guardedInputHeld) {
|
||||
this._guardedInputRevision++;
|
||||
throw new Error('Guarded submission in progress');
|
||||
}
|
||||
this._guardedPaneRevision++;
|
||||
return new Promise((resolve, reject) => {
|
||||
if (this.ptyProcess) {
|
||||
reject(new Error('Session already has a running process'));
|
||||
@@ -4764,6 +4792,229 @@ export class Session extends EventEmitter {
|
||||
|
||||
// Note: checkAutoCompact/checkAutoClear moved to SessionAutoOps (this._autoOps)
|
||||
|
||||
private readonly _inspectionInstance = uuidv4();
|
||||
private _guardedPaneRevision = 0;
|
||||
private _guardedGeometryRevision = 0;
|
||||
private _guardedInputRevision = 0;
|
||||
private _guardedPendingWrites = 0;
|
||||
private _guardedSubmitInFlight = false;
|
||||
/**
|
||||
* Input that arrived while a guarded submit held the lease, in arrival order. Each
|
||||
* entry runs when the lease is released; an entry that returns a promise (a mux
|
||||
* write, a named key) is waited for before the next runs, so nothing overtakes it.
|
||||
*/
|
||||
private _guardedHeld: Array<{ run: () => void | Promise<unknown>; bytes: number }> = [];
|
||||
private _guardedHeldBytes = 0;
|
||||
/** True while the drain waits for a held asynchronous write to finish. */
|
||||
private _guardedHeldDraining = false;
|
||||
/** Held entries per lease. A lease lasts milliseconds; past this the caller backs off. */
|
||||
static readonly MAX_GUARDED_HELD_INPUTS = 256;
|
||||
/** Held bytes per lease (16 browser frames at the 64 KiB frame cap). */
|
||||
static readonly MAX_GUARDED_HELD_BYTES = 16 * 64 * 1024;
|
||||
/** Ephemeral identity, never persisted or based on a potentially reused pid alone. */
|
||||
get inspectionGeneration(): string {
|
||||
return `${this._inspectionInstance}:${this._guardedPaneRevision}:${this.owner ?? ''}`;
|
||||
}
|
||||
/** Staging additionally binds geometry; transcript cursors survive a terminal resize. */
|
||||
get guardedInputGeneration(): string {
|
||||
return `${this.inspectionGeneration}:${this._guardedGeometryRevision}`;
|
||||
}
|
||||
get guardedInputPendingWrites(): number {
|
||||
return this._guardedPendingWrites;
|
||||
}
|
||||
/**
|
||||
* True while a guarded submit holds the input lease (a few milliseconds). Input that
|
||||
* arrives in that span is held and written after it (see {@link guardedInputHeld}).
|
||||
*/
|
||||
get guardedSubmitInFlight(): boolean {
|
||||
return this._guardedSubmitInFlight;
|
||||
}
|
||||
/**
|
||||
* True while input is being held behind a guarded submit: the lease itself, or held
|
||||
* input not yet written after it. A write that is not routed through
|
||||
* {@link holdForGuardedLease} must refuse in this window, or it overtakes held input.
|
||||
* `write()` is the known exception: it refuses during the lease only, since the drain
|
||||
* writes held input through it, so a direct `write()` caller (cron's `paste` mode in
|
||||
* `cron/cron-service.ts`) can still land ahead of input that is draining.
|
||||
*/
|
||||
get guardedInputHeld(): boolean {
|
||||
return this._guardedSubmitInFlight || this._guardedHeld.length > 0 || this._guardedHeldDraining;
|
||||
}
|
||||
/**
|
||||
* Hold input behind a guarded submit's lease instead of refusing it.
|
||||
*
|
||||
* `free`: nothing is held, so the caller writes inline as it always did. `held`: `run`
|
||||
* is queued and runs, in arrival order with every other held input, once the lease is
|
||||
* released (whatever the submit's outcome). `full`: the per-lease cap is reached and
|
||||
* nothing was queued; the caller must stop delivering from that source until it can
|
||||
* resend in order. Refusing instead lost input: the browser's WebSocket path does not
|
||||
* wait for ACKs, so a refused seq N was overtaken by N+1 and its redelivery was then
|
||||
* rejected as a duplicate. `data`, when given, is observed as input on arrival, so a
|
||||
* keystroke held during the lease still moves the input revision at once.
|
||||
*/
|
||||
holdForGuardedLease(run: () => void | Promise<unknown>, bytes = 0, data?: string): 'free' | 'held' | 'full' {
|
||||
if (!this.guardedInputHeld) return 'free';
|
||||
if (data !== undefined) this._observeGuardedKeyboardInput(data);
|
||||
if (
|
||||
this._guardedHeld.length >= Session.MAX_GUARDED_HELD_INPUTS ||
|
||||
this._guardedHeldBytes + bytes > Session.MAX_GUARDED_HELD_BYTES
|
||||
)
|
||||
return 'full';
|
||||
this._guardedHeld.push({ run, bytes });
|
||||
this._guardedHeldBytes += bytes;
|
||||
return 'held';
|
||||
}
|
||||
/**
|
||||
* Run an asynchronous write now, or in its turn behind a guarded submit's lease. The
|
||||
* turn lasts until the write settles, so later held input waits for it. Resolves
|
||||
* `whenFull` without running anything when the hold queue is full.
|
||||
*/
|
||||
private _inGuardedTurn<T>(write: () => Promise<T>, whenFull: () => T): Promise<T> {
|
||||
if (!this.guardedInputHeld) return write();
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const held = this.holdForGuardedLease(() => {
|
||||
const running = write();
|
||||
running.then(resolve, reject);
|
||||
return running;
|
||||
});
|
||||
if (held === 'full') {
|
||||
try {
|
||||
resolve(whenFull());
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
/** Run held input in arrival order until it is all written or a new lease is taken. */
|
||||
private _drainGuardedHeld(): void {
|
||||
while (this._guardedHeld.length > 0 && !this._guardedSubmitInFlight && !this._guardedHeldDraining) {
|
||||
const entry = this._guardedHeld.shift()!;
|
||||
this._guardedHeldBytes -= entry.bytes;
|
||||
let running: void | Promise<unknown>;
|
||||
try {
|
||||
running = entry.run();
|
||||
} catch (err) {
|
||||
console.error(`[Session ${this.id}] held input failed after a guarded submit:`, getErrorMessage(err));
|
||||
continue;
|
||||
}
|
||||
if (running && typeof running.then === 'function') {
|
||||
this._guardedHeldDraining = true;
|
||||
void running
|
||||
.catch(() => {})
|
||||
.then(() => {
|
||||
this._guardedHeldDraining = false;
|
||||
this._drainGuardedHeld();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
/** Expose only the path selection needed for attributed Codex evidence, never credentials. */
|
||||
getCodexHomeOverride(): string | undefined {
|
||||
return this._envOverrides?.CODEX_HOME || undefined;
|
||||
}
|
||||
private _observeGuardedKeyboardInput(data: string): void {
|
||||
if (data && isKeyboardTerminalInput(data)) this._guardedInputRevision++;
|
||||
}
|
||||
guardedInputSnapshot(): GuardedInputSnapshot | null {
|
||||
return this._readGuardedInputSnapshot(false);
|
||||
}
|
||||
private _readGuardedInputSnapshot(allowLease: boolean): GuardedInputSnapshot | null {
|
||||
if (
|
||||
this._isStopped ||
|
||||
this._closing ||
|
||||
this.paneLifecycleInFlight ||
|
||||
this._guardedPendingWrites ||
|
||||
(!allowLease && this.guardedInputHeld) ||
|
||||
this.remote ||
|
||||
this.docker ||
|
||||
this.paneExit ||
|
||||
!this._muxSession
|
||||
)
|
||||
return null;
|
||||
// Only a CLI whose registry entry describes its composer chrome takes guarded input.
|
||||
const chrome = guardedComposerChrome(getCli(this.mode));
|
||||
if (!chrome) return null;
|
||||
const capture: import('./mux-interface.js').PaneCaptureOptions = {};
|
||||
const screen = this._mux?.capturePaneBuffer?.(this._muxSession.muxName, undefined, capture);
|
||||
if (!screen) return null;
|
||||
// tmux's replay has CUP addresses rather than line breaks. Read the SAME
|
||||
// fresh frame for dialog/work chrome and exact composer/caret proof.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const plain = stripAnsi(screen.replace(/\x1b\[\d+;\d+H/g, '\n'));
|
||||
const working = this._workingLinePattern();
|
||||
working.lastIndex = 0;
|
||||
if (this._paneShowsBlocked(plain) || working.test(plain) || this._paneAwaitsWorkers(plain)) return null;
|
||||
const composer = readGuardedSnapshotDetails(screen, chrome);
|
||||
return composer === null
|
||||
? null
|
||||
: {
|
||||
generation: this.guardedInputGeneration,
|
||||
revision: this._guardedInputRevision,
|
||||
composerSha: promptSha256(composer.composer),
|
||||
availableColumns: Number.isFinite(capture.capturedGeometry?.cols)
|
||||
? capture.capturedGeometry!.cols - composer.prefixWidth
|
||||
: 0,
|
||||
};
|
||||
}
|
||||
/** Stage through ordinary delivery, after cancelling any older Enter retry timer. */
|
||||
async stageGuardedInput(message: string): Promise<boolean> {
|
||||
if (/[\r\n]/.test(message)) return false;
|
||||
if (this._guardedPendingWrites || this.guardedInputHeld) {
|
||||
this._guardedInputRevision++;
|
||||
return false;
|
||||
}
|
||||
this._submitVerifier?.cancel();
|
||||
return this.writeViaMux(message, { fromUser: true });
|
||||
}
|
||||
/** One conditional Enter. An ambiguous acknowledgement is never replayed. */
|
||||
async submitGuardedInput(expected: GuardedInputSnapshot): Promise<boolean> {
|
||||
const matches = (current: GuardedInputSnapshot | null): boolean =>
|
||||
!!current &&
|
||||
current.generation === expected.generation &&
|
||||
current.revision === expected.revision &&
|
||||
current.composerSha === expected.composerSha &&
|
||||
current.availableColumns === expected.availableColumns;
|
||||
if (!matches(this.guardedInputSnapshot()) || !this._mux || !this._muxSession) return false;
|
||||
this._guardedSubmitInFlight = true;
|
||||
let dispatched = false;
|
||||
try {
|
||||
const sent = await this._mux.sendInput(this.id, '\r', {
|
||||
beforeDispatch: () => {
|
||||
if (!matches(this._readGuardedInputSnapshot(true))) return false;
|
||||
this._guardedInputRevision++;
|
||||
dispatched = true;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
if (sent && dispatched) this._emitSubmittedPrompt(this._trackSubmit('\r', { fromUser: true }));
|
||||
return sent && dispatched;
|
||||
} finally {
|
||||
this._guardedSubmitInFlight = false;
|
||||
this._drainGuardedHeld();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Lease/pending boundary for named keys whose bytes bypass the ordinary write methods.
|
||||
* During a guarded submit the operation waits for the lease like any other write;
|
||||
* only a full hold queue refuses it, with {@link GuardedInputBusyError}.
|
||||
*/
|
||||
async performAuxiliaryInput(operation: () => Promise<void>): Promise<void> {
|
||||
this._guardedInputRevision++;
|
||||
return this._inGuardedTurn(
|
||||
async () => {
|
||||
this._guardedPendingWrites++;
|
||||
try {
|
||||
await operation();
|
||||
} finally {
|
||||
this._guardedPendingWrites--;
|
||||
}
|
||||
},
|
||||
() => {
|
||||
throw new GuardedInputBusyError();
|
||||
}
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Sends input directly to the PTY process.
|
||||
*
|
||||
@@ -4783,6 +5034,9 @@ export class Session extends EventEmitter {
|
||||
* input could disappear while the caller believed it had been delivered.
|
||||
*/
|
||||
write(data: string, options: SessionWriteOptions = {}): boolean {
|
||||
this._observeGuardedKeyboardInput(data);
|
||||
// The lease only, not the drain, which writes held input through here (see guardedInputHeld).
|
||||
if (this._guardedSubmitInFlight) return false;
|
||||
const submittedPrompt = this._trackSubmit(data, options);
|
||||
if (!this.ptyProcess) return false;
|
||||
this.ptyProcess.write(data);
|
||||
@@ -4831,6 +5085,7 @@ export class Session extends EventEmitter {
|
||||
* separator. Reports submissions like a write would (a line feed never is one).
|
||||
*/
|
||||
trackUserInput(data: string): void {
|
||||
this._observeGuardedKeyboardInput(data);
|
||||
if (!this._acceptsPrompts) return;
|
||||
this._emitSubmittedPrompt(this._submittedPromptTracker.feed(data));
|
||||
}
|
||||
@@ -4852,6 +5107,7 @@ export class Session extends EventEmitter {
|
||||
* their prompt must count as real and alert normally.
|
||||
*/
|
||||
markPromptSubmitted(prompt?: string): void {
|
||||
this._guardedInputRevision++;
|
||||
if (prompt !== undefined && prompt.trim() !== KEEP_WARM_NUDGE) this._keepAliveTurnUntil = 0;
|
||||
this._stampSubmit();
|
||||
}
|
||||
@@ -4947,22 +5203,39 @@ export class Session extends EventEmitter {
|
||||
* ```
|
||||
*/
|
||||
async writeViaMux(data: string, options: SessionWriteOptions = {}): Promise<boolean> {
|
||||
const submittedPrompt = this._trackSubmit(data, options);
|
||||
if (this._mux && this._muxSession) {
|
||||
const sent = await this._mux.sendInput(this.id, data);
|
||||
if (sent) {
|
||||
this._emitSubmittedPrompt(submittedPrompt);
|
||||
this._verifySubmitted(data);
|
||||
this._observeGuardedKeyboardInput(data);
|
||||
// A guarded submit's lease lasts for its Enter only: wait for it, in arrival order,
|
||||
// rather than refusing, so an approval answer or a programmatic prompt is not
|
||||
// dropped. Without a lease the write starts synchronously, so the pending count
|
||||
// rises before any await and no lease can be taken while it is in flight.
|
||||
return this._inGuardedTurn(
|
||||
() => this._writeViaMuxNow(data, options),
|
||||
() => false
|
||||
);
|
||||
}
|
||||
|
||||
private async _writeViaMuxNow(data: string, options: SessionWriteOptions): Promise<boolean> {
|
||||
this._guardedPendingWrites++;
|
||||
try {
|
||||
const submittedPrompt = this._trackSubmit(data, options);
|
||||
if (this._mux && this._muxSession) {
|
||||
const sent = await this._mux.sendInput(this.id, data);
|
||||
if (sent) {
|
||||
this._emitSubmittedPrompt(submittedPrompt);
|
||||
this._verifySubmitted(data);
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
return sent;
|
||||
// Fallback to PTY write
|
||||
if (this.ptyProcess) {
|
||||
this.ptyProcess.write(data);
|
||||
this._emitSubmittedPrompt(submittedPrompt);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
this._guardedPendingWrites--;
|
||||
}
|
||||
// Fallback to PTY write
|
||||
if (this.ptyProcess) {
|
||||
this.ptyProcess.write(data);
|
||||
this._emitSubmittedPrompt(submittedPrompt);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4990,7 +5263,16 @@ export class Session extends EventEmitter {
|
||||
this._isStopped || !this._mux || !this._muxSession
|
||||
? null
|
||||
: this._mux.capturePaneText?.(this._muxSession.muxName),
|
||||
sendEnter: () => this._mux?.sendInput(this.id, '\r'),
|
||||
sendEnter: () => {
|
||||
// A retry Enter is never held behind a guarded submit: once that submit's
|
||||
// Enter went out, a re-press would submit whatever is on the composer next.
|
||||
if (this.guardedInputHeld) {
|
||||
this._guardedInputRevision++;
|
||||
this._submitVerifier?.cancel();
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
return this.writeViaMux('\r');
|
||||
},
|
||||
// ⚠ NO fallback glyph here, unlike the screen-reading probe elsewhere in this file.
|
||||
// Only claude, codex, pi, opencode, omp, gemini and antigravity declare a promptGlyph; the other modes would fall back
|
||||
// to claude's `❯`, which is ALSO starship's default shell prompt (and pure's, and
|
||||
@@ -5019,6 +5301,7 @@ export class Session extends EventEmitter {
|
||||
* `resize()` skipped a real resize that happened to match them.
|
||||
*/
|
||||
private _notePtySpawnGeometry(cols: number, rows: number): void {
|
||||
this._guardedPaneRevision++;
|
||||
this._ptyCols = cols;
|
||||
this._ptyRows = rows;
|
||||
}
|
||||
@@ -5141,6 +5424,7 @@ export class Session extends EventEmitter {
|
||||
}
|
||||
const dimsChanged = cols !== this._ptyCols || rows !== this._ptyRows;
|
||||
if (this.ptyProcess && (dimsChanged || options.force)) {
|
||||
this._guardedGeometryRevision++;
|
||||
this._ptyCols = cols;
|
||||
this._ptyRows = rows;
|
||||
if (!IS_TEST_MODE && this._mux && this._muxSession) {
|
||||
@@ -5157,6 +5441,10 @@ export class Session extends EventEmitter {
|
||||
|
||||
// Legacy method for sending input - wraps runPrompt
|
||||
async sendInput(input: string): Promise<void> {
|
||||
if (this.guardedInputHeld) {
|
||||
this._guardedInputRevision++;
|
||||
throw new Error('Guarded submission in progress');
|
||||
}
|
||||
this._status = 'busy';
|
||||
this._markActivity(true);
|
||||
this.runPrompt(input).catch((err) => {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/** @fileoverview Distinguish complete terminal focus/mouse reports from keyboard-bearing input. */
|
||||
const FOCUS_REPORT_LENGTH = 3;
|
||||
const X10_REPORT_LENGTH = 6;
|
||||
|
||||
function sgrMouseReportLength(rest: string): number {
|
||||
if (!rest.startsWith('\x1b[<')) return 0;
|
||||
|
||||
let offset = 3;
|
||||
for (let field = 0; field < 3; field += 1) {
|
||||
const digitStart = offset;
|
||||
while (offset < rest.length && rest.charCodeAt(offset) >= 48 && rest.charCodeAt(offset) <= 57) {
|
||||
offset += 1;
|
||||
}
|
||||
if (offset === digitStart) return 0;
|
||||
|
||||
if (field < 2) {
|
||||
if (rest[offset] !== ';') return 0;
|
||||
offset += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return rest[offset] === 'M' || rest[offset] === 'm' ? offset + 1 : 0;
|
||||
}
|
||||
|
||||
function x10MouseReportLength(rest: string): number {
|
||||
if (!rest.startsWith('\x1b[M') || rest.length < X10_REPORT_LENGTH) return 0;
|
||||
|
||||
const button = rest.charCodeAt(3);
|
||||
const x = rest.charCodeAt(4);
|
||||
const y = rest.charCodeAt(5);
|
||||
if (button < 32 || button > 255 || x < 33 || x > 255 || y < 33 || y > 255) return 0;
|
||||
|
||||
return X10_REPORT_LENGTH;
|
||||
}
|
||||
|
||||
function terminalReportLengthAt(data: string, offset: number): number {
|
||||
const rest = data.slice(offset);
|
||||
if (rest.startsWith('\x1b[I') || rest.startsWith('\x1b[O')) return FOCUS_REPORT_LENGTH;
|
||||
|
||||
const sgrLength = sgrMouseReportLength(rest);
|
||||
if (sgrLength > 0) return sgrLength;
|
||||
|
||||
return x10MouseReportLength(rest);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether terminal input contains any keyboard-bearing bytes.
|
||||
*
|
||||
* Returns false only when every byte is consumed as an allowlisted mouse or
|
||||
* focus report. Unknown, malformed, mixed, and empty input fails closed.
|
||||
*/
|
||||
export function isKeyboardTerminalInput(data: string): boolean {
|
||||
if (data.length === 0) return true;
|
||||
|
||||
let offset = 0;
|
||||
while (offset < data.length) {
|
||||
const reportLength = terminalReportLengthAt(data, offset);
|
||||
if (reportLength === 0) return true;
|
||||
offset += reportLength;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
+56
-9
@@ -984,6 +984,20 @@ export function formatCursorRestore(geometry: PaneCursorGeometry): string {
|
||||
return `${up > 0 ? `\x1b[${up}A` : ''}\r${right > 0 ? `\x1b[${right}C` : ''}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split the output of `capture-pane -p \; display-message -p '<cursor format>'`
|
||||
* into the captured rows and the cursor line, which tmux prints last. Null unless
|
||||
* that last line has the cursor query's shape (four leading integers), so a query
|
||||
* that printed nothing can never have the frame's own last row taken for it.
|
||||
*/
|
||||
export function splitFrameAndCursor(output: string): { frame: string; cursor: string } | null {
|
||||
const body = output.endsWith('\n') ? output.slice(0, -1) : output;
|
||||
const split = body.lastIndexOf('\n');
|
||||
const cursor = body.slice(split + 1);
|
||||
if (!/^\d+ \d+ \d+ \d+(?: |$)/.test(cursor)) return null;
|
||||
return { frame: body.slice(0, split + 1), cursor };
|
||||
}
|
||||
|
||||
export function formatPaneSnapshot(
|
||||
lines: string[],
|
||||
geometry: { cols: number; rows: number; cursorX: number; cursorY: number }
|
||||
@@ -3983,7 +3997,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
* - `Enter` key is sent as a SEPARATE tmux invocation after a small delay
|
||||
* - Ink (Claude CLI) needs text and Enter split to avoid treating Enter as a newline
|
||||
*/
|
||||
async sendInput(sessionId: string, input: string): Promise<boolean> {
|
||||
async sendInput(sessionId: string, input: string, options?: { beforeDispatch?: () => boolean }): Promise<boolean> {
|
||||
if (options?.beforeDispatch && input !== '\r') return false;
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) {
|
||||
console.error(
|
||||
@@ -3996,7 +4011,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
// inputRunner() so a test subclass can record what WOULD reach tmux.
|
||||
const run = this.inputRunner();
|
||||
if (!run) {
|
||||
return true;
|
||||
return options?.beforeDispatch?.() ?? true;
|
||||
}
|
||||
|
||||
console.log(
|
||||
@@ -4050,7 +4065,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
`${this.tmux()} send-keys -t "${session.muxName}" -l -- ${shellescape(escapeTmuxTrailingSemicolon(textPart))}`
|
||||
);
|
||||
} else if (hasCarriageReturn) {
|
||||
// Enter only
|
||||
// Enter only: no await between the guard and dispatch.
|
||||
if (options?.beforeDispatch && !options.beforeDispatch()) return false;
|
||||
await run(`${this.tmux()} send-keys -t "${session.muxName}" Enter`);
|
||||
}
|
||||
|
||||
@@ -4279,7 +4295,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
|
||||
capturePaneBuffer(muxName: string, paneTarget?: string, opts?: PaneCaptureOptions): string | null {
|
||||
if (IS_TEST_MODE) return '';
|
||||
const exec = this.captureRunner();
|
||||
if (!exec) return '';
|
||||
const target = resolveTmuxPaneTarget(muxName, paneTarget);
|
||||
if (!target) {
|
||||
console.error('[TmuxManager] Invalid pane target in capturePaneBuffer:', { muxName, paneTarget });
|
||||
@@ -4317,9 +4334,28 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
execOpts.maxBuffer =
|
||||
(opts?.maxCaptureBytes ?? DEFAULT_TERMINAL_BUFFER_MAX_BYTES) + FULL_HISTORY_CAPTURE_SLACK_BYTES;
|
||||
}
|
||||
const cursorQuery = `display-message -p -t ${shellescape(target)} '#{cursor_x} #{cursor_y} #{pane_width} #{pane_height} #{history_size} #{alternate_on}'`;
|
||||
const captureCommand = `${this.tmux()} ${captureFlags} -t ${shellescape(target)}`;
|
||||
// The visible frame and its caret come from ONE tmux invocation
|
||||
// (the capture, `\;`, then the cursor query): tmux runs a command list back to back
|
||||
// in its command queue, with no pane output parsed between the two, so the
|
||||
// caret belongs to the frame. Two separate calls raced the CLI's repaint: a
|
||||
// CLI that redraws its composer a few ms after input arrives (codex) could be
|
||||
// captured before the redraw and its caret queried after it, and guarded
|
||||
// stage then refused a frame the keys had already reached. Only output that
|
||||
// splitFrameAndCursor() cannot split (a last line that is not the query's)
|
||||
// falls back to the two separate calls, which is what this always did. A call
|
||||
// that THREW (a hung tmux timing out) goes to the catch below like any other
|
||||
// capture failure: retrying it would block the event loop for a second timeout
|
||||
// on every `GET .../terminal` load.
|
||||
const combined = fullHistory
|
||||
? null
|
||||
: splitFrameAndCursor(
|
||||
exec(`${captureCommand} \\; ${cursorQuery}`, { encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS })
|
||||
);
|
||||
const rawCapture = joinScrollbackAndFrame(
|
||||
scrollbackOverride,
|
||||
execSync(`${this.tmux()} ${captureFlags} -t ${shellescape(target)}`, execOpts),
|
||||
combined?.frame ?? exec(captureCommand, execOpts),
|
||||
scrollbackOverride !== undefined ? opts?.scrollbackOverrideScreen : undefined
|
||||
);
|
||||
// Query the cursor BEFORE deciding anything else. On the full-history path
|
||||
@@ -4327,10 +4363,9 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
// appended, and those two have to agree: trailing blank rows are only safe
|
||||
// to keep when a move follows to put the caret back above them.
|
||||
const geometry = queryPaneCursor(() =>
|
||||
execSync(
|
||||
`${this.tmux()} display-message -p -t ${shellescape(target)} '#{cursor_x} #{cursor_y} #{pane_width} #{pane_height} #{history_size} #{alternate_on}'`,
|
||||
{ encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS }
|
||||
)
|
||||
combined
|
||||
? combined.cursor
|
||||
: exec(`${this.tmux()} ${cursorQuery}`, { encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS })
|
||||
);
|
||||
// Report the size the pane was really drawing at. The visible-frame path
|
||||
// below addresses every row absolutely, so a consumer whose terminal is
|
||||
@@ -4396,6 +4431,18 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How {@link capturePaneBuffer} runs tmux, or null where it must not (vitest).
|
||||
* Split out like {@link inputRunner} so a test subclass can count and script the
|
||||
* calls a capture makes.
|
||||
*/
|
||||
protected captureRunner():
|
||||
| ((cmd: string, opts: { encoding: 'utf-8'; timeout: number; maxBuffer?: number }) => string)
|
||||
| null {
|
||||
if (IS_TEST_MODE) return null;
|
||||
return (cmd, opts) => execSync(cmd, opts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture the active pane for a tmux session.
|
||||
*
|
||||
|
||||
@@ -706,6 +706,9 @@
|
||||
'New sessions for this case land in this group': '此案例的新会话将放入此分组',
|
||||
'Could not save the default session group.': '无法保存默认会话分组。',
|
||||
'Remote auto-reconnect': '远程自动重连',
|
||||
'Experimental agent coordination': '实验性智能体协作',
|
||||
"Lets agents read another session's output in bounded pages and type a prompt into a local Codex composer, then press Enter once after checking it is unchanged (the inspect, stage and submit commands). Experimental: the commands and their HTTP routes may change in any release. Off by default; while off those routes refuse every request.":
|
||||
'允许智能体分页读取另一个会话的输出(每页有上限),并把提示词输入本地 Codex 输入框,确认未被改动后只按一次 Enter(即 inspect、stage 和 submit 命令)。实验性功能:这些命令及其 HTTP 路由可能在任何版本中变化。默认关闭;关闭时这些路由拒绝所有请求。',
|
||||
'Pin tab names on the CLI': '在 CLI 上固定标签名',
|
||||
"Launch every Claude session with its tab name, so the CLI's prompt label and /resume list match your tabs. Claude then stops generating its own titles for those sessions, and a rename in Codeman holds only until the next turn. Applies from the next session start or respawn, no server restart needed.":
|
||||
'以标签名启动每个 Claude 会话,让 CLI 的提示框标签和 /resume 列表与你的标签一致。Claude 随后不再为这些会话生成自己的标题,在 Codeman 中的重命名也只保留到下一轮。从下一次会话启动或重新生成时生效,无需重启服务器。',
|
||||
|
||||
@@ -2234,6 +2234,13 @@
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsAgentInboxPersist"><span class="slider"></span></label>
|
||||
</div>
|
||||
<div class="set-row" data-search="experimental agent coordination inspect stage submit codeman agent guarded input">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Experimental agent coordination</span>
|
||||
<span class="set-row-desc">Lets agents read another session's output in bounded pages and type a prompt into a local Codex composer, then press Enter once after checking it is unchanged (the inspect, stage and submit commands). Experimental: the commands and their HTTP routes may change in any release. Off by default; while off those routes refuse every request.</span>
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsAgentCoordination"><span class="slider"></span></label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -541,6 +541,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('appSettingsApprovalsInbox').checked = settings.approvalsInboxEnabled === true;
|
||||
// Agent inbox snapshot on disk: synced, default OFF.
|
||||
document.getElementById('appSettingsAgentInboxPersist').checked = settings.agentInboxPersistEnabled === true;
|
||||
// Experimental agent coordination (inspect/stage/submit routes): synced, default OFF.
|
||||
document.getElementById('appSettingsAgentCoordination').checked = settings.agentCoordinationEnabled === true;
|
||||
// Custom Model Endpoint Profiles: synced, default OFF. The toggle governs both
|
||||
// the Run-menu picker's generated entries and this settings panel's visibility;
|
||||
// the endpoint list itself is server state, loaded on demand below.
|
||||
@@ -2994,6 +2996,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
configBackupDir: document.getElementById('appSettingsConfigBackupDir').value.trim(),
|
||||
...this._configBackupRetentionPayload(_prev),
|
||||
agentInboxPersistEnabled: document.getElementById('appSettingsAgentInboxPersist').checked,
|
||||
agentCoordinationEnabled: document.getElementById('appSettingsAgentCoordination').checked,
|
||||
readMyMindEnabled: document.getElementById('appSettingsReadMyMind').checked,
|
||||
ultracodeFloatingWindows: document.getElementById('appSettingsUltracodeFloatingWindows').checked,
|
||||
showMultiMonitorButton: document.getElementById('appSettingsShowMultiMonitorButton').checked,
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* @fileoverview Agent-facing bounded inspection and guarded stage/submit endpoints.
|
||||
* Ownership is checked before any disk or pane read. Native evidence comes only
|
||||
* from strict conversation attribution; all other modes get labeled snapshots.
|
||||
*
|
||||
* Experimental and opt-in: all three routes answer `403 FORBIDDEN`, naming the
|
||||
* setting, until the synced `agentCoordinationEnabled` is on (default OFF), the
|
||||
* same shape as `cliManagementEnabled` and `mcpSyncEnabled`. The gate runs first,
|
||||
* before session lookup, so a disabled install reveals nothing about its sessions.
|
||||
*/
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { Session } from '../../session.js';
|
||||
import type { SessionPort, InfraPort } from '../ports/index.js';
|
||||
import { getCli } from '../../config/cli-registry/registry.js';
|
||||
import { findExactCodexConversation, resolveEffectiveCodexHome } from '../../agent-codex-identity.js';
|
||||
import { InspectionReader, InspectionConflict, boundedUtf8Tail } from '../../agent-inspection.js';
|
||||
import {
|
||||
GuardedStageStore,
|
||||
GuardedInputConflict,
|
||||
guardedComposerChrome,
|
||||
MAY_BE_TYPED,
|
||||
type GuardedInputTarget,
|
||||
} from '../../agent-staging.js';
|
||||
import { ApiErrorCode, createErrorResponse, type ApiResponse } from '../../types.js';
|
||||
import { findSessionOrFail, getAuthUser, parseBody, readJsonConfig, SETTINGS_PATH } from '../route-helpers.js';
|
||||
import { AgentInspectQuerySchema, AgentStageSchema, AgentSubmitSchema } from '../schemas.js';
|
||||
|
||||
/** Default OFF, same shape as `readMcpSyncEnabled`: read fresh so a toggle applies at once. */
|
||||
export async function readAgentCoordinationEnabled(): Promise<boolean> {
|
||||
const settings = await readJsonConfig<Record<string, unknown>>(SETTINGS_PATH, 'settings.json', {});
|
||||
return settings.agentCoordinationEnabled === true;
|
||||
}
|
||||
|
||||
/** The refusal every route sends while the setting is off. Exported for the tests. */
|
||||
export const AGENT_COORDINATION_DISABLED_MESSAGE =
|
||||
'Experimental agent coordination (inspect, stage, submit) is disabled. Turn on "Experimental agent coordination" in Settings (agentCoordinationEnabled) and save first.';
|
||||
|
||||
async function gate(): Promise<ApiResponse<never> | null> {
|
||||
if (await readAgentCoordinationEnabled()) return null;
|
||||
return createErrorResponse(ApiErrorCode.FORBIDDEN, AGENT_COORDINATION_DISABLED_MESSAGE);
|
||||
}
|
||||
|
||||
/** A Node error code (`EACCES`, `EIO`, ...) or the error's class name; never its message. */
|
||||
export function errorCode(error: unknown): string {
|
||||
const code = (error as { code?: unknown } | null)?.code;
|
||||
if (typeof code === 'string' && /^[A-Z0-9_]{1,40}$/.test(code)) return code;
|
||||
return error instanceof Error ? error.constructor.name : 'unknown';
|
||||
}
|
||||
|
||||
export function registerAgentSessionRoutes(app: FastifyInstance, ctx: SessionPort & InfraPort): void {
|
||||
const reader = new InspectionReader();
|
||||
const stages = new GuardedStageStore();
|
||||
app.addHook('onClose', async () => {
|
||||
reader.clear();
|
||||
stages.clear();
|
||||
});
|
||||
const generation = (session: Session) => session.inspectionGeneration;
|
||||
const target = (session: Session): GuardedInputTarget => ({
|
||||
id: session.id,
|
||||
chrome: () => guardedComposerChrome(getCli(session.mode)),
|
||||
snapshot: () => {
|
||||
if (ctx.sessions.get(session.id) !== session) return null;
|
||||
const snapshot = session.guardedInputSnapshot?.();
|
||||
return snapshot ?? null;
|
||||
},
|
||||
write: (text) => session.stageGuardedInput(text),
|
||||
submit: (expected) => session.submitGuardedInput(expected),
|
||||
});
|
||||
app.get('/api/sessions/:id/inspect', async (req, reply) => {
|
||||
const refused = await gate();
|
||||
if (refused) return reply.code(403).send(refused);
|
||||
const { id } = req.params as { id: string };
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
const { maxBytes, since } = parseBody(AgentInspectQuerySchema, req.query);
|
||||
const initialGeneration = generation(session);
|
||||
const identity = { sessionId: session.id, mode: session.mode };
|
||||
const activity = { status: session.status, lastSubmitAt: session.lastSubmitAt || null, observedAt: Date.now() };
|
||||
try {
|
||||
if (getCli(session.mode)?.capabilities.transcript === 'codex-rollout' && !session.remote && !session.docker) {
|
||||
const conversation = await findExactCodexConversation(
|
||||
{
|
||||
codexHome: resolveEffectiveCodexHome(session.getCodexHomeOverride(), session.workingDir),
|
||||
sessionId: session.id,
|
||||
workingDir: session.workingDir,
|
||||
resumeSessionId: session.codexConfig?.resumeSessionId,
|
||||
},
|
||||
{ maxEntries: 8192, maxBytes: 1048576 }
|
||||
);
|
||||
if (generation(session) !== initialGeneration || ctx.sessions.get(id) !== session)
|
||||
throw new InspectionConflict('Session changed during inspection');
|
||||
if (conversation) {
|
||||
const result = await reader.read(
|
||||
conversation.path,
|
||||
{
|
||||
owner: getAuthUser(req).username,
|
||||
sessionId: id,
|
||||
generation: initialGeneration,
|
||||
conversationId: conversation.id,
|
||||
},
|
||||
maxBytes,
|
||||
since
|
||||
);
|
||||
if (generation(session) !== initialGeneration || ctx.sessions.get(id) !== session)
|
||||
throw new InspectionConflict('Session changed during inspection');
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
source: 'codex-jsonl',
|
||||
identity: { ...identity, conversationId: conversation.id },
|
||||
activity,
|
||||
incremental: true,
|
||||
maxBytes,
|
||||
...result,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
if (since)
|
||||
throw new InspectionConflict('Attributed transcript unavailable; this cursor cannot resume a pane snapshot');
|
||||
const frame = session.muxName ? ctx.mux.capturePaneText?.(session.muxName) : null;
|
||||
const evidence = frame ?? session.terminalBuffer;
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
source: 'pane-snapshot',
|
||||
identity,
|
||||
activity,
|
||||
incremental: false,
|
||||
cursor: null,
|
||||
maxBytes,
|
||||
evidence: boundedUtf8Tail(evidence, maxBytes),
|
||||
truncated: evidence.length > maxBytes || Buffer.byteLength(evidence) > maxBytes,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof InspectionConflict)
|
||||
return reply.code(409).send(createErrorResponse(ApiErrorCode.CONFLICT, error.message));
|
||||
// Anything else (an unreadable rollout, an IO error) is not a retryable cursor
|
||||
// conflict. Log the session and the error code only: the message can carry the
|
||||
// native transcript path, which must never reach the log or the response.
|
||||
console.warn(`[agent-inspect] session ${session.id}: inspection failed (${errorCode(error)})`);
|
||||
return reply.code(422).send(createErrorResponse(ApiErrorCode.OPERATION_FAILED, 'Inspection source unavailable'));
|
||||
}
|
||||
});
|
||||
app.post('/api/sessions/:id/stage', async (req, reply) => {
|
||||
const refused = await gate();
|
||||
if (refused) return reply.code(403).send(refused);
|
||||
const session = findSessionOrFail(ctx, (req.params as { id: string }).id, req);
|
||||
const { message } = parseBody(AgentStageSchema, req.body);
|
||||
try {
|
||||
const receipt = await stages.stage(target(session), getAuthUser(req).username, message);
|
||||
return { success: true, data: receipt };
|
||||
} catch (error) {
|
||||
if (!(error instanceof GuardedInputConflict))
|
||||
console.warn(`[agent-stage] session ${session.id}: delivery failed (${errorCode(error)})`);
|
||||
return reply
|
||||
.code(409)
|
||||
.send(
|
||||
createErrorResponse(
|
||||
ApiErrorCode.CONFLICT,
|
||||
error instanceof GuardedInputConflict
|
||||
? error.message
|
||||
: `Stage delivery failed or ambiguous; ${MAY_BE_TYPED}`
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
app.post('/api/sessions/:id/submit', async (req, reply) => {
|
||||
const refused = await gate();
|
||||
if (refused) return reply.code(403).send(refused);
|
||||
const session = findSessionOrFail(ctx, (req.params as { id: string }).id, req);
|
||||
const { stageId, confirmSha } = parseBody(AgentSubmitSchema, req.body);
|
||||
try {
|
||||
return {
|
||||
success: true,
|
||||
data: await stages.submit(target(session), getAuthUser(req).username, stageId, confirmSha),
|
||||
};
|
||||
} catch (error) {
|
||||
if (!(error instanceof GuardedInputConflict))
|
||||
console.warn(`[agent-submit] session ${session.id}: delivery failed (${errorCode(error)})`);
|
||||
return reply
|
||||
.code(409)
|
||||
.send(
|
||||
createErrorResponse(
|
||||
ApiErrorCode.CONFLICT,
|
||||
error instanceof GuardedInputConflict
|
||||
? error.message
|
||||
: 'Submit delivery failed or ambiguous; receipt consumed, inspect the pane'
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -47,3 +47,5 @@ export {
|
||||
type CustomModelSwapDisplacement,
|
||||
} from './custom-model-routes.js';
|
||||
export { registerCliRegistryRoutes, readCliManagementEnabled, type CliListItem } from './cli-registry-routes.js';
|
||||
|
||||
export { registerAgentSessionRoutes } from './agent-session-routes.js';
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
type RemoteHost,
|
||||
} from '../../types.js';
|
||||
import {
|
||||
GuardedInputBusyError,
|
||||
Session,
|
||||
cliTakesSessionModel,
|
||||
isAltScreenStripMode,
|
||||
@@ -2078,6 +2079,32 @@ export function registerSessionRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
// A guarded submit (agent-staging.ts) holds the input lease for the few
|
||||
// milliseconds of its conditional Enter, and input that arrives meanwhile is held
|
||||
// and written in arrival order after it. A TAGGED request is refused for that span
|
||||
// (the lease plus the held input's drain) rather than overtake held input: say so
|
||||
// instead of answering 200 for bytes that were never written, and give the seq
|
||||
// back so the browser's durable queue (which keeps a frame on any 409, and whose
|
||||
// POST drainer sends one frame at a time) delivers it on its next retry. An
|
||||
// UNTAGGED request has no retry behind it (the phone accessory keys and the Stop
|
||||
// button's Ctrl+C are fire-and-forget POSTs that never read the answer), so it is
|
||||
// held instead, like a WebSocket frame: `writeViaMux` takes its own turn behind
|
||||
// the lease, and the raw write below is held explicitly. Nothing from here to the
|
||||
// write below awaits, so the lease cannot be taken in between.
|
||||
const refuseGuarded = () =>
|
||||
reply
|
||||
.code(409)
|
||||
.send(
|
||||
createErrorResponse(
|
||||
ApiErrorCode.CONFLICT,
|
||||
'A guarded submit is in progress on this session; nothing was written. Retry the input.'
|
||||
)
|
||||
);
|
||||
if (!duplicate && tagged && session.guardedInputHeld === true) {
|
||||
session.forgetInputSeq(clientId as string, seq as number);
|
||||
return refuseGuarded();
|
||||
}
|
||||
|
||||
// Only a waiting request pays for the tmux probe: the browser's plain input path
|
||||
// (thousands of calls per session) must stay exec-free.
|
||||
const workerDead = wantsWait && workerIsDead(ctx.mux, session);
|
||||
@@ -2188,7 +2215,38 @@ export function registerSessionRoutes(
|
||||
// Same rollback. NOT an error response, deliberately: a session can
|
||||
// legitimately have no PTY yet (created but not started), and callers have
|
||||
// always been able to write to one without a 4xx.
|
||||
delivered = session.write(inputStr, { fromUser: true });
|
||||
//
|
||||
// During a guarded submit (untagged only: a tagged one was refused above) the
|
||||
// write is held and runs in arrival order once the lease is released. The answer
|
||||
// is a 200 once held; a send-and-wait reads `delivered` from the held write. Only
|
||||
// a full hold queue refuses, after releasing the waiter registered above.
|
||||
let heldWrite: Promise<boolean> | null = null;
|
||||
if (session.guardedInputHeld === true) {
|
||||
let settle!: (written: boolean) => void;
|
||||
const written = new Promise<boolean>((resolve) => {
|
||||
settle = resolve;
|
||||
});
|
||||
const held = session.holdForGuardedLease(
|
||||
() => {
|
||||
let ok = false;
|
||||
try {
|
||||
ok = session.write(inputStr, { fromUser: true });
|
||||
} finally {
|
||||
settle(ok);
|
||||
}
|
||||
},
|
||||
inputStr.length,
|
||||
inputStr
|
||||
);
|
||||
if (held === 'full') {
|
||||
abort.abort();
|
||||
stopDeathWatch();
|
||||
return refuseGuarded();
|
||||
}
|
||||
if (held === 'held') heldWrite = written;
|
||||
}
|
||||
if (heldWrite && !waitPromise) return {};
|
||||
delivered = heldWrite ? await heldWrite : session.write(inputStr, { fromUser: true });
|
||||
if (!delivered && tagged) {
|
||||
session.forgetInputSeq(clientId as string, seq as number);
|
||||
}
|
||||
@@ -2399,7 +2457,7 @@ export function registerSessionRoutes(
|
||||
// own `capabilities.newline`. Claude Code's Ink input recognizes 0x0a as "insert newline" vs
|
||||
// 0x0d (carriage return = submit).
|
||||
|
||||
app.post('/api/sessions/:id/send-key', async (req) => {
|
||||
app.post('/api/sessions/:id/send-key', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const body = req.body as Record<string, unknown>;
|
||||
const key = typeof body?.key === 'string' ? body.key : '';
|
||||
@@ -2429,18 +2487,26 @@ export function registerSessionRoutes(
|
||||
try {
|
||||
// Route through the dedicated Codeman socket — bare `tmux` would target the
|
||||
// user's default server and never find this session (same #80 regression class).
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
execFile(
|
||||
'tmux',
|
||||
['-L', ctx.mux.muxSocket, 'send-keys', '-H', '-t', muxName, ...hex],
|
||||
{ timeout: 5000 },
|
||||
(err) => {
|
||||
if (err) reject(err);
|
||||
else resolve();
|
||||
}
|
||||
);
|
||||
});
|
||||
await session.performAuxiliaryInput(
|
||||
() =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
execFile(
|
||||
'tmux',
|
||||
['-L', ctx.mux.muxSocket, 'send-keys', '-H', '-t', muxName, ...hex],
|
||||
{ timeout: 5000 },
|
||||
(err) => {
|
||||
if (err) reject(err);
|
||||
else resolve();
|
||||
}
|
||||
);
|
||||
})
|
||||
);
|
||||
} catch (err) {
|
||||
// A guarded submit's lease holds the key until its Enter is out; only a full
|
||||
// hold queue refuses it, and that is a retryable conflict, not a tmux failure.
|
||||
if (err instanceof GuardedInputBusyError) {
|
||||
return reply.code(409).send(createErrorResponse(ApiErrorCode.CONFLICT, err.message));
|
||||
}
|
||||
console.error('[Server] send-key failed:', err);
|
||||
return createErrorResponse(ApiErrorCode.INTERNAL_ERROR, 'tmux send-keys failed');
|
||||
}
|
||||
|
||||
+83
-45
@@ -29,6 +29,11 @@
|
||||
* {"t":"i","d":"...","seq":N,"cid":"..."} — input (keystroke or paste). seq+cid are
|
||||
* optional reliable-delivery tags: the server applies each
|
||||
* (cid,seq) at-most-once and ACKs with {"t":"ia","seq":N}.
|
||||
* A frame that arrives while a guarded submit holds the
|
||||
* session's input lease is held, then applied and ACKed in
|
||||
* arrival order once it is released; when that hold queue
|
||||
* is full the socket is closed with 1013 and nothing later
|
||||
* from it is applied, so the client resends in order.
|
||||
* {"t":"z","c":N,"r":N,"f":bool} — resize terminal (f=true forces SIGWINCH even if dims unchanged)
|
||||
*/
|
||||
|
||||
@@ -169,12 +174,69 @@ export function registerWsRoutes(app: FastifyInstance, ctx: SessionPort, getHost
|
||||
const sizingToken = Symbol('ws-desktop-sizing');
|
||||
let holdsDesktopClaim = false;
|
||||
|
||||
// Set once an input frame could not be held behind a guarded submit's lease
|
||||
// (the hold queue was full). Nothing later from this socket is applied: it is
|
||||
// closed, and the browser reconnects and resends everything unACKed, in order.
|
||||
let inputStalled = false;
|
||||
|
||||
// Apply one input frame and ACK it. Runs inline, or later and in arrival order
|
||||
// when a guarded submit held the input lease as the frame arrived.
|
||||
const applyInputFrame = (msg: { d: string; seq?: unknown; cid?: unknown }) => {
|
||||
// Reliable delivery: when the frame carries a clientId + seq, apply it
|
||||
// exactly once (skip a duplicate redelivery) but ACK it regardless so
|
||||
// the client can drop it from its durable queue. Frames without seq
|
||||
// (legacy/other tools) are applied as-is — no behavior change.
|
||||
const cid = typeof msg.cid === 'string' ? msg.cid : null;
|
||||
const seq = Number.isInteger(msg.seq) ? (msg.seq as number) : null;
|
||||
const apply = cid && seq !== null ? session.shouldApplyInput(cid, seq) : true;
|
||||
let delivered = true;
|
||||
if (apply) {
|
||||
// Typed input from a claim-holding desktop keeps the claim "hot"
|
||||
// and re-asserts the desktop layout after a mobile override.
|
||||
if (holdsDesktopClaim) session.noteDesktopActivity();
|
||||
// Browser keystrokes are the user's own, so they may name the tab.
|
||||
delivered = session.write(msg.d, { fromUser: true });
|
||||
// A session whose PTY is gone swallows the write. ACKing anyway told
|
||||
// the client to drop the frame from its durable queue and left the seq
|
||||
// burnt, so the retry that reliable delivery exists for was rejected as
|
||||
// a duplicate: the input was lost for good.
|
||||
if (!delivered && cid && seq !== null) session.forgetInputSeq(cid, seq);
|
||||
}
|
||||
if (seq !== null && socket.readyState === 1) {
|
||||
if (apply) {
|
||||
if (delivered) socket.send(`{"t":"ia","seq":${seq}}`);
|
||||
} else {
|
||||
// REJECTED as a duplicate. ACK it — the client must still drop it
|
||||
// from its durable queue — but say so, and hand back our watermark.
|
||||
//
|
||||
// A plain ACK here is indistinguishable from "applied", which is
|
||||
// what made a client with a rolled-back counter unrecoverable: its
|
||||
// seqs persist to localStorage on a DEBOUNCED write, so a tab killed
|
||||
// between a send and that write comes back with a counter BELOW this
|
||||
// watermark, every later keystroke lands at or under it, and each one
|
||||
// is dropped-but-ACKed. The UI stays clean, nothing is delivered, and
|
||||
// a reload restores the same stale counter. `last` is what lets the
|
||||
// client lift itself out.
|
||||
// ⚠️ Defensive: the session arrives through a structural port, and an
|
||||
// implementation without this method must not take the whole input
|
||||
// path down with it — a throw here aborts the message handler and the
|
||||
// frame is never ACKed at all, which strands it in the client's queue.
|
||||
const watermark =
|
||||
typeof (session as { lastInputSeq?: (c: string) => number }).lastInputSeq === 'function'
|
||||
? (session as { lastInputSeq: (c: string) => number }).lastInputSeq(cid as string)
|
||||
: seq;
|
||||
socket.send(`{"t":"ia","seq":${seq},"dup":true,"last":${watermark}}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Attach message handler synchronously BEFORE any async work
|
||||
// (@fastify/websocket requirement to avoid dropped messages).
|
||||
socket.on('message', (raw) => {
|
||||
try {
|
||||
const msg = JSON.parse(String(raw));
|
||||
if (msg.t === 'i' && typeof msg.d === 'string') {
|
||||
if (inputStalled) return;
|
||||
if (msg.d.length > MAX_INPUT_LENGTH) {
|
||||
// Refused for good, so say so: a silent return left the frame
|
||||
// unACKed and the client redelivered it every few seconds forever
|
||||
@@ -185,51 +247,27 @@ export function registerWsRoutes(app: FastifyInstance, ctx: SessionPort, getHost
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Reliable delivery: when the frame carries a clientId + seq, apply it
|
||||
// exactly once (skip a duplicate redelivery) but ACK it regardless so
|
||||
// the client can drop it from its durable queue. Frames without seq
|
||||
// (legacy/other tools) are applied as-is — no behavior change.
|
||||
const cid = typeof msg.cid === 'string' ? msg.cid : null;
|
||||
const seq = Number.isInteger(msg.seq) ? (msg.seq as number) : null;
|
||||
const apply = cid && seq !== null ? session.shouldApplyInput(cid, seq) : true;
|
||||
let delivered = true;
|
||||
if (apply) {
|
||||
// Typed input from a claim-holding desktop keeps the claim "hot"
|
||||
// and re-asserts the desktop layout after a mobile override.
|
||||
if (holdsDesktopClaim) session.noteDesktopActivity();
|
||||
// Browser keystrokes are the user's own, so they may name the tab.
|
||||
delivered = session.write(msg.d, { fromUser: true });
|
||||
// A session whose PTY is gone swallows the write. ACKing anyway told
|
||||
// the client to drop the frame from its durable queue and left the seq
|
||||
// burnt, so the retry that reliable delivery exists for was rejected as
|
||||
// a duplicate: the input was lost for good.
|
||||
if (!delivered && cid && seq !== null) session.forgetInputSeq(cid, seq);
|
||||
}
|
||||
if (seq !== null && socket.readyState === 1) {
|
||||
if (apply) {
|
||||
if (delivered) socket.send(`{"t":"ia","seq":${seq}}`);
|
||||
} else {
|
||||
// REJECTED as a duplicate. ACK it — the client must still drop it
|
||||
// from its durable queue — but say so, and hand back our watermark.
|
||||
//
|
||||
// A plain ACK here is indistinguishable from "applied", which is
|
||||
// what made a client with a rolled-back counter unrecoverable: its
|
||||
// seqs persist to localStorage on a DEBOUNCED write, so a tab killed
|
||||
// between a send and that write comes back with a counter BELOW this
|
||||
// watermark, every later keystroke lands at or under it, and each one
|
||||
// is dropped-but-ACKed. The UI stays clean, nothing is delivered, and
|
||||
// a reload restores the same stale counter. `last` is what lets the
|
||||
// client lift itself out.
|
||||
// ⚠️ Defensive: the session arrives through a structural port, and an
|
||||
// implementation without this method must not take the whole input
|
||||
// path down with it — a throw here aborts the message handler and the
|
||||
// frame is never ACKed at all, which strands it in the client's queue.
|
||||
const watermark =
|
||||
typeof (session as { lastInputSeq?: (c: string) => number }).lastInputSeq === 'function'
|
||||
? (session as { lastInputSeq: (c: string) => number }).lastInputSeq(cid as string)
|
||||
: seq;
|
||||
socket.send(`{"t":"ia","seq":${seq},"dup":true,"last":${watermark}}`);
|
||||
}
|
||||
// A guarded submit (agent-staging.ts) holds the input lease across its
|
||||
// awaited Enter, so frames keep arriving while it is held. Refusing one
|
||||
// lost it: this path does not wait for ACKs, so the next seq landed after
|
||||
// the lease, moved the watermark past the refused one, and its redelivery
|
||||
// was then dropped as a duplicate. Hold the frame instead; the session runs
|
||||
// it, ACK included, in arrival order the moment the lease is released.
|
||||
// ⚠️ Defensive, like `lastInputSeq` below: the session arrives through a
|
||||
// structural port, and one without this method must still deliver input
|
||||
// (a throw here would drop the frame unACKed).
|
||||
const held =
|
||||
typeof session.holdForGuardedLease === 'function'
|
||||
? session.holdForGuardedLease(() => applyInputFrame(msg), msg.d.length, msg.d)
|
||||
: 'free';
|
||||
if (held === 'free') {
|
||||
applyInputFrame(msg);
|
||||
} else if (held === 'full') {
|
||||
// Not held, not applied, not ACKed, and no later frame from this socket
|
||||
// is applied either, so nothing can overtake it.
|
||||
inputStalled = true;
|
||||
console.warn('[ws] input backlog during a guarded submit; closing for redelivery', { sessionId: id });
|
||||
socket.close(1013, 'Input backlog during guarded submit');
|
||||
}
|
||||
} else if (
|
||||
msg.t === 'z' &&
|
||||
|
||||
@@ -1557,6 +1557,13 @@ export const SettingsUpdateSchema = z
|
||||
* inboxes stay). On, pending messages between agents survive a server restart.
|
||||
*/
|
||||
agentInboxPersistEnabled: z.boolean().optional(),
|
||||
/**
|
||||
* Experimental agent coordination (src/web/routes/agent-session-routes.ts): bounded
|
||||
* inspection and the guarded stage/submit routes behind `codeman agent inspect|stage|submit`.
|
||||
* SYNCED, default OFF: the routes are labeled experimental and may change in a minor or
|
||||
* patch release, so automation has to opt in. While OFF, all three routes answer 403.
|
||||
*/
|
||||
agentCoordinationEnabled: z.boolean().optional(),
|
||||
/**
|
||||
* Read My Mind predictor model override. Empty/absent = the AI-checker
|
||||
* default (opus: prediction quality is the product and it runs only on an
|
||||
@@ -2432,3 +2439,15 @@ export const CustomModelSelectionSchema = z.union([
|
||||
}),
|
||||
z.object({ clear: z.literal(true) }),
|
||||
]);
|
||||
|
||||
/** Agent inspection bounds are bytes of evidence, independent of the JSON envelope. */
|
||||
export const AgentInspectQuerySchema = z
|
||||
.object({
|
||||
maxBytes: z.coerce.number().int().min(1).max(65536).default(8192),
|
||||
since: z.string().uuid().optional(),
|
||||
})
|
||||
.strict();
|
||||
export const AgentStageSchema = z.object({ message: z.string().min(1).max(8192) }).strict();
|
||||
export const AgentSubmitSchema = z
|
||||
.object({ stageId: z.string().uuid(), confirmSha: z.string().regex(/^[a-f0-9]{64}$/) })
|
||||
.strict();
|
||||
@@ -219,6 +219,7 @@ import {
|
||||
registerCaseRoutes,
|
||||
registerWorktreeRoutes,
|
||||
registerSessionRoutes,
|
||||
registerAgentSessionRoutes,
|
||||
registerRespawnRoutes,
|
||||
registerRalphRoutes,
|
||||
registerPlanRoutes,
|
||||
@@ -1306,6 +1307,7 @@ export class WebServer extends EventEmitter {
|
||||
// The registry's lifetime is the server's: it drops per-session wake state on every
|
||||
// cleanup path and resolves in-flight wakes on shutdown.
|
||||
this.remoteWake = registerSessionRoutes(this.app, ctx);
|
||||
registerAgentSessionRoutes(this.app, ctx);
|
||||
registerRespawnRoutes(this.app, ctx);
|
||||
registerRalphRoutes(this.app, ctx);
|
||||
registerPlanRoutes(this.app, ctx);
|
||||
|
||||
Reference in new issue
Block a user