Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions plugins/hcoord/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ On macOS its LaunchAgent label is derived from that directory, so it does not re
`stop` records that choice, and a later hide launch or plugin startup leaves the daemon stopped until `start` is run.
The LaunchAgent starts at login and restarts an unexpected exit, while the ledger and outbox survive executable upgrades.

Every write command saves a letter in `${HCOORD_HOME:-~/.hcoord}/outbox` first.
A session whose sandbox cannot write there (a Codex `workspace-write` session without that directory in `writable_roots`) gets `permission_denied` naming the blocked path and the next action, and nothing is sent; running the same command again after the fix is safe.
An unexpected exception keeps its errno code and message in the `hcoord.command_failed` event on stderr.
A watch check an observer never closes is sent to the observer, reminded once and escalated to the human once, then left alone.
A watch whose target and observer have both been unreachable for an hour is stopped by the daemon (`watch.orphaned` event) and can be restarted or reassigned by a human.

After deleting hide.app, remove the default login service explicitly:

```sh
Expand Down Expand Up @@ -82,3 +88,5 @@ A retry restores a name Herdr dropped only when the recorded session matches, be

Remote registration, worktree spawn, and outbox collection use the machine names saved by Herdr.
The remote machine must have `~/.hcoord/bin/hcoord`, the source repository, and a testable Herdr server; hcoord stores no SSH credentials and the HQ always initiates the connection.
Runs to one machine share a multiplexed SSH connection (a socket under `/tmp/hcoord-ssh-<uid>/`, closed after 60 idle seconds), so a flaky SSH agent is asked to sign far less often.
A collection that keeps failing the same way logs one `hcoord.collect_failed` line per ten minutes with a `repeated` count, and `hcoord.collect_recovered` when it works again.
17 changes: 15 additions & 2 deletions plugins/hcoord/src/hcoord/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,20 @@ function warnIfUnstable(): void {
}
}

/**
* An exception no caller-facing code classified. The stderr event keeps its
* own code (the errno when it has one) and message so the cause is findable;
* the caller gets `internal` plus the errno, which is safe to show. A
* SyntaxError's message quotes the text it failed to parse, which can be a
* request body, so only its name is kept.
*/
function unclassifiedFailure(error: unknown): HcoordError {
const cause = error instanceof Error ? error : new Error(String(error));
const errno = typeof (cause as NodeJS.ErrnoException).code === "string" ? (cause as NodeJS.ErrnoException).code! : null;
process.stderr.write(`${JSON.stringify({ event: "hcoord.command_failed", at: new Date().toISOString(), code: errno ?? "internal", name: cause.name, ...(cause instanceof SyntaxError ? {} : { message: cause.message.slice(0, 300) }) })}\n`);
return new HcoordError("internal", `command failed${errno ? ` (${errno})` : ""}; the cause is on stderr as hcoord.command_failed`);
}

function print(result: WireResult, json: boolean): void {
warnIfUnstable();
if (json) { process.stdout.write(`${JSON.stringify(result)}\n`); return; }
Expand Down Expand Up @@ -371,8 +385,7 @@ export async function main(argv: string[]): Promise<number> {
print(result, json);
return result.ok ? 0 : 1;
} catch (error) {
const reason = error instanceof HcoordError ? error : new HcoordError("internal", "command failed; inspect stderr");
if (!(error instanceof HcoordError)) process.stderr.write(`${JSON.stringify({ event: "hcoord.command_failed", at: new Date().toISOString(), code: "internal" })}\n`);
const reason = error instanceof HcoordError ? error : unclassifiedFailure(error);
print({ ok: false, error: { code: reason.code, message: reason.message, ...(reason.detail ? { detail: reason.detail } : {}) }, observedAt: new Date().toISOString() }, json);
return reason.code === "invalid_argument" ? 2 : 1;
}
Expand Down
38 changes: 38 additions & 0 deletions plugins/hcoord/src/hcoord/failure-log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Keeps a failure that repeats on the same subject to one log line per
* window. A machine that stays unreachable once logged the same
* `collect_failed` line every few seconds (2265 in five days); the first
* failure and every change of cause still log at once, a repeat only adds to
* a count the next line carries, and recovery reports how many were folded.
* A success does not end the window: a machine that fails, answers once and
* fails again with the same cause is still one episode.
*/
export interface FailureLog {
/** Writes a line for a new or changed failure, or once per window while it repeats; returns whether it wrote. */
failed(subject: string, cause: string, fields: Record<string, unknown>): boolean;
/** Writes one line if repeats were folded and resets that count; the window itself keeps running. Returns whether it wrote. */
recovered(subject: string, fields?: Record<string, unknown>): boolean;
}

interface Episode { cause: string; loggedAt: number; folded: number }

export function createFailureLog(event: { failed: string; recovered: string }, write: (line: string) => void, windowMs: number, now: () => number = Date.now): FailureLog {
const episodes = new Map<string, Episode>();
const line = (name: string, fields: Record<string, unknown>): void => write(`${JSON.stringify({ event: name, at: new Date(now()).toISOString(), ...fields })}\n`);
return {
failed(subject, cause, fields) {
const episode = episodes.get(subject);
if (episode !== undefined && episode.cause === cause && now() - episode.loggedAt < windowMs) { episode.folded += 1; return false; }
line(event.failed, { ...fields, ...(episode !== undefined && episode.folded > 0 ? { repeated: episode.folded } : {}) });
episodes.set(subject, { cause, loggedAt: now(), folded: 0 });
return true;
},
recovered(subject, fields = {}) {
const episode = episodes.get(subject);
if (episode === undefined || episode.folded === 0) return false;
line(event.recovered, { ...fields, repeated: episode.folded });
episode.folded = 0;
return true;
},
};
}
11 changes: 6 additions & 5 deletions plugins/hcoord/src/hcoord/herdr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ export function validateBinding(machine: string, session: string, instance: stri
}

type LocalBinding = Pick<Participant, "machine" | "hostScope" | "session" | "instance" | "pane">;
type ParticipantInspection = { runtime: Participant["runtime"]; connection: Participant["connection"]; reason: string; interactiveReady: boolean | null };
/** `gone` is Herdr's own answer that the execution is not there; an unreachable Herdr or remote is `unavailable` and not gone. */
type ParticipantInspection = { runtime: Participant["runtime"]; connection: Participant["connection"]; reason: string; interactiveReady: boolean | null; gone: boolean };
export const OFFICIAL_PROMPT_BOUNDARY = {
transport: "Herdr 0.9.1 agent.prompt",
preflight: "same pane and session (the terminal only for a sessionless agent), idle or done lifecycle, and interactive readiness unless Herdr reports none",
Expand All @@ -31,12 +32,12 @@ export const OFFICIAL_PROMPT_BOUNDARY = {
} as const;

export function inspectParticipant(participant: LocalBinding): ParticipantInspection {
if (participant.pane === null) return { runtime: "unknown", connection: "unverified", reason: "participant has no exact pane binding", interactiveReady: null };
if (participant.pane === null) return { runtime: "unknown", connection: "unverified", reason: "participant has no exact pane binding", interactiveReady: null, gone: true };
const found = getAgent(participant.pane, at(participant), 1000);
if (found.kind !== "found") return { runtime: "unknown", connection: "unavailable", reason: found.detail, interactiveReady: null };
if (found.kind !== "found") return { runtime: "unknown", connection: "unavailable", reason: found.detail, interactiveReady: null, gone: found.kind === "absent" };
const agent = found.agent;
if (!sameExecution(participant, { machine: participant.machine, hostScope: participant.hostScope, pane: agent.paneId, session: agent.sessionId, instance: agent.terminalId })) return { runtime: "unknown", connection: "unavailable", reason: "execution identity changed", interactiveReady: null };
return { runtime: agent.status === "blocked" ? "unknown" : agent.status, connection: "connected", reason: agent.status === "blocked" ? "recipient is blocked" : "the recorded execution observed in its pane", interactiveReady: agent.interactiveReady };
if (!sameExecution(participant, { machine: participant.machine, hostScope: participant.hostScope, pane: agent.paneId, session: agent.sessionId, instance: agent.terminalId })) return { runtime: "unknown", connection: "unavailable", reason: "execution identity changed", interactiveReady: null, gone: true };
return { runtime: agent.status === "blocked" ? "unknown" : agent.status, connection: "connected", reason: agent.status === "blocked" ? "recipient is blocked" : "the recorded execution observed in its pane", interactiveReady: agent.interactiveReady, gone: false };
}

/**
Expand Down
4 changes: 4 additions & 0 deletions plugins/hcoord/src/hcoord/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export const REMOTE_PROTOCOL = 1;
export const MAX_OUTBOX_LETTERS = 1024;
export const MAX_LETTER_RECORDS = 20000;
export const LETTER_OPERATIONS = new Set(["config.set", "agent.register", "agent.spawn", "watch.start", "watch.assign", "watch.stop", "watch.check", "request.send", "request.reply", "request.relay", "request.ack", "request.cancel", "request.escalate", "agent.end"]);
/** How long a watch whose target and observer are both unreachable stays active before the daemon stops it. */
export const WATCH_ORPHAN_MS = 60 * 60_000;
export const DEFAULTS = { watchMs: 5 * 60_000, remindMs: 15 * 60_000, escalateMs: 30 * 60_000, retentionMs: 30 * 24 * 60 * 60_000 };

export type RequestStatus = "open" | "answered" | "canceled";
Expand Down Expand Up @@ -67,6 +69,8 @@ export interface Watch {
* neither reminded nor escalated, until the target works again (D-20).
*/
quietSince?: string | null;
/** When the target and the observer were first both unreachable; cleared as soon as either answers. */
orphanedSince?: string | null;
}
export interface Delivery {
id: string; requestId: string; recipient: string; status: DeliveryStatus; reason: string | null;
Expand Down
24 changes: 20 additions & 4 deletions plugins/hcoord/src/hcoord/outbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,27 @@ export function outboxDir(home = os.homedir()): string { return path.join(dataDi

const letterFile = /^(\d{15})-([0-9a-f-]{36})\.json$/;

/**
* A write the session's sandbox or the disk refused. The caller needs the
* blocked path and the next action, not an `internal` failure: nothing was
* saved, so the same command can be retried unchanged once the cause is fixed.
*/
function outboxWriteError(error: unknown, dir: string): unknown {
const code = (error as NodeJS.ErrnoException | null)?.code;
if (code === "EPERM" || code === "EACCES" || code === "EROFS") {
return new HcoordError("permission_denied", `this session cannot write the hcoord outbox ${dir} (${code}), so nothing was sent; add ${path.dirname(dir)} to the session's writable roots (a Codex workspace-write sandbox lists them as writable_roots) or send from a session that may write it, then run the same command again`, { path: (error as NodeJS.ErrnoException).path ?? dir, errno: code });
}
if (code === "ENOSPC" || code === "EDQUOT") return new HcoordError("capacity", `the disk holding the hcoord outbox ${dir} is full (${code}), so nothing was sent; free space there, then run the same command again`, { path: dir, errno: code });
return error;
}

export function writeLetter(operation: string, args: Record<string, unknown>, home = os.homedir()): Letter {
const dir = outboxDir(home);
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
fs.chmodSync(dataDir(home), 0o700);
fs.chmodSync(dir, 0o700);
try {
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
fs.chmodSync(dataDir(home), 0o700);
fs.chmodSync(dir, 0o700);
} catch (error) { throw outboxWriteError(error, dir); }
if (fs.readdirSync(dir).filter((name) => letterFile.test(name)).length >= MAX_OUTBOX_LETTERS) {
throw new HcoordError("capacity", `outbox holds ${MAX_OUTBOX_LETTERS} uncollected letters; start the coordinator or restore its connection before sending more`);
}
Expand All @@ -27,7 +43,7 @@ export function writeLetter(operation: string, args: Record<string, unknown>, ho
const bytes = Buffer.from(`${JSON.stringify(letter)}\n`);
if (bytes.length > MAX_MESSAGE_BYTES) throw new HcoordError("capacity", `letter exceeds ${MAX_MESSAGE_BYTES} bytes; shorten context or native arguments before retrying`);
const name = `${String(created.getTime()).padStart(15, "0")}-${letter.id}.json`;
writeFileAtomic(path.join(dir, name), bytes);
try { writeFileAtomic(path.join(dir, name), bytes); } catch (error) { throw outboxWriteError(error, dir); }
return letter;
}

Expand Down
28 changes: 27 additions & 1 deletion plugins/hcoord/src/hcoord/remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,33 @@ function remoteShell(argv: string[]): string {
return `HCOORD_HOME=${dir} exec ${dir}/bin/hcoord remote ${before.map(quote).join(" ")} --json${divider < 0 ? "" : ` -- ${tail.map(quote).join(" ")}`}`;
}

const sshArgs = (target: string, argv: string[]): string[] => ["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=5", "-o", "ServerAliveCountMax=2", target, "--", remoteShell(argv)];
// Every SSH run used to open its own connection, so a flaky SSH agent was asked
// to sign every few seconds (about 15 refusals an hour, 2265 since 2026-09-26).
// One multiplexed master per target serves the runs inside its idle window.
// The socket directory is short and private because a unix socket path caps
// near 104 bytes and the per-user temp directory alone is nearly that long.
const CONTROL_PERSIST_SECONDS = 60;
let reuseSkipLogged = false;
const controlDir = (): string => path.join("/tmp", `hcoord-ssh-${process.getuid?.() ?? 0}`);

/**
* SSH options that reuse one connection per target. A directory that cannot be
* made, for example inside a sandbox, only costs the reuse: every run then
* opens its own connection exactly as before, so the call itself never fails
* on it.
*/
export function controlOptions(): string[] {
if (process.platform === "win32") return [];
const dir = controlDir();
try { fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); fs.chmodSync(dir, 0o700); }
catch (error) {
if (!reuseSkipLogged) { reuseSkipLogged = true; process.stderr.write(`${JSON.stringify({ event: "hcoord.ssh_reuse_unavailable", at: new Date().toISOString(), code: (error as NodeJS.ErrnoException).code ?? "internal" })}\n`); }
return [];
}
return ["-o", "ControlMaster=auto", "-o", `ControlPath=${dir}/%C`, "-o", `ControlPersist=${CONTROL_PERSIST_SECONDS}`];
}

export const sshArgs = (target: string, argv: string[]): string[] => ["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=5", "-o", "ServerAliveCountMax=2", ...controlOptions(), target, "--", remoteShell(argv)];

export type Raw = { status: number | null; stdout: string; stderr: string };

Expand Down
15 changes: 14 additions & 1 deletion plugins/hcoord/src/hcoord/service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from "node:path";
import { DEFAULTS, event, HcoordError, id, MAX_AGENTS, MAX_LETTER_RECORDS, MAX_BODY_BYTES, MAX_BRIEF_BYTES, MAX_EVENTS, MAX_MESSAGE_BYTES, MAX_QUEUE, MAX_REQUESTS, MAX_SPAWN_INTENTS, MAX_WATCH_HISTORY, SPAWN_EVENT_SLOTS, own, put, sameExecution, validateSpawnSpec, type Delivery, type Ledger, type LetterRecord, type Participant, type Request, type SpawnIntent, type Watch } from "./model";
import { DEFAULTS, WATCH_ORPHAN_MS, event, HcoordError, id, MAX_AGENTS, MAX_LETTER_RECORDS, MAX_BODY_BYTES, MAX_BRIEF_BYTES, MAX_EVENTS, MAX_MESSAGE_BYTES, MAX_QUEUE, MAX_REQUESTS, MAX_SPAWN_INTENTS, MAX_WATCH_HISTORY, SPAWN_EVENT_SLOTS, own, put, sameExecution, validateSpawnSpec, type Delivery, type Ledger, type LetterRecord, type Participant, type Request, type SpawnIntent, type Watch } from "./model";

type Args = Record<string, unknown>;
const isHere = (machine: string): boolean => machine === "local" || machine === require("node:os").hostname();
Expand Down Expand Up @@ -593,11 +593,24 @@ export function execute(state: Ledger, operation: string, args: Args, at: string
if (retained.length !== state.events.length) { state.events = retained; state.prunedBefore = at; changed = true; }
}
const observed = args["observedTargets"] === undefined ? null : new Set(Array.isArray(args["observedTargets"]) ? args["observedTargets"] : []);
const readings = args["watchReadings"] !== null && typeof args["watchReadings"] === "object" ? args["watchReadings"] as Record<string, unknown> : {};
for (const watch of Object.values(state.watches)) {
if (watch.status !== "active" || Date.parse(watch.dueAt) > Date.parse(at)) continue;
if (observed !== null && !observed.has(watch.target)) continue;
changed = true;
const target = own(state.participants, watch.target);
// Nobody left to look at the target or to be woken for it: the watch can only wait, so it ends after a grace and says why.
// The grace needs consecutive evaluations: a check this late means the daemon was down or asleep, so the count starts over.
const reading = readings[watch.target];
if (Date.parse(at) - Date.parse(watch.dueAt) > Math.max(2 * watch.intervalMs, 60_000) || reading === "present") watch.orphanedSince = null;
if (reading === "gone") {
watch.orphanedSince ??= at;
if (Date.parse(at) - Date.parse(watch.orphanedSince) >= WATCH_ORPHAN_MS) {
watch.status = "stopped"; watch.stoppedAt = at;
event(state, at, "watch.orphaned", watch.target, null, { generation: watch.generation, observer: watch.observer, since: watch.orphanedSince });
continue;
}
}
const resting = target !== undefined && target.runtime !== "working";
if (resting && watch.quietSince) { watch.dueAt = timed(at, watch.intervalMs); continue; }
if (resting) { watch.quietSince = at; event(state, at, "watch.quiet", watch.target, null, { runtime: target!.runtime }); }
Expand Down
Loading
Loading