Skip to content
Open
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
23 changes: 11 additions & 12 deletions src/core/hookServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import type { ControlRegistry } from '../main/control';
import type { CircuitBreaker } from '../main/breaker';
import { estimateCostUsd } from '../main/pricing';
import { validateHookEvent } from '../shared/hookEvents';
import { isIdleWaitNotification } from '../shared/hookClassify';
import type { HookSink } from '../main/hookSink';

import { liveModelOf } from '../shared/liveModel';
Expand Down Expand Up @@ -196,10 +197,11 @@ export class HookServer {
/** Standing goal text for an agent (from the durable roster). Optional so
* tests can omit it; when set, injected at session start and when changed. */
private getStandingGoal?: (agentId: string) => string | null,
/** Optional observer of every hook boundary (agentId, event, message). The
* worker inbox-wake watchdog (workerWake.ts) feeds on this to learn when an
* agent is parked on a permission/HITL prompt so it never types into it. */
private onEvent?: (agentId: string | undefined, event: string, message: string | undefined, tool?: string, source?: string) => void
/** Optional observer of every hook boundary (agentId, event, message, tool,
* source, notificationType). The worker inbox-wake watchdog (workerWake.ts)
* feeds on this to learn when an agent is parked on a permission/HITL
* prompt so it never types into it. */
private onEvent?: (agentId: string | undefined, event: string, message: string | undefined, tool?: string, source?: string, notificationType?: unknown) => void
) {}

/** Bind the hook socket. Asynchronous and safe to call repeatedly — a
Expand Down Expand Up @@ -579,14 +581,14 @@ export class HookServer {
const agentId = p.agent_id ?? undefined;
const event = p.hook_event_name ?? 'Unknown';
// Autosend proof first, before any other work here can delay it.
this.proof.note(agentId, event, p.prompt, { message: p.message, tool: p.tool_name });
this.proof.note(agentId, event, p.prompt, { message: p.message, tool: p.tool_name, notificationType: p.notification_type });
// The session and turn events as they arrive, so a hook lost in the CLI can be told from one lost here.
// Tool events are left out: they add nothing to delivery and come by the hundred. A prompt's tail
// length only, never its text.
if (LOGGED_HOOKS.has(event)) try {
this.hive.appendLog({ kind: 'hook-seen', event, agentId: agentId ?? null, ...(event === 'UserPromptSubmit' && typeof p.prompt === 'string' ? { tailLen: promptTail(p.prompt).length } : {}) });
} catch { /* the log never affects the reply */ }
this.onEvent?.(agentId, event, p.message, p.tool_name, p.source);
this.onEvent?.(agentId, event, p.message, p.tool_name, p.source, p.notification_type);
try {
this.onFacts?.({ agentId, event, tool: p.tool_name, toolInput: p.tool_input, sessionId: p.session_id, agentType: p.agent_type, source: p.source });
} catch { /* an observer must never affect the hook reply */ }
Expand Down Expand Up @@ -860,12 +862,9 @@ export class HookServer {
// A Notification hook that means "the agent is blocked waiting for the user"
// (idle prompt) deserves a desktop toast too — distinct from a permission
// request, which surfaces natively in the agent's own Claude Code session
// (approvable remotely via /remote-control).
if (
event === 'Notification' &&
(p.notification_type === 'idle' ||
(p.message ?? '').toLowerCase().includes('waiting for your input'))
) {
// (approvable remotely via /remote-control). Claude Code tags this one
// `idle_prompt`; isIdleWaitNotification shares the watchdog's type rules.
if (isIdleWaitNotification(event, p.message, p.notification_type)) {
this.notify(agentId ?? 'Agent', p.message ?? 'needs your attention');
}

Expand Down
15 changes: 5 additions & 10 deletions src/main/hookProof.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* removed (promptTail): enough to recognise our own text, never the message.
*/
import { promptTail, tailMatches } from '../shared/providerAutomation';
import { classifyHook } from '../shared/hookClassify';

/** Events that mean a prompt was taken or a turn is running. Only these are
* proof of activity, and only these show the hook channel works (gate G1,
Expand Down Expand Up @@ -35,19 +36,13 @@ interface AgentHooks {
/**
* A PROMPT THAT ASKS THE PERSON IS OPEN (trigger-prompt-058, god, 9 Nov 2026: a launch desk trigger's Enter approved a
* subagent's permission prompt that had waited 3 hours, and its own text was lost). Opened by a Notification that needs
* the person (a permission, an approval, a confirm: agentState.ts stateAfter's rule) or by the AskUserQuestion tool.
* the person or by the AskUserQuestion tool. A known Claude notification_type decides; without one, the shared
* HITL-first message rule in hookClassify.ts decides.
* Closed only by what answers it: the tool running or failing (PostToolUse, PostToolUseFailure), a prompt sent
* (UserPromptSubmit) or a new session (SessionStart). Not by a Stop: a background subagent's prompt stays open after
* its parent's turn ends. Not by the quiet "waiting for your input" Notification, which also comes while it is open.
*/
const ASKS_PERSON = /permission|approve|approval|confirm|needs your/i;
const QUIET = /waiting for your input|is idle|waiting for input/i;
const ASK_CLOSED: ReadonlySet<string> = new Set(['PostToolUse', 'PostToolUseFailure', 'UserPromptSubmit', 'SessionStart']);
/** A Notification's words that ask the person, never the quiet one. */
export function asksPerson(message: string | undefined): boolean {
const m = (message ?? '').trim();
return !!m && ASKS_PERSON.test(m) && !QUIET.test(m);
}

/**
* A COMPACTION IS RUNNING. From PreCompact until one of these comes after it: the
Expand All @@ -64,14 +59,14 @@ export class HookProofRecord {

constructor(private now: () => number = Date.now) {}

note(agentId: string | undefined, event: string, prompt?: unknown, extra?: { message?: unknown; tool?: unknown }): void {
note(agentId: string | undefined, event: string, prompt?: unknown, extra?: { message?: unknown; tool?: unknown; notificationType?: unknown }): void {
if (!agentId) return;
const at = this.now();
let a = this.byAgent.get(agentId);
if (!a) { a = { lastAt: new Map(), turnAt: 0, prompts: [], askOpenAt: 0 }; this.byAgent.set(agentId, a); }
a.lastAt.set(event, at);
if (TURN_EVENTS.has(event)) a.turnAt = at;
if (event === 'Notification' && asksPerson(typeof extra?.message === 'string' ? extra.message : undefined)) a.askOpenAt = at;
if (classifyHook(event, extra?.message, extra?.notificationType) === 'needsHuman') a.askOpenAt = at;
else if (event === 'PreToolUse' && extra?.tool === 'AskUserQuestion') a.askOpenAt = at;
else if (ASK_CLOSED.has(event)) a.askOpenAt = 0;
if (event === 'UserPromptSubmit' && typeof prompt === 'string') {
Expand Down
2 changes: 1 addition & 1 deletion src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -875,7 +875,7 @@ const hookServer = new HookServer(
// always true).
// 0.5.6: the same stream tells wakeFiling when a turn ends (Stop), which is
// when the mail that turn's wake printed is filed.
(agentId, event, message, tool, source) => { loginPastOnHook(agentId, event); if (agentId && event !== 'Status') agentDemand.touch(agentId); workerWake.noteHook(agentId, event, message, undefined, tool); wakeFiling.noteHook(agentId, event, source); }
(agentId, event, message, tool, source, notificationType) => { loginPastOnHook(agentId, event); if (agentId && event !== 'Status') agentDemand.touch(agentId); workerWake.noteHook(agentId, event, message, undefined, tool, notificationType); wakeFiling.noteHook(agentId, event, source); }
);
// The toast itself is Electron's; the hook server decides when.
hookServer.setNotifier((title, body) => {
Expand Down
29 changes: 5 additions & 24 deletions src/main/workerWake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@

import { OpenQuestionTracker } from '../shared/openQuestion';
import { TURN_EVENTS } from './hookProof';
import { classifyHook } from '../shared/hookClassify';

export { classifyHook, type HookClass } from '../shared/hookClassify';

/** The exact nudge the renderer's inbox-wake loop would have typed. */
export const WORKER_WAKE_NUDGE =
Expand Down Expand Up @@ -82,28 +85,6 @@ export const WORKER_WAKE_OPEN_TURN_MS = 15 * 60_000;
/** Minimum age of pending mail before a held worker is reported in the log. */
export const WORKER_WAKE_REPORT_MS = 60_000;

/** A hook event message that means "the agent needs the human" — permission /
* approve / confirm prompts (mirrors the renderer's needsHuman detection in
* useHive.ts). Anything matching the idle-waiting shape is NOT a HITL hold. */
export type HookClass = 'needsHuman' | 'idle' | null;

export function classifyHook(event: string | undefined, message: string | undefined): HookClass {
if (event === 'Notification') {
const msg = (message ?? '').toLowerCase();
const idleWaiting = !msg
|| msg.includes('waiting for your input')
|| msg.includes('is idle')
|| msg.includes('waiting for input');
const needsHuman = msg.includes('permission')
|| msg.includes('approve')
|| msg.includes('confirm')
|| msg.includes('needs your');
if (needsHuman && !idleWaiting) return 'needsHuman';
return 'idle';
}
return null;
}

/** A hook event that proves the CLI took a turn: the activity signal every
* engine the harness shims produces, unlike telemetry, which only Claude Code
* exports. SessionStart is the CLI coming up, not a turn: a worker whose boot
Expand Down Expand Up @@ -239,15 +220,15 @@ export class WorkerWakeWatchdog {
}

/** Feed hook events (from HookServer) so a HITL prompt blocks nudges. */
noteHook(agentId: string | undefined, event: string | undefined, message: string | undefined, at = Date.now(), tool?: string): void {
noteHook(agentId: string | undefined, event: string | undefined, message: string | undefined, at = Date.now(), tool?: string, notificationType?: unknown): void {
if (!agentId) return;
this.questions.note(agentId, event, tool);
this.hookSeenAt.set(agentId, at);
if (isTurnHook(event) && at > (this.lastTurnHookAt.get(agentId) ?? 0)) {
this.lastTurnHookAt.set(agentId, at);
this.lastTurnHookEvent.set(agentId, event as string);
}
if (classifyHook(event, message) === 'needsHuman') this.lastHumanNeedsAt.set(agentId, at);
if (classifyHook(event, message, notificationType) === 'needsHuman') this.lastHumanNeedsAt.set(agentId, at);
else if (event && TURN_EVENTS.has(event)) this.lastTurnAt.set(agentId, at);
}

Expand Down
23 changes: 6 additions & 17 deletions src/renderer/src/hooks/useHive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { effectiveGodCommand } from '../../../shared/godCommand';
import { agentExitOf } from '../../../shared/agentExit';
import { godRunning, refusedBecauseAlive } from '../../../shared/godBoot';
import { resolveGodName } from '../../../shared/godIdentity';
import { classifyHook } from '../../../shared/hookClassify';
import { resolveResponder } from '../../../shared/responder';
import { RESPONSE_STYLE_TAG, renderResponseStyle } from '../../../shared/responseStyle';
import { acquireTerminal, resetTerminal, isTerminalAutomationSafe, terminalAutomationBlockFor } from '@/components/terminalPool';
Expand Down Expand Up @@ -709,23 +710,11 @@ export function useHive(config: HarnessConfig | null): void {
if (e.event === 'Stop' && codexSizeDue.current.has(e.agentId)) void queueCodexSizeClear(e.agentId);
}
} else if (e.event === 'Notification' && !breakerArmed) {
// Claude Code fires Notification for two very different situations:
// 1. it genuinely needs the human (a permission / approval prompt), or
// 2. the prompt has merely gone idle ("Claude is waiting for your
// input") — i.e. the agent answered and has nothing queued.
// Only (1) is a real "needs you". Treating (2) as blocked made Michael
// march to the door with a red "!" right after finishing, so detect the
// idle case and let him linger on the floor instead.
const msg = (e.message ?? '').toLowerCase();
const idleWaiting = !msg
|| msg.includes('waiting for your input')
|| msg.includes('is idle')
|| msg.includes('waiting for input');
const needsHuman = msg.includes('permission')
|| msg.includes('approve')
|| msg.includes('confirm')
|| msg.includes('needs your');
if (needsHuman && !idleWaiting) {
// Known Claude notification types are authoritative. Legacy/unknown
// notifications use the shared text fallback so the watchdog and UI
// cannot disagree about HITL versus ordinary idle notifications.
const hookClass = classifyHook(e.event, e.message, e.notificationType);
if (hookClass === 'needsHuman') {
// Only the god agent escalates to the human; sub-agents are autonomous
// and read as "waiting" (parked on god, not on you).
updateAgent(e.agentId, { status: self.isGod ? 'blocked' : 'waiting' });
Expand Down
67 changes: 67 additions & 0 deletions src/shared/hookClassify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
export type HookClass = 'needsHuman' | 'idle' | null;

const CLAUDE_BLOCKING_NOTIFICATION_TYPES: ReadonlySet<string> = new Set([
'permission_prompt',
'elicitation_dialog',
'elicitation_url_dialog',
'agent_needs_input'
]);

const CLAUDE_IDLE_NOTIFICATION_TYPES: ReadonlySet<string> = new Set([
'idle_prompt'
]);

/** A notification type from before Claude's typed notifications, still passed
* through unchanged by engine shims such as Grok's. It only means "toast";
* classification falls back to the message as for any unknown type. */
const LEGACY_IDLE_TOAST_TYPES: ReadonlySet<string> = new Set([
'idle'
]);

/** Whole words only: "approved" or "confirmed" in an idle report must not open
* an ask, because nothing closes one on an idle agent. */
const HITL_MESSAGE_MARKERS = /\b(?:permissions?|approve|approval|confirm|confirmation|needs your)\b/;

function normalizeString(value: unknown): string {
return typeof value === 'string' ? value.trim().toLowerCase() : '';
}

/** Classify Notification hooks consistently for the renderer, WorkerWake and hookProof/ptySubmit.
* Known Claude notification types are authoritative. Legacy and unknown
* types fall back to message markers, where a HITL signal wins over generic
* idle wording. Untrusted runtime field shapes safely normalize to empty. */
export function classifyHook(
event: unknown,
message?: unknown,
notificationType?: unknown
): HookClass {
if (event !== 'Notification') return null;

const type = normalizeString(notificationType);
if (CLAUDE_BLOCKING_NOTIFICATION_TYPES.has(type)) return 'needsHuman';
if (CLAUDE_IDLE_NOTIFICATION_TYPES.has(type)) return 'idle';

const msg = normalizeString(message);
return HITL_MESSAGE_MARKERS.test(msg) ? 'needsHuman' : 'idle';
}

/** Whether a Notification is the "done, waiting for you" idle prompt that
* earns a desktop toast. Not every non-HITL notification qualifies: an
* auth_success or an empty message classifies as idle but is no reason to
* ping the person. A known Claude type decides; without one, the idle
* wording counts only when the message is not a HITL prompt, which surfaces
* natively in the agent's own session instead. */
export function isIdleWaitNotification(
event: unknown,
message?: unknown,
notificationType?: unknown
): boolean {
if (event !== 'Notification') return false;

const type = normalizeString(notificationType);
if (CLAUDE_IDLE_NOTIFICATION_TYPES.has(type) || LEGACY_IDLE_TOAST_TYPES.has(type)) return true;
if (CLAUDE_BLOCKING_NOTIFICATION_TYPES.has(type)) return false;

return classifyHook(event, message, type) === 'idle'
&& normalizeString(message).includes('waiting for your input');
}
71 changes: 71 additions & 0 deletions test/hook-proof.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const loadTs = require('./load-ts.cjs');

const { HookProofRecord } = loadTs('src/main/hookProof.ts');

test('a mixed permission and idle notification opens the ask without a type', () => {
const proof = new HookProofRecord(() => 1_000);
proof.note('alice', 'Notification', undefined, { message: 'Permission required — waiting for your input' });
assert.equal(proof.askOpen('alice'), true);
});

test('a permission_prompt opens the ask despite idle wording', () => {
const proof = new HookProofRecord(() => 1_000);
proof.note('alice', 'Notification', undefined, {
message: 'Claude is waiting for your input',
notificationType: 'permission_prompt'
});
assert.equal(proof.askOpen('alice'), true);
});

test('a quiet notification without a type does not open the ask', () => {
const proof = new HookProofRecord(() => 1_000);
proof.note('alice', 'Notification', undefined, { message: 'Claude is waiting for your input' });
assert.equal(proof.askOpen('alice'), false);
});

test('an idle_prompt does not open the ask despite permission wording', () => {
const proof = new HookProofRecord(() => 1_000);
proof.note('alice', 'Notification', undefined, {
message: 'Permission required — waiting for your input',
notificationType: 'idle_prompt'
});
assert.equal(proof.askOpen('alice'), false);
});

test('approval wording opens the ask without a type', () => {
const proof = new HookProofRecord(() => 1_000);
proof.note('alice', 'Notification', undefined, { message: 'Tool use needs approval' });
assert.equal(proof.askOpen('alice'), true);
});

test('a quiet notification leaves an ask open until PostToolUse closes it', () => {
let now = 1_000;
const proof = new HookProofRecord(() => now);
proof.note('alice', 'Notification', undefined, { message: 'Permission required' });
assert.equal(proof.askOpen('alice'), true);
now += 1_000;
proof.note('alice', 'Notification', undefined, { message: 'Claude is waiting for your input' });
assert.equal(proof.askOpen('alice'), true);
now += 1_000;
proof.note('alice', 'PostToolUse');
assert.equal(proof.askOpen('alice'), false);
});

test('non-string message and notificationType values never throw', () => {
for (const message of [123, {}, null]) {
for (const notificationType of [123, {}, null]) {
const proof = new HookProofRecord(() => 1_000);
assert.doesNotThrow(() => proof.note('alice', 'Notification', undefined, { message, notificationType }));
assert.equal(proof.askOpen('alice'), false);
}
}
});

test('a past-tense report with idle wording does not open the ask', () => {
// Nothing closes an ask on an idle agent, so a false open would hold every send while the screen is unreadable.
const proof = new HookProofRecord(() => 1_000);
proof.note('alice', 'Notification', undefined, { message: 'Changes approved — waiting for your input' });
assert.equal(proof.askOpen('alice'), false);
});
Loading
Loading