feat(agent): make coordination routes opt-in and address review

Gate inspect, stage and submit behind the synced agentCoordinationEnabled
setting (default OFF, App Settings > Cross-session features, zh-CN
strings). While off, all three routes answer 403 FORBIDDEN naming the
setting, checked before session lookup; the CLI verbs print it verbatim.

Remember the attributed Codex rollout per session and re-verify only its
head on later calls, rescanning only date directories not older than it
for a /new conflict. The first walk reads 1 KiB prefixes first, so a
store of 2,100+ unrelated rollouts still attributes.

Answer unexpected inspection errors with 422 OPERATION_FAILED and log
the session id and error code only.

Read the guarded composer glyph and footer from the CLI registry: codex
workDetect.promptGlyph and a new workDetect.composerFooterLine
capability, compiled through compileVersionRegex. Codex footer effort
words are one shared list with modelDetect.screenLine.

Fix the wiki API reference link, frame the versioning policy entry as a
case of the experimental rule, join the CLAUDE.md Agent CLI paragraph,
and update the changeset, skill reference and architecture notes.
This commit is contained in:
Aamer Akhter committed 2026-10-24 22:54:17 -04:00
1 parent 1a2c3be0ea
commit c78635a3d3
32 files changed
+848 -124

No files matched your search

+152 -36
View File
@@ -1,11 +1,16 @@
/**
* @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 { join, resolve } from 'node:path';
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;
@@ -67,6 +72,42 @@ function strictMetadata(bytes: Buffer): Metadata | undefined {
}
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. Any failed check drops the entry and falls back to the
* full walk. 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
@@ -81,9 +122,92 @@ export async function findExactCodexConversation(
if (!workspace || !home) return undefined;
const sessions = join(home, 'sessions');
if ((await probePathKind(sessions, { pastCap: true })) !== 'directory') return undefined;
const directories = [{ path: sessions, depth: 0 }];
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 second candidate is a conflict a full walk would report too; anything
// else (a replaced file, an exhausted budget) gets one full walk now.
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;
@@ -98,32 +222,43 @@ export async function findExactCodexConversation(
const path = join(dir.path, entry.name);
if (entry.isDirectory()) {
if (dir.depth >= 8) return undefined;
directories.push({ path, depth: dir.depth + 1 });
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;
const id = entry.name.match(UUID_AT_END)?.[1];
const prefixBytes = Math.min(info.size, 4096);
if (prefixes + prefixBytes > prefixLimit) return undefined;
prefixes += prefixBytes;
const prefix = Buffer.alloc(prefixBytes);
const first = await file.read(prefix, 0, prefixBytes, 0);
// Cheap negative filter only; a match still needs full parsed metadata.
if (
id !== explicit &&
!prefix.subarray(0, first.bytesRead).toString('utf8').includes(JSON.stringify(originator))
)
continue;
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 || !id || meta.id !== id) continue;
if (!meta || meta.id !== id) continue;
if (id === explicit || meta.originator === originator) candidates.push({ id, path, meta });
} finally {
await file.close();
@@ -131,24 +266,5 @@ export async function findExactCodexConversation(
}
}
}
if (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 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;
return { id: candidate.id, path: candidate.path };
} finally {
await handle.close();
}
return candidates;
}
+50 -20
View File
@@ -6,10 +6,30 @@
import { createHash, randomUUID } from 'node:crypto';
import { stripAnsi } from './utils/regex-patterns.js';
import { visibleWidth } from './tui/tui-ansi.js';
import { CODEX_REASONING_EFFORTS } from './types/session.js';
const FOOTER_LINE = new RegExp(
String.raw`^\s+(?:\d+% context left|\? for shortcuts|← for agents|\S+ (?:${[...CODEX_REASONING_EFFORTS, 'default'].join('|')}) · )`
);
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, both from the CLI registry
* (`capabilities.workDetect`): the composer glyph and the pattern every row below an
* idle composer must match. Nothing here names a CLI; a CLI takes part in guarded
* input by declaring `composerFooterLine`.
*/
export interface GuardedComposerChrome {
promptGlyph: string;
footerLine: RegExp;
}
/** 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);
return footerLine ? { promptGlyph: detect.promptGlyph, footerLine } : null;
}
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 {
@@ -34,19 +54,21 @@ interface Receipt extends GuardedInputSnapshot {
export class GuardedInputConflict extends Error {}
/**
* Conservatively read a Codex composer: exactly one visible, unwrapped row and a
* known footer. Never remove internal spaces, infer an unknown shell prompt, or
* interpret dialog options as authority. An unsupported frame yields no proof.
* 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 readGuardedCodexComposer(screen: string): string | null {
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) => /^\s*›(?:\s|$)/.test(row.line));
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) => !FOOTER_LINE.test(line))) return null;
if (below.length === 0 || below.length > 3 || below.some((line) => !chrome.footerLine.test(line))) return null;
// Preserve exact printable content; only SGR-dim placeholder/suggestion text is excluded.
const raw = screen.split('\n')[last.index];
let dim = false;
@@ -65,15 +87,22 @@ export function readGuardedCodexComposer(screen: string): string | null {
}
} else if (!dim) visible += token;
}
return stripAnsi(visible).trimStart().slice(2).trimEnd();
// The glyph and the one space after it are the prefix, not input.
return stripAnsi(visible)
.trimStart()
.slice(chrome.promptGlyph.length + 1)
.trimEnd();
}
/** Require the capture's caret at the exact end of the unwrapped composer. */
export function readGuardedCodexSnapshot(snapshot: string): string | null {
return readGuardedCodexSnapshotDetails(snapshot)?.composer ?? null;
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 readGuardedCodexSnapshotDetails(snapshot: string): { composer: string; prefixWidth: number } | null {
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
@@ -87,16 +116,17 @@ export function readGuardedCodexSnapshotDetails(snapshot: string): { composer: s
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 = readGuardedCodexComposer(rows.join('\n'));
const composer = readGuardedComposer(rows.join('\n'), chrome);
if (composer === null) return null;
let composerRow = -1;
const isComposer = composerRow(chrome);
let row = -1;
for (let i = rows.length - 1; i >= 0; i--)
if (/^\s*›(?:\s|$)/.test(stripAnsi(rows[i]))) {
composerRow = i;
if (isComposer.test(stripAnsi(rows[i]))) {
row = i;
break;
}
const prefix = stripAnsi(rows[composerRow]).match(/^(\s*›[ \u00a0])/);
if (!prefix || Number(caret[1]) !== composerRow + 1 || Number(caret[2]) !== visibleWidth(prefix[1] + composer) + 1)
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]) };
}
+14 -8
View File
@@ -2,11 +2,13 @@
* @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`, `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
* A thin HTTP client over the server's endpoints (`quick-start`, `input`, `wait`,
* `wait-output`, `last-response`, `terminal`, `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.
@@ -1272,7 +1274,9 @@ export function registerAgentCommands(program: Command): Command {
agent
.command('inspect <id>')
.description('Experimental: bounded transcript evidence or a labeled pane snapshot; opaque incremental cursors')
.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')
@@ -1289,7 +1293,7 @@ export function registerAgentCommands(program: Command): Command {
agent
.command('stage <id>')
.description(
'Experimental: type a printable single-line UTF8 file without Enter; requires a verifiable local Codex composer'
'Experimental, opt-in (agentCoordinationEnabled): type a printable single-line UTF8 file without Enter; requires a verifiable local Codex composer'
)
.requiredOption('--message-file <path>', 'Regular UTF8 file, at most 8192 bytes, no trailing newline')
.option('--json', 'Machine-readable output')
@@ -1299,7 +1303,9 @@ export function registerAgentCommands(program: Command): Command {
agent
.command('submit <id>')
.description('Experimental: send Enter once only when the staged composer, pane and hash still match')
.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')
+10
View File
@@ -384,6 +384,16 @@ 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(),
})
.strict()
// A window with nothing to search is a typo, not a configuration. Refused at LOAD
+15 -1
View File
@@ -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,12 @@ 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}) · )`,
},
// 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 +771,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
+9
View File
@@ -432,6 +432,15 @@ 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;
};
/**
* How many columns this CLI indents its transcript body by, so a copy taken from its
+10 -3
View File
@@ -129,7 +129,12 @@ 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 { promptSha256, readGuardedCodexSnapshotDetails, type GuardedInputSnapshot } from './agent-staging.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';
@@ -4764,10 +4769,12 @@ export class Session extends EventEmitter {
this.remote ||
this.docker ||
this.paneExit ||
getCli(this.mode)?.capabilities.transcript !== 'codex-rollout' ||
!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;
@@ -4778,7 +4785,7 @@ export class Session extends EventEmitter {
const working = this._workingLinePattern();
working.lastIndex = 0;
if (this._paneShowsBlocked(plain) || working.test(plain) || this._paneAwaitsWorkers(plain)) return null;
const composer = readGuardedCodexSnapshotDetails(screen);
const composer = readGuardedSnapshotDetails(screen, chrome);
return composer === null
? null
: {
+3
View File
@@ -697,6 +697,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 中的重命名也只保留到下一轮。从下一次会话启动或重新生成时生效,无需重启服务器。',
+7
View File
@@ -2178,6 +2178,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>
+3
View File
@@ -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.
@@ -2929,6 +2931,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,
+44 -6
View File
@@ -2,6 +2,11 @@
* @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';
@@ -10,10 +15,32 @@ 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, type GuardedInputTarget } from '../../agent-staging.js';
import { ApiErrorCode, createErrorResponse } from '../../types.js';
import { findSessionOrFail, getAuthUser, parseBody } from '../route-helpers.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();
@@ -33,6 +60,8 @@ export function registerAgentSessionRoutes(app: FastifyInstance, ctx: SessionPor
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);
@@ -99,19 +128,24 @@ export function registerAgentSessionRoutes(app: FastifyInstance, ctx: SessionPor
} catch (error) {
if (error instanceof InspectionConflict)
return reply.code(409).send(createErrorResponse(ApiErrorCode.CONFLICT, error.message));
// Native paths and arbitrary IO errors must never escape into the response.
return reply
.code(409)
.send(createErrorResponse(ApiErrorCode.CONFLICT, 'Inspection source unavailable; retry without a cursor'));
// 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(
@@ -125,6 +159,8 @@ export function registerAgentSessionRoutes(app: FastifyInstance, ctx: SessionPor
}
});
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 {
@@ -133,6 +169,8 @@ export function registerAgentSessionRoutes(app: FastifyInstance, ctx: SessionPor
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(
+7
View File
@@ -1544,6 +1544,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