mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-12-01 00:49:33 +01:00
feat(adopt): adopt tmux sessions a human started, in all three locations
A tmux session someone opened by hand (`tmux new -s work`, then `claude`, or just a shell) is invisible to Codeman: it lives on the default socket, not the instance-scoped one Codeman owns. The home screen now lists those, and one click wraps one in a Codeman tab. Local, in-container and over-ssh all work. The shape is a WRAPPER session, not a direct attach: adoption creates an ordinary `codeman-<8hex>` session on our own socket whose pane runs the attach. That makes "detach, never kill the foreign session" structural rather than a matter of discipline — `killSession` can only ever reach our own wrapper, so no shape of caller bug reaches the foreign server. View reclamation differs by location: local relies on client death and ssh on SIGHUP, but a `docker exec` does NOT die with its client, so the in-container view has to be reclaimed explicitly on kill or every adoption leaks one. Measured facts, recorded in the code comments: - A grouped session (`new-session -t`) buys `status off` and an independent current window. It does NOT buy an independent size. A window is one object with one size and a group shares it: on tmux 3.3a a bare attach and a grouped attach both shrink a 200x49 target to 80x23. Only `window-size largest` holds it, and that is a shared window option which survives our detach, so setting it would permanently rewrite the owner's configuration. Left unset. - Session names come from other people, while the local launch chain ends in `bash -c` + `JSON.stringify`, which escapes neither `$` nor backticks — the outer shell performs command substitution before the inner single quotes are considered (verified: both substitutions inside the inner quotes ran). So session names and socket paths go through a character allowlist and are dropped at DISCOVERY, which means a non-conforming candidate never gets an id and the adopt endpoint fails closed when it re-resolves. - `pane_current_command` is `node` for both claude and codex, so the mode can only come from a bounded process-tree walk of `pane_pid`'s argv; anything unrecognized is treated as a shell. An adopted session has to say no to every assumption that Codeman owns the pane: respawn, Ralph, the orchestrator and hook waits all refuse. The hook check runs BEFORE the mode check, because adoption asks who launched the process and no mode can vouch for a workspace Codeman never touched. `paneExit` is forced to unknown, since the pane runs `tmux attach` rather than the agent and its exiting with 0 only means the connection ended. Reboot restore refuses too: all Codeman ever had was an attach command, and replaying it would build a connection to a foreign session a reboot has almost certainly taken with it, while presenting whatever it lands on as a session we restored. Adoption is admin-only under multi-user mode: adopting someone's shell is equivalent to arbitrary host execution. Discovery is read-only, never creates a session, and degrades to an empty list whenever a probe cannot reach its target.
This commit is contained in:
1 parent
848ab48b0a
commit
245ee68c7c
27 files changed
+2622
-35
No files matched your search
@@ -1,6 +1,13 @@
|
||||
/**
|
||||
* @fileoverview Mux (tmux) session management routes.
|
||||
* Provides mux session listing, killing, reconciliation, and stats control.
|
||||
* Provides mux session listing, killing, reconciliation, stats control, and
|
||||
* discovery of FOREIGN tmux sessions (ones a human started outside Codeman).
|
||||
*
|
||||
* Discovery lives here rather than beside the adopt endpoint on purpose: like
|
||||
* every other route in this file it exposes cross-user process state — other
|
||||
* people's session names, commands and working directories — so it inherits the
|
||||
* admin gate this file already applies. Adoption is a session CREATE and stays in
|
||||
* `session-routes.ts`, where the owner, capacity and case-space gates live.
|
||||
*/
|
||||
|
||||
import { FastifyInstance } from 'fastify';
|
||||
@@ -8,6 +15,8 @@ import type { InfraPort } from '../ports/index.js';
|
||||
import { STATS_COLLECTION_INTERVAL_MS } from '../../config/server-timing.js';
|
||||
import { requireAdmin } from '../route-helpers.js';
|
||||
import { isMultiUserMode } from '../../config/multiuser.js';
|
||||
import { discoverForeignSessions, readAllDockerCases, readAllRemoteHosts } from '../../foreign-tmux-discovery.js';
|
||||
import { FOREIGN_POLL_INTERVAL_MS } from '../../config/foreign-tmux.js';
|
||||
|
||||
export function registerMuxRoutes(app: FastifyInstance, ctx: InfraPort): void {
|
||||
app.get('/api/mux-sessions', async (req, reply) => {
|
||||
@@ -36,6 +45,58 @@ export function registerMuxRoutes(app: FastifyInstance, ctx: InfraPort): void {
|
||||
return result;
|
||||
});
|
||||
|
||||
/**
|
||||
* Foreign tmux sessions available for adoption.
|
||||
*
|
||||
* LOCAL results are always included and are TTL-cached, because the home screen
|
||||
* polls this endpoint while it is open. DOCKER and REMOTE are opt-in per
|
||||
* request (`?docker=1`, `?remote=1`): each costs one `docker exec` or one ssh
|
||||
* per target, and having the home page fan those out on every load is the one
|
||||
* cost this design refuses to pay.
|
||||
*
|
||||
* `adoptedBy` is filled from the live mux sessions, so a target Codeman already
|
||||
* wraps renders as "open" rather than offering a second wrapper.
|
||||
*/
|
||||
app.get('/api/mux/foreign', async (req, reply) => {
|
||||
if (isMultiUserMode() && !requireAdmin(req, reply)) return;
|
||||
const q = (req.query ?? {}) as Record<string, string | undefined>;
|
||||
const wantDocker = q.docker === '1' || q.docker === 'true';
|
||||
const wantRemote = q.remote === '1' || q.remote === 'true';
|
||||
|
||||
// Read the registries either way: `canScanWide` tells the browser whether the
|
||||
// expensive scan has anywhere to go. Without it the UI hides an empty block —
|
||||
// and with it the toggle that is the ONLY way to populate that block, which on
|
||||
// a host with containers but no local tmux sessions made the feature invisible.
|
||||
const dockerCases = await readAllDockerCases();
|
||||
const remoteHosts = await readAllRemoteHosts();
|
||||
|
||||
const result = await discoverForeignSessions({
|
||||
local: true,
|
||||
force: q.force === '1',
|
||||
dockerCases: wantDocker ? dockerCases : undefined,
|
||||
remoteHosts: wantRemote ? remoteHosts : undefined,
|
||||
});
|
||||
|
||||
// Match on the (socket, session) pair rather than on our opaque candidate id:
|
||||
// the id encodes a host key that a restored wrapper does not carry, while the
|
||||
// pair is exactly what the wrapper stores and what it re-attaches to.
|
||||
const wrapped = new Map<string, string>();
|
||||
for (const m of ctx.mux.getSessions()) {
|
||||
if (m.adopt) wrapped.set(`${m.adopt.socketPath}\u0000${m.adopt.targetSession}`, m.sessionId);
|
||||
}
|
||||
|
||||
return {
|
||||
sessions: result.sessions.map((f) => ({
|
||||
...f,
|
||||
adoptedBy: wrapped.get(`${f.socketPath}\u0000${f.sessionName}`),
|
||||
})),
|
||||
scannedAt: result.scannedAt,
|
||||
notes: result.notes,
|
||||
pollIntervalMs: FOREIGN_POLL_INTERVAL_MS,
|
||||
canScanWide: dockerCases.length > 0 || remoteHosts.length > 0,
|
||||
};
|
||||
});
|
||||
|
||||
app.post('/api/mux-sessions/stats/start', async (req, reply) => {
|
||||
// Multi-user: process-wide stats collection toggle → admin-only.
|
||||
if (isMultiUserMode() && !requireAdmin(req, reply)) return;
|
||||
|
||||
@@ -53,6 +53,17 @@ export function registerRalphRoutes(
|
||||
};
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
|
||||
// ⚠️ Adoption gate, kept SEPARATE from the external-CLI gate above: an adopted
|
||||
// session can be `mode: 'claude'` and still be a process we never launched.
|
||||
// Everything below drives the pane on the assumption Codeman owns what runs
|
||||
// in it — sending `/clear`, killing and relaunching the agent — which against
|
||||
// someone else's live session is destructive, not merely unsupported.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'The Ralph tracker is not available for adopted sessions: Codeman did not start this agent and must not drive its lifecycle'
|
||||
);
|
||||
}
|
||||
// Ralph tracker is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(
|
||||
|
||||
@@ -98,6 +98,17 @@ export function registerRespawnRoutes(
|
||||
}
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
|
||||
// ⚠️ Adoption gate, kept SEPARATE from the external-CLI gate above: an adopted
|
||||
// session can be `mode: 'claude'` and still be a process we never launched.
|
||||
// Everything below drives the pane on the assumption Codeman owns what runs
|
||||
// in it — sending `/clear`, killing and relaunching the agent — which against
|
||||
// someone else's live session is destructive, not merely unsupported.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Respawn is not available for adopted sessions: Codeman did not start this agent and must not drive its lifecycle'
|
||||
);
|
||||
}
|
||||
// Respawn is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, `Respawn is not supported for ${session.mode} sessions`);
|
||||
@@ -241,6 +252,17 @@ export function registerRespawnRoutes(
|
||||
return createErrorResponse(ApiErrorCode.SESSION_BUSY, 'Session is busy');
|
||||
}
|
||||
|
||||
// ⚠️ Adoption gate, kept SEPARATE from the external-CLI gate above: an adopted
|
||||
// session can be `mode: 'claude'` and still be a process we never launched.
|
||||
// Everything below drives the pane on the assumption Codeman owns what runs
|
||||
// in it — sending `/clear`, killing and relaunching the agent — which against
|
||||
// someone else's live session is destructive, not merely unsupported.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Respawn is not available for adopted sessions: Codeman did not start this agent and must not drive its lifecycle'
|
||||
);
|
||||
}
|
||||
// Respawn is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, `Respawn is not supported for ${session.mode} sessions`);
|
||||
@@ -310,6 +332,17 @@ export function registerRespawnRoutes(
|
||||
const body = reResult.data as { config?: Partial<RespawnConfig>; durationMinutes?: number };
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
|
||||
// ⚠️ Adoption gate, kept SEPARATE from the external-CLI gate above: an adopted
|
||||
// session can be `mode: 'claude'` and still be a process we never launched.
|
||||
// Everything below drives the pane on the assumption Codeman owns what runs
|
||||
// in it — sending `/clear`, killing and relaunching the agent — which against
|
||||
// someone else's live session is destructive, not merely unsupported.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Respawn is not available for adopted sessions: Codeman did not start this agent and must not drive its lifecycle'
|
||||
);
|
||||
}
|
||||
// Respawn is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, `Respawn is not supported for ${session.mode} sessions`);
|
||||
|
||||
@@ -30,6 +30,16 @@ import {
|
||||
type OmpConfig,
|
||||
type RemoteHost,
|
||||
} from '../../types.js';
|
||||
import { AdoptForeignSessionSchema } from '../schemas.js';
|
||||
import {
|
||||
discoverForeignSessions,
|
||||
invalidateForeignCache,
|
||||
readAllDockerCases,
|
||||
readAllRemoteHosts,
|
||||
} from '../../foreign-tmux-discovery.js';
|
||||
import { foreignViewSessionName } from '../../foreign-tmux.js';
|
||||
import { requireAdmin } from '../route-helpers.js';
|
||||
import type { SessionAdopt } from '../../types/session.js';
|
||||
import { Session, isAltScreenStripMode, isExternalCliMode, isMuxAltScreenOnlyStripMode } from '../../session.js';
|
||||
import type { PaneCaptureOptions } from '../../mux-interface.js';
|
||||
import { SseEvent } from '../sse-events.js';
|
||||
@@ -1156,6 +1166,149 @@ export function registerSessionRoutes(
|
||||
return { session: lightState };
|
||||
});
|
||||
|
||||
// ========== Adopt a foreign tmux session ==========
|
||||
|
||||
/**
|
||||
* Wrap a tmux session a HUMAN started (local, in a container, or over ssh) in a
|
||||
* Codeman session, so it appears as a tab and can be driven from the browser.
|
||||
*
|
||||
* Four things make this safe, and each is load-bearing:
|
||||
*
|
||||
* 1. **The body carries only an opaque id.** The socket path, session name and
|
||||
* host are re-resolved by re-running discovery here. A browser therefore
|
||||
* never supplies a fragment of the command we are about to run, which is the
|
||||
* same rule that keeps docker-adopt and remote-attach injection-free.
|
||||
* 2. **The candidate must still exist.** Discovery is re-run rather than cached,
|
||||
* so a session that died between the listing and the click fails with a 404
|
||||
* instead of producing a wrapper attached to nothing.
|
||||
* 3. **One wrapper per target.** Two wrappers on one foreign session would each
|
||||
* create their own grouped view and each think they own the tab; the guard
|
||||
* is here rather than in the button's in-flight lock, which only stops a
|
||||
* double-click on one device.
|
||||
* 4. **Admin-only under multi-user.** Discovery already is (it exposes other
|
||||
* users' processes), and adopting someone's `shell` is arbitrary execution
|
||||
* as the server account — which is exactly what the `can-bypass-permissions`
|
||||
* grant gates elsewhere. The admin gate subsumes it, so there is deliberately
|
||||
* no second grant check here.
|
||||
*/
|
||||
app.post('/api/sessions/adopt', async (req, reply) => {
|
||||
if (isMultiUserMode() && !requireAdmin(req, reply)) return;
|
||||
|
||||
const owner = ownerFor(req);
|
||||
const capMsg = sessionCapacityMessage(ctx.sessions, owner);
|
||||
if (capMsg) return createErrorResponse(ApiErrorCode.SESSION_BUSY, capMsg);
|
||||
|
||||
const body = parseBody(AdoptForeignSessionSchema, req.body, 'Invalid request body');
|
||||
|
||||
// Re-resolve rather than trust: point 1 and 2 above.
|
||||
const found = await discoverForeignSessions({
|
||||
local: true,
|
||||
force: true,
|
||||
dockerCases: body.docker ? await readAllDockerCases() : undefined,
|
||||
remoteHosts: body.remote ? await readAllRemoteHosts() : undefined,
|
||||
});
|
||||
const target = found.sessions.find((f) => f.id === body.id);
|
||||
if (!target) {
|
||||
// ⚠️ "Not in the re-resolve" has two very different causes and they must not
|
||||
// be reported as one. The session really being gone is the ordinary case;
|
||||
// the OTHER case is a location we could not reach this time, which on a
|
||||
// flaky link makes a perfectly live remote session read as deleted. Measured
|
||||
// against a real VM whose ssh path dropped ~10% of connections: clicking
|
||||
// Open failed with "no longer there" while the session was sitting right
|
||||
// there. Discovery already knows which it was — it wrote a note — so say so.
|
||||
const reach = found.notes.filter((n) => !/skipped/.test(n));
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.NOT_FOUND,
|
||||
reach.length
|
||||
? `Could not reach it just now (${reach.join('; ')}). It may still be running — try again.`
|
||||
: 'That tmux session is no longer there. Refresh the list and try again.'
|
||||
);
|
||||
}
|
||||
|
||||
// Point 3 — one wrapper per (socket, session).
|
||||
const existing = ctx.mux
|
||||
.getSessions()
|
||||
.find((m) => m.adopt?.socketPath === target.socketPath && m.adopt?.targetSession === target.sessionName);
|
||||
if (existing) {
|
||||
const live = ctx.sessions.get(existing.sessionId);
|
||||
if (live) return { session: ctx.getSessionStateWithRespawn(live), alreadyAdopted: true };
|
||||
}
|
||||
|
||||
// Connection facts are copied onto the session rather than referenced by id:
|
||||
// a wrapper restored after a server restart must be able to rebuild its
|
||||
// command even if the host registry was edited in the meantime.
|
||||
const adopt: SessionAdopt = {
|
||||
location: target.location,
|
||||
socketPath: target.socketPath,
|
||||
targetSession: target.sessionName,
|
||||
viewSession: '',
|
||||
paneCurrentPath: target.workingDir,
|
||||
};
|
||||
|
||||
if (target.location === 'docker') {
|
||||
const hosts = await readDockerHosts(CODEMAN_CONFIG_DIR);
|
||||
const host = hosts.find((h) => h.id === target.hostId);
|
||||
if (!target.containerName) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Container name missing for a docker candidate');
|
||||
}
|
||||
adopt.docker = {
|
||||
hostId: target.hostId ?? '',
|
||||
label: target.hostLabel ?? target.containerName,
|
||||
engine: host?.engine ?? 'docker',
|
||||
containerName: target.containerName,
|
||||
daemonHost: host?.daemonHost,
|
||||
context: host?.context,
|
||||
};
|
||||
} else if (target.location === 'remote') {
|
||||
const host = (await readRemoteHosts(CODEMAN_CONFIG_DIR)).find((h) => h.id === target.hostId);
|
||||
if (!host) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Remote host not found');
|
||||
adopt.remote = {
|
||||
hostId: host.id,
|
||||
label: host.label,
|
||||
host: host.host,
|
||||
username: host.username,
|
||||
port: host.port,
|
||||
identityFile: host.identityFile,
|
||||
socksProxy: host.socksProxy,
|
||||
jumpHost: host.jumpHost,
|
||||
extraSshOptions: host.extraSshOptions,
|
||||
};
|
||||
}
|
||||
|
||||
const adoptHistoryConfig = await ctx.getTerminalHistoryConfig();
|
||||
|
||||
// ⚠️ `workingDir` for an adopted session is the FOREIGN pane's cwd, which may
|
||||
// not exist on this host (a container path, a remote path). It is recorded as
|
||||
// an observation for display; the wrapper pane is never `cd`'d into it, and
|
||||
// the case-space confinement that guards a real workingDir does not apply
|
||||
// because nothing is created there.
|
||||
const session = new Session({
|
||||
workingDir: target.workingDir || process.cwd(),
|
||||
mode: target.mode,
|
||||
name: body.name || target.sessionName,
|
||||
mux: ctx.mux,
|
||||
useMux: true,
|
||||
tmuxHistoryLimit: adoptHistoryConfig.tmuxHistoryLimit,
|
||||
adopt,
|
||||
owner,
|
||||
parentSessionId: resolveParentSessionId(ctx, req, body.parentSessionId, owner),
|
||||
});
|
||||
// The view session name is derived from the Codeman session id, so it can only
|
||||
// be filled once the Session exists.
|
||||
adopt.viewSession = foreignViewSessionName(session.id);
|
||||
|
||||
await ctx.addSession(session);
|
||||
ctx.store.incrementSessionsCreated();
|
||||
ctx.persistSessionState(session);
|
||||
await ctx.setupSessionListeners(session);
|
||||
getLifecycleLog().log({ event: 'created', sessionId: session.id, name: session.name });
|
||||
invalidateForeignCache();
|
||||
|
||||
const lightState = ctx.getSessionStateWithRespawn(session);
|
||||
ctx.broadcast(SseEvent.SessionCreated, lightState);
|
||||
return { session: lightState, adopted: true };
|
||||
});
|
||||
|
||||
// ========== Rename Session ==========
|
||||
|
||||
app.put('/api/sessions/:id/name', async (req) => {
|
||||
|
||||
Reference in new issue
Block a user