Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: relaunch agy on its conversation when it exits to the launch shell

[._.]/ Adam Eivy9f25aa2daf89
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index 5fbb676f50..9942d47a3d 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -1683,3 +1683,63 @@ export function createStallNudgeGate({
get nudgesSent() { return total; },
};
}
+
+// ─── agy exited to its launch shell ─────────────────────────────────────────
+//
+// When agy quits (a crash, a dropped connection, a stray `/exit`), it prints
+//
+// Resume with -c (or command below):
+// agy --conversation=<uuid>
+//
+// and the LOGIN SHELL it was typed into survives. Every nudge above then pastes
+// into a bare prompt, and the stall gate burns its budget on a shell — the
+// worktree holds a half-finished run that nothing will ever continue. The
+// banner carries the one thing needed to recover: the conversation id.
+const AGY_CONVERSATION_PATTERN = /--conversation=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi;
+// Carry-over so a banner split by a PTY chunk boundary still matches: the flag
+// plus a full uuid is 51 chars.
+const AGY_RESUME_CARRY_CAP = 96;
+// A run that exits to the shell this many times is not going to survive one
+// more relaunch.
+export const AGY_RESUME_MAX_ATTEMPTS = 3;
+// The shell must have been silent this long before the relaunch is typed, so
+// the banner has finished painting and the prompt is back.
+export const AGY_RESUME_SETTLE_MS = 3000;
+
+/**
+ * State machine for "agy left its shell behind — relaunch it on the same
+ * conversation". `observe` records the newest conversation id seen in the
+ * (ANSI-stripped) stream; `takeResume` returns it once, when the stream has been
+ * quiet long enough and the budget allows, else null; the caller reports each
+ * real relaunch via `recordRelaunch`.
+ *
+ * @returns {{ observe: (chunk: string) => void,
+ * takeResume: (nowMs: number, lastOutputAtMs: number) => string|null,
+ * recordRelaunch: () => void, readonly attempts: number }}
+ */
+export function createAgyResumeGate({ settleMs = AGY_RESUME_SETTLE_MS, maxAttempts = AGY_RESUME_MAX_ATTEMPTS } = {}) {
+ let carry = '';
+ let pending = null;
+ let attempts = 0;
+ return {
+ observe(chunk) {
+ if (!chunk) return;
+ const window = carry + chunk;
+ carry = window.slice(-AGY_RESUME_CARRY_CAP);
+ let last = null;
+ for (const match of window.matchAll(AGY_CONVERSATION_PATTERN)) last = match[1];
+ if (last) pending = last.toLowerCase();
+ },
+ takeResume(nowMs, lastOutputAtMs) {
+ if (!pending || attempts >= maxAttempts) return null;
+ if (nowMs - lastOutputAtMs < settleMs) return null;
+ const id = pending;
+ pending = null;
+ return id;
+ },
+ // Counted separately from `takeResume`: a banner that scrolled past in a
+ // session whose agy is still alive is not a relaunch and must not spend budget.
+ recordRelaunch() { attempts += 1; },
+ get attempts() { return attempts; },
+ };
+}
diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.js
index 0000d37c17..e4735c466e 100644
--- a/server/lib/tuiHandshake.test.js
+++ b/server/lib/tuiHandshake.test.js
@@ -2184,3 +2184,30 @@ describe('CODEX_COMPOSER_READY_PATTERN', () => {
expect(CODEX_COMPOSER_READY_PATTERN.test('Loading MCP servers…')).toBe(false);
});
});
+
+describe('createAgyResumeGate', () => {
+ const ID = '81c97d96-72b6-44d1-a6d1-18f3e283d642';
+
+ it('returns the conversation id once the shell has gone quiet, even split across chunks', async () => {
+ const { createAgyResumeGate } = await import('./tuiHandshake.js');
+ const gate = createAgyResumeGate({ settleMs: 1000 });
+ gate.observe('Resume with -c (or command below):\nagy--conversation=81c97d96-72b6-');
+ gate.observe('44d1-a6d1-18f3e283d642\n');
+ expect(gate.takeResume(1500, 1000)).toBeNull();
+ expect(gate.takeResume(2500, 1000)).toBe(ID);
+ expect(gate.takeResume(9000, 1000)).toBeNull();
+ });
+
+ it('stops relaunching after the attempt budget is spent', async () => {
+ const { createAgyResumeGate } = await import('./tuiHandshake.js');
+ const gate = createAgyResumeGate({ settleMs: 0, maxAttempts: 2 });
+ for (let i = 0; i < 2; i++) {
+ gate.observe(`--conversation=${ID}`);
+ expect(gate.takeResume(1, 0)).toBe(ID);
+ gate.recordRelaunch();
+ }
+ gate.observe(`--conversation=${ID}`);
+ expect(gate.takeResume(1, 0)).toBeNull();
+ expect(gate.attempts).toBe(2);
+ });
+});
diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.js
index 2ab0eb41ae..8aecf83d89 100644
--- a/server/services/agentTuiSpawning/sessionController.js
+++ b/server/services/agentTuiSpawning/sessionController.js
@@ -58,6 +58,8 @@ import {
TRUNCATION_NUDGE_MAX_ATTEMPTS,
TRUNCATION_NUDGE_TEXT,
createStallNudgeGate,
+ createAgyResumeGate,
+ AGY_RESUME_MAX_ATTEMPTS,
STALL_NUDGE_MAX_ATTEMPTS,
STALL_NUDGE_TEXT,
STALL_NUDGE_MAX_TOTAL,
@@ -547,6 +549,11 @@ export function createTuiSessionController({
// createTruncationNudgeGate.
const detectTruncatedResponse = createTruncatedResponseDetector();
const truncationNudgeGate = createTruncationNudgeGate();
+ // agy quitting back to its launch shell (see createAgyResumeGate). Only a
+ // login-shell launch has a shell to fall back to; a direct PTY dies with agy
+ // and finishes through handleExit instead.
+ const agyResumeGate = !directLaunch && isAntigravityCommand(tuiConfig.command) ? createAgyResumeGate() : null;
+ let agyResumeAwaitingComposer = false;
// A request the TUI keeps retrying and the provider never answers. Every
// reaper reads such a session as busy (the retry ladder repaints the screen),
// so without this the run holds its lane until the max-runtime ceiling — see
@@ -1360,6 +1367,17 @@ export function createTuiSessionController({
// gone quiet. Gated on promptSubmittedAt for the same reason
// resubmitAfterSignal is: before the prompt is in, there is no turn to
// resume and the ordinary paste path still owns first delivery.
+ if (agyResumeGate && promptSubmittedAt) {
+ agyResumeGate.observe(stripped);
+ // A relaunched agy is up once its composer footer paints; only then is a
+ // "continue" a message to the model rather than keystrokes into a boot.
+ if (agyResumeAwaitingComposer && AGY_INPUT_READY_PATTERN.test(stripped)) {
+ agyResumeAwaitingComposer = false;
+ if (pasteController?.resubmit({ text: STALL_NUDGE_TEXT, label: 'agy resume nudge' })) {
+ appendLine('🔁 agy resumed its conversation — nudged it to continue');
+ }
+ }
+ }
const oomSignal = promptSubmittedAt ? detectLocalRuntimeOom(stripped) : null;
if (oomSignal) {
const armed = oomNudgeGate.arm(oomSignal, now);
@@ -1717,6 +1735,23 @@ export function createTuiSessionController({
resubmitAfterSignal();
return;
}
+ // agy fell back to the shell it was launched from: type its own resume
+ // command. Checked against the live process tree, not just the banner —
+ // the banner also scrolls past in a session that is still running.
+ const resumeId = agyResumeGate && sessionPhase === 'running' && promptSubmittedAt
+ ? agyResumeGate.takeResume(now, lastOutputAt)
+ : null;
+ if (resumeId) {
+ Promise.resolve(session.hasLiveChild(pid)).then((alive) => {
+ if (alive || isTerminal()) return;
+ const wrote = session.write(sessionId, `${tuiConfig.commandLine} --conversation=${resumeId}\r`);
+ if (wrote === false) return;
+ agyResumeGate.recordRelaunch();
+ agyResumeAwaitingComposer = true;
+ appendLine(`🔁 agy exited to the shell — relaunched it on conversation ${resumeId.slice(0, 8)} (attempt ${agyResumeGate.attempts}/${AGY_RESUME_MAX_ATTEMPTS})`);
+ }).catch((err) => emitLog('error', `TUI agent ${agentId} agy resume failed: ${err?.message || err}`, { agentId }));
+ return;
+ }
const stall = retryStallGate.takeStall();
if (stall) {
failOverToFallback(stall).catch((err) =>