an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
refactor(enrich): extract shared runHiddenClaude helper; convert reflect.ts
Chaitanya Giri850d6f56b54b
diff --git a/src/main/assistant.ts b/src/main/assistant.tsindex cb260dee..a3f07fe9 100644--- a/src/main/assistant.ts+++ b/src/main/assistant.ts@@ -1,8 +1,5 @@-import * as pty from 'node-pty';-import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';-import path from 'node:path';-import { resolveCommand, userShellPath } from './shellEnv';-import { projectDir } from './transcript';+import { existsSync } from 'node:fs';+import { runHiddenClaude } from './hiddenClaude';/*** Michael's silent prep assistant.@@ -12,30 +9,12 @@ import { projectDir } from './transcript';* instruction the user parked for Michael, it explores read-only and rewrites* it into a self-contained context-rich prompt Michael can execute immediately.*- * Uses an interactive PTY (not `claude -p`) so enrichment draws from the- * user's normal interactive plan quota — not the separate Agent SDK credit that- * moves to a claim-required pool from 2026-06-15.- *- * Session lifecycle: spawn → boot quiet → bracketed-paste prompt + \r →- * idle-settle → transcript extract → kill. Ephemeral per-enrich (no /clear- * needed; each call gets a fresh session and its own JSONL).+ * See hiddenClaude.ts for the session lifecycle.*//** Haiku 4.5 — fast, draws from interactive plan quota (not Agent SDK credit). */const ASSISTANT_MODEL = 'claude-haiku-4-5';-/** ms of PTY silence that signals the TUI is ready for input (boot complete). */-const BOOT_QUIET_MS = 1500;-/** Hard cap: send the prompt at most this many ms after spawn (handles stalls). */-const BOOT_MAX_MS = 7000;-/**- * ms of PTY silence after the prompt that signals response is complete.- * Includes a small write-to-disk margin so the JSONL record is flushed.- */-const IDLE_SETTLE_MS = 3500;-/** Absolute safety net for the whole enrichment round-trip. */-const DEFAULT_TIMEOUT_MS = 180_000;-export interface EnrichRequest {/** The raw instruction the user wants enriched. */message: string;@@ -92,149 +71,26 @@ function buildTaskPrompt(message: string, cwd: string, repos: string[]): string].join('\n');}-/**- * Extract the last assistant text block from the transcript JSONL written- * at or after `spawnedAt`. Looks in the projectDir for cwd, picks the file- * with the most-recent mtime (the one this session wrote), and returns the- * final text content block.- */-function extractLastAssistantText(cwd: string, spawnedAt: number): string | null {- try {- const dir = projectDir(cwd);- if (!existsSync(dir)) return null;-- const candidates: { f: string; mtime: number }[] = [];- for (const f of readdirSync(dir)) {- if (!f.endsWith('.jsonl')) continue;- try {- const mtime = statSync(path.join(dir, f)).mtimeMs;- // Include files touched up to 5 s before spawn to handle pre-existing- // sessions; we want the one written by this call, so we sort by mtime- // and take the newest.- if (mtime >= spawnedAt - 5000) candidates.push({ f, mtime });- } catch { /* file removed between readdir and stat — skip */ }- }- if (!candidates.length) return null;- candidates.sort((a, b) => b.mtime - a.mtime);-- const lines = readFileSync(path.join(dir, candidates[0].f), 'utf8').split('\n');- for (let i = lines.length - 1; i >= 0; i--) {- const trimmed = lines[i].trim();- if (!trimmed) continue;- let rec: { type?: unknown; message?: { content?: unknown[] } };- try { rec = JSON.parse(trimmed); } catch { continue; }- if (rec.type !== 'assistant') continue;- const content = rec.message?.content;- if (!Array.isArray(content)) continue;- for (let j = content.length - 1; j >= 0; j--) {- const block = content[j] as { type?: unknown; text?: unknown };- if (block.type === 'text' && typeof block.text === 'string' && block.text.trim()) {- return block.text.trim();- }- }- }- return null;- } catch { return null; }-}--export function enrichMessage(req: EnrichRequest): Promise<EnrichResult> {- return new Promise((resolve) => {- const message = (req.message ?? '').trim();- if (!message) { resolve({ ok: false, error: 'empty message' }); return; }- if (!req.cwd || !existsSync(req.cwd)) {- resolve({ ok: false, error: `working directory does not exist: ${req.cwd}` });- return;- }-- const binary = (req.command || 'claude').trim().split(/\s+/)[0] || 'claude';- const exe = resolveCommand(binary);- const repos = (req.repos ?? []).filter((r) => r && existsSync(r) && r !== req.cwd);- const taskPrompt = buildTaskPrompt(message, req.cwd, repos);-- const args: string[] = [- '--model', req.model || ASSISTANT_MODEL,- '--permission-mode', 'bypassPermissions',- '--disallowedTools', 'Edit', 'Write', 'NotebookEdit',- ];- // --add-dir follows --disallowedTools; the leading -- signals the end of- // the variadic tool list to the CLI parser.- for (const r of repos) { args.push('--add-dir', r); }-- const spawnedAt = Date.now();- let ptyProc: pty.IPty;- try {- ptyProc = pty.spawn(exe, args, {- name: 'xterm-color',- cols: 220,- rows: 50,- cwd: req.cwd,- env: {- ...process.env,- PATH: userShellPath(),- ...(req.env ?? {}),- } as Record<string, string>,- });- } catch (e) {- resolve({ ok: false, error: e instanceof Error ? e.message : String(e) });- return;- }-- let settled = false;- let promptSent = false;- let bootTimer: NodeJS.Timeout | null = null;- let idleTimer: NodeJS.Timeout | null = null;- // Declared before finish() so the closure can reference them.- let bootMaxTimer: NodeJS.Timeout;- let globalTimer: NodeJS.Timeout;-- const kill = () => { try { ptyProc.kill(); } catch { /* noop */ } };-- const finish = (r: EnrichResult) => {- if (settled) return;- settled = true;- if (bootTimer) { clearTimeout(bootTimer); bootTimer = null; }- if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; }- clearTimeout(bootMaxTimer);- clearTimeout(globalTimer);- kill();- resolve(r);- };-- const captureAndFinish = () => {- const text = extractLastAssistantText(req.cwd, spawnedAt);- finish(text- ? { ok: true, prompt: text }- : { ok: false, error: 'no assistant response found in transcript' });- };-- const sendPrompt = () => {- if (settled || promptSent) return;- promptSent = true;- if (bootTimer) { clearTimeout(bootTimer); bootTimer = null; }- // Bracketed paste + enter (same mechanism as submitToPty in useHive.ts).- ptyProc.write(`\x1b[200~${taskPrompt}\x1b[201~`);- setTimeout(() => { if (!settled) ptyProc.write('\r'); }, 140);- };-- bootMaxTimer = setTimeout(sendPrompt, BOOT_MAX_MS);- globalTimer = setTimeout(- () => finish({ ok: false, error: 'enrichment timed out' }),- req.timeoutMs ?? DEFAULT_TIMEOUT_MS,- );-- ptyProc.onData(() => {- if (!promptSent) {- // Boot phase: reset quiet timer on every byte; send prompt once quiet.- if (bootTimer) clearTimeout(bootTimer);- bootTimer = setTimeout(sendPrompt, BOOT_QUIET_MS);- } else {- // Response phase: reset idle timer; capture once output goes quiet.- if (idleTimer) clearTimeout(idleTimer);- idleTimer = setTimeout(captureAndFinish, IDLE_SETTLE_MS);- }- });-- // If the session exits cleanly before we detect idle, try to capture anyway.- ptyProc.onExit(() => { if (!settled) captureAndFinish(); });+export async function enrichMessage(req: EnrichRequest): Promise<EnrichResult> {+ const message = (req.message ?? '').trim();+ if (!message) return { ok: false, error: 'empty message' };+ if (!req.cwd || !existsSync(req.cwd)) {+ return { ok: false, error: `working directory does not exist: ${req.cwd}` };+ }++ const repos = (req.repos ?? []).filter((r) => r && existsSync(r) && r !== req.cwd);+ const taskPrompt = buildTaskPrompt(message, req.cwd, repos);++ const result = await runHiddenClaude(taskPrompt, {+ model: req.model || ASSISTANT_MODEL,+ cwd: req.cwd,+ command: req.command,+ disallowedTools: ['Edit', 'Write', 'NotebookEdit'],+ addDirs: repos,+ timeoutMs: req.timeoutMs,+ env: req.env,});++ if (result.ok && result.text) return { ok: true, prompt: result.text };+ return { ok: false, error: result.error };}diff --git a/src/main/hiddenClaude.ts b/src/main/hiddenClaude.tsnew file mode 100644index 00000000..76032171--- /dev/null+++ b/src/main/hiddenClaude.ts@@ -0,0 +1,197 @@+import * as pty from 'node-pty';+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import path from 'node:path';+import { resolveCommand, userShellPath } from './shellEnv';+import { projectDir } from './transcript';++/**+ * Shared helper: run a HIDDEN interactive claude session (ephemeral PTY) and+ * return the assistant's final text response.+ *+ * "Hidden" means: not added to the PtyManager, not emitted to the renderer,+ * not visible in the agent list or OfficeFloor scene. Each call spawns its own+ * session and kills it after capture — no /clear needed, no context bleed.+ *+ * Uses an interactive PTY (not `claude -p`) so calls draw from the user's+ * normal interactive plan quota, not the Agent SDK credit that moves to a+ * separate claim-required pool from 2026-06-15.+ *+ * Session lifecycle:+ * spawn → boot-quiet detect → bracketed-paste prompt + \r → idle-settle →+ * transcript JSONL extract (last assistant text block) → kill+ */++/** ms of PTY silence that signals the TUI is ready for input (boot complete). */+const BOOT_QUIET_MS = 1500;++export interface HiddenClaudeOptions {+ /** Model to use (e.g. 'claude-haiku-4-5'). */+ model: string;+ /** Working directory for the claude session. */+ cwd: string;+ /** Base claude command/binary. Defaults to 'claude'. */+ command?: string;+ /** Tools the session is forbidden to use. Defaults to ['Edit','Write','NotebookEdit']. */+ disallowedTools?: string[];+ /** Directories added via --add-dir (for context gathering). */+ addDirs?: string[];+ /** Hard cap ms before forcing prompt send regardless of boot activity. Default 7000. */+ bootCapMs?: number;+ /** ms of PTY silence after the prompt that signals response is complete. Default 3500. */+ idleMs?: number;+ /** Total timeout ms. Default 180000. */+ timeoutMs?: number;+ /** Extra env merged over the resolved shell env (e.g. the shared MemPalace). */+ env?: Record<string, string>;+}++export interface HiddenClaudeResult {+ ok: boolean;+ /** The assistant's final text response (stripped of any TUI framing). */+ text?: string;+ error?: string;+}++/**+ * Extract the last assistant text block from the transcript JSONL written+ * at or after `spawnedAt`. Reuses projectDir() from transcript.ts.+ */+function extractLastAssistantText(cwd: string, spawnedAt: number): string | null {+ try {+ const dir = projectDir(cwd);+ if (!existsSync(dir)) return null;++ const candidates: { f: string; mtime: number }[] = [];+ for (const f of readdirSync(dir)) {+ if (!f.endsWith('.jsonl')) continue;+ try {+ const mtime = statSync(path.join(dir, f)).mtimeMs;+ // 5 s slack: include files that already existed at spawn but were+ // updated by this session. Sort by mtime and take the newest.+ if (mtime >= spawnedAt - 5000) candidates.push({ f, mtime });+ } catch { /* file removed between readdir and stat — skip */ }+ }+ if (!candidates.length) return null;+ candidates.sort((a, b) => b.mtime - a.mtime);++ const lines = readFileSync(path.join(dir, candidates[0].f), 'utf8').split('\n');+ for (let i = lines.length - 1; i >= 0; i--) {+ const trimmed = lines[i].trim();+ if (!trimmed) continue;+ let rec: { type?: unknown; message?: { content?: unknown[] } };+ try { rec = JSON.parse(trimmed); } catch { continue; }+ if (rec.type !== 'assistant') continue;+ const content = rec.message?.content;+ if (!Array.isArray(content)) continue;+ for (let j = content.length - 1; j >= 0; j--) {+ const block = content[j] as { type?: unknown; text?: unknown };+ if (block.type === 'text' && typeof block.text === 'string' && block.text.trim()) {+ return block.text.trim();+ }+ }+ }+ return null;+ } catch { return null; }+}++export function runHiddenClaude(prompt: string, opts: HiddenClaudeOptions): Promise<HiddenClaudeResult> {+ return new Promise((resolve) => {+ if (!prompt.trim()) { resolve({ ok: false, error: 'empty prompt' }); return; }+ if (!opts.cwd || !existsSync(opts.cwd)) {+ resolve({ ok: false, error: `cwd does not exist: ${opts.cwd}` });+ return;+ }++ const binary = (opts.command || 'claude').trim().split(/\s+/)[0] || 'claude';+ const exe = resolveCommand(binary);+ const disallowed = opts.disallowedTools ?? ['Edit', 'Write', 'NotebookEdit'];+ const addDirs = (opts.addDirs ?? []).filter((d) => d && existsSync(d));++ const args: string[] = [+ '--model', opts.model,+ '--permission-mode', 'bypassPermissions',+ '--disallowedTools', ...disallowed,+ ];+ for (const d of addDirs) { args.push('--add-dir', d); }++ const bootCapMs = opts.bootCapMs ?? 7000;+ const idleMs = opts.idleMs ?? 3500;+ const timeoutMs = opts.timeoutMs ?? 180_000;++ const spawnedAt = Date.now();+ let ptyProc: pty.IPty;+ try {+ ptyProc = pty.spawn(exe, args, {+ name: 'xterm-color',+ cols: 220,+ rows: 50,+ cwd: opts.cwd,+ env: {+ ...process.env,+ PATH: userShellPath(),+ ...(opts.env ?? {}),+ } as Record<string, string>,+ });+ } catch (e) {+ resolve({ ok: false, error: e instanceof Error ? e.message : String(e) });+ return;+ }++ let settled = false;+ let promptSent = false;+ let bootTimer: NodeJS.Timeout | null = null;+ let idleTimer: NodeJS.Timeout | null = null;+ let bootMaxTimer: NodeJS.Timeout;+ let globalTimer: NodeJS.Timeout;++ const kill = () => { try { ptyProc.kill(); } catch { /* noop */ } };++ const finish = (r: HiddenClaudeResult) => {+ if (settled) return;+ settled = true;+ if (bootTimer) { clearTimeout(bootTimer); bootTimer = null; }+ if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; }+ clearTimeout(bootMaxTimer);+ clearTimeout(globalTimer);+ kill();+ resolve(r);+ };++ const captureAndFinish = () => {+ const text = extractLastAssistantText(opts.cwd, spawnedAt);+ finish(text+ ? { ok: true, text }+ : { ok: false, error: 'no assistant response found in transcript' });+ };++ const sendPrompt = () => {+ if (settled || promptSent) return;+ promptSent = true;+ if (bootTimer) { clearTimeout(bootTimer); bootTimer = null; }+ // Bracketed paste + enter — same mechanism as submitToPty in useHive.ts.+ ptyProc.write(`\x1b[200~${prompt}\x1b[201~`);+ setTimeout(() => { if (!settled) ptyProc.write('\r'); }, 140);+ };++ bootMaxTimer = setTimeout(sendPrompt, bootCapMs);+ globalTimer = setTimeout(+ () => finish({ ok: false, error: 'hidden session timed out' }),+ timeoutMs,+ );++ ptyProc.onData(() => {+ if (!promptSent) {+ // Boot phase: reset quiet timer; send prompt once output goes quiet.+ if (bootTimer) clearTimeout(bootTimer);+ bootTimer = setTimeout(sendPrompt, BOOT_QUIET_MS);+ } else {+ // Response phase: reset idle timer; capture when output settles.+ if (idleTimer) clearTimeout(idleTimer);+ idleTimer = setTimeout(captureAndFinish, idleMs);+ }+ });++ // Session exited cleanly before idle — try to capture the transcript anyway.+ ptyProc.onExit(() => { if (!settled) captureAndFinish(); });+ });+}diff --git a/src/main/reflect.ts b/src/main/reflect.tsindex 10222336..7be0870e 100644--- a/src/main/reflect.ts+++ b/src/main/reflect.ts@@ -20,13 +20,12 @@** Runs in the Electron main process.*/-import { spawn } from 'node:child_process';import {existsSync, statSync, readdirSync, readFileSync, writeFileSync,mkdirSync, copyFileSync, renameSync, openSync, fsyncSync, closeSync} from 'node:fs';import { join, dirname } from 'node:path';-import { resolveCommand, userShellPath } from './shellEnv';+import { runHiddenClaude } from './hiddenClaude';/** Total memory.md budget — mirrors the janitor's CONTEXT_BUDGET_BYTES (128 KB). */const BUDGET_BYTES = 131_072;@@ -259,63 +258,40 @@ export class MemoryReflector {// — the headless LLM call (the only non-deterministic step) —- private summarize(+ private async summarize(home: string, condensed: string | null, evict: Section[], pinned: string | null): Promise<{ condensed: string; hoist: string[] }> {- return new Promise((resolve, reject) => {- const binary = (this.getCommand() || 'claude').trim().split(/\s+/)[0] || 'claude';- const exe = resolveCommand(binary);- const evictText = evict.map((s) => `${s.heading}\n${s.body}`).join('\n\n').trim();- const prompt = [- CONDENSE_SYSTEM,- '',- '--- INPUT ---',- '(A) CURRENT CONDENSED SUMMARY:',- condensed?.trim() || '(none yet)',- '',- '(B) OLDER SECTIONS BEING EVICTED:',- evictText || '(none)',- '',- '(C) PINNED DURABLE FACTS (context only — do not rewrite):',- pinned?.trim() || '(none)'- ].join('\n');-- const args = [- '-p', prompt,- '--model', CONDENSE_MODEL,- '--output-format', 'json',- '--permission-mode', 'bypassPermissions',- // Pure text transform — it must never touch the repo or shell out.- '--disallowedTools', 'Edit', 'Write', 'NotebookEdit', 'Bash'- ];-- let child;- try {- child = spawn(exe, args, {- cwd: home,- env: { ...process.env, PATH: userShellPath(), ...this.getMemoryEnv() } as Record<string, string>,- stdio: ['ignore', 'pipe', 'pipe']- });- } catch (e) { reject(e); return; }-- let stdout = '';- let stderr = '';- let settled = false;- const finish = (fn: () => void): void => { if (settled) return; settled = true; clearTimeout(timer); fn(); };- const timer = setTimeout(() => {- try { child.kill('SIGKILL'); } catch { /* noop */ }- finish(() => reject(new Error('condense timed out')));- }, DEFAULT_TIMEOUT_MS);-- child.stdout?.on('data', (d) => { stdout += d.toString(); });- child.stderr?.on('data', (d) => { stderr += d.toString(); });- child.on('error', (e) => finish(() => reject(e)));- child.on('close', (code) => finish(() => {- const parsed = parseSummary(stdout);- if (parsed) { resolve(parsed); return; }- reject(new Error(stderr.trim() || `condense exited ${code ?? '?'} with no parseable JSON`));- }));+ const evictText = evict.map((s) => `${s.heading}\n${s.body}`).join('\n\n').trim();+ const prompt = [+ CONDENSE_SYSTEM,+ '',+ '--- INPUT ---',+ '(A) CURRENT CONDENSED SUMMARY:',+ condensed?.trim() || '(none yet)',+ '',+ '(B) OLDER SECTIONS BEING EVICTED:',+ evictText || '(none)',+ '',+ '(C) PINNED DURABLE FACTS (context only — do not rewrite):',+ pinned?.trim() || '(none)'+ ].join('\n');++ const result = await runHiddenClaude(prompt, {+ model: CONDENSE_MODEL,+ cwd: home,+ command: this.getCommand(),+ // Pure text transform — must never touch the repo or shell out.+ disallowedTools: ['Edit', 'Write', 'NotebookEdit', 'Bash'],+ env: this.getMemoryEnv(),+ timeoutMs: DEFAULT_TIMEOUT_MS,});++ if (!result.ok || !result.text) {+ throw new Error(result.error ?? 'condense: hidden session returned no text');+ }+ const parsed = parseSummary(result.text);+ if (!parsed) throw new Error('condense: response contained no parseable JSON');+ return parsed;}}